user.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package db
  5. import (
  6. "bytes"
  7. "context"
  8. "crypto/sha256"
  9. "crypto/subtle"
  10. "encoding/hex"
  11. "fmt"
  12. "image"
  13. _ "image/jpeg"
  14. "image/png"
  15. "os"
  16. "path/filepath"
  17. "strings"
  18. "time"
  19. "unicode/utf8"
  20. "github.com/nfnt/resize"
  21. "github.com/unknwon/com"
  22. "golang.org/x/crypto/pbkdf2"
  23. log "unknwon.dev/clog/v2"
  24. "xorm.io/xorm"
  25. "github.com/gogs/git-module"
  26. "gogs.io/gogs/internal/avatar"
  27. "gogs.io/gogs/internal/conf"
  28. "gogs.io/gogs/internal/db/errors"
  29. "gogs.io/gogs/internal/errutil"
  30. "gogs.io/gogs/internal/strutil"
  31. "gogs.io/gogs/internal/tool"
  32. "gogs.io/gogs/internal/userutil"
  33. )
  34. // TODO(unknwon): Delete me once refactoring is done.
  35. func (u *User) BeforeInsert() {
  36. u.CreatedUnix = time.Now().Unix()
  37. u.UpdatedUnix = u.CreatedUnix
  38. }
  39. // TODO(unknwon): Refactoring together with methods that do updates.
  40. func (u *User) BeforeUpdate() {
  41. if u.MaxRepoCreation < -1 {
  42. u.MaxRepoCreation = -1
  43. }
  44. u.UpdatedUnix = time.Now().Unix()
  45. }
  46. // TODO(unknwon): Delete me once refactoring is done.
  47. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  48. switch colName {
  49. case "created_unix":
  50. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  51. case "updated_unix":
  52. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  53. }
  54. }
  55. // NewGitSig generates and returns the signature of given user.
  56. func (u *User) NewGitSig() *git.Signature {
  57. return &git.Signature{
  58. Name: u.DisplayName(),
  59. Email: u.Email,
  60. When: time.Now(),
  61. }
  62. }
  63. // EncodePassword encodes password to safe format.
  64. func (u *User) EncodePassword() {
  65. newPasswd := pbkdf2.Key([]byte(u.Password), []byte(u.Salt), 10000, 50, sha256.New)
  66. u.Password = fmt.Sprintf("%x", newPasswd)
  67. }
  68. // ValidatePassword checks if given password matches the one belongs to the user.
  69. func (u *User) ValidatePassword(passwd string) bool {
  70. newUser := &User{Password: passwd, Salt: u.Salt}
  71. newUser.EncodePassword()
  72. return subtle.ConstantTimeCompare([]byte(u.Password), []byte(newUser.Password)) == 1
  73. }
  74. // UploadAvatar saves custom avatar for user.
  75. // FIXME: split uploads to different subdirs in case we have massive number of users.
  76. func (u *User) UploadAvatar(data []byte) error {
  77. img, _, err := image.Decode(bytes.NewReader(data))
  78. if err != nil {
  79. return fmt.Errorf("decode image: %v", err)
  80. }
  81. _ = os.MkdirAll(conf.Picture.AvatarUploadPath, os.ModePerm)
  82. fw, err := os.Create(userutil.CustomAvatarPath(u.ID))
  83. if err != nil {
  84. return fmt.Errorf("create custom avatar directory: %v", err)
  85. }
  86. defer fw.Close()
  87. m := resize.Resize(avatar.AVATAR_SIZE, avatar.AVATAR_SIZE, img, resize.NearestNeighbor)
  88. if err = png.Encode(fw, m); err != nil {
  89. return fmt.Errorf("encode image: %v", err)
  90. }
  91. return nil
  92. }
  93. // DeleteAvatar deletes the user's custom avatar.
  94. func (u *User) DeleteAvatar() error {
  95. avatarPath := userutil.CustomAvatarPath(u.ID)
  96. log.Trace("DeleteAvatar [%d]: %s", u.ID, avatarPath)
  97. if err := os.Remove(avatarPath); err != nil {
  98. return err
  99. }
  100. u.UseCustomAvatar = false
  101. return UpdateUser(u)
  102. }
  103. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  104. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  105. return Perms.Authorize(context.TODO(), u.ID, repo.ID, AccessModeAdmin,
  106. AccessModeOptions{
  107. OwnerID: repo.OwnerID,
  108. Private: repo.IsPrivate,
  109. },
  110. )
  111. }
  112. // IsWriterOfRepo returns true if user has write access to given repository.
  113. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  114. return Perms.Authorize(context.TODO(), u.ID, repo.ID, AccessModeWrite,
  115. AccessModeOptions{
  116. OwnerID: repo.OwnerID,
  117. Private: repo.IsPrivate,
  118. },
  119. )
  120. }
  121. // IsOrganization returns true if user is actually a organization.
  122. func (u *User) IsOrganization() bool {
  123. return u.Type == UserTypeOrganization
  124. }
  125. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  126. func (u *User) IsUserOrgOwner(orgId int64) bool {
  127. return IsOrganizationOwner(orgId, u.ID)
  128. }
  129. // IsPublicMember returns true if user public his/her membership in give organization.
  130. func (u *User) IsPublicMember(orgId int64) bool {
  131. return IsPublicMembership(orgId, u.ID)
  132. }
  133. // IsEnabledTwoFactor returns true if user has enabled two-factor authentication.
  134. func (u *User) IsEnabledTwoFactor() bool {
  135. return TwoFactors.IsUserEnabled(context.TODO(), u.ID)
  136. }
  137. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  138. return e.Where("uid=?", u.ID).Count(new(OrgUser))
  139. }
  140. // GetOrganizationCount returns count of membership of organization of user.
  141. func (u *User) GetOrganizationCount() (int64, error) {
  142. return u.getOrganizationCount(x)
  143. }
  144. // GetRepositories returns repositories that user owns, including private repositories.
  145. func (u *User) GetRepositories(page, pageSize int) (err error) {
  146. u.Repos, err = GetUserRepositories(&UserRepoOptions{
  147. UserID: u.ID,
  148. Private: true,
  149. Page: page,
  150. PageSize: pageSize,
  151. })
  152. return err
  153. }
  154. // GetRepositories returns mirror repositories that user owns, including private repositories.
  155. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  156. return GetUserMirrorRepositories(u.ID)
  157. }
  158. // GetOwnedOrganizations returns all organizations that user owns.
  159. func (u *User) GetOwnedOrganizations() (err error) {
  160. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  161. return err
  162. }
  163. // GetOrganizations returns all organizations that user belongs to.
  164. func (u *User) GetOrganizations(showPrivate bool) error {
  165. orgIDs, err := GetOrgIDsByUserID(u.ID, showPrivate)
  166. if err != nil {
  167. return fmt.Errorf("GetOrgIDsByUserID: %v", err)
  168. }
  169. if len(orgIDs) == 0 {
  170. return nil
  171. }
  172. u.Orgs = make([]*User, 0, len(orgIDs))
  173. if err = x.Where("type = ?", UserTypeOrganization).In("id", orgIDs).Find(&u.Orgs); err != nil {
  174. return err
  175. }
  176. return nil
  177. }
  178. // DisplayName returns full name if it's not empty,
  179. // returns username otherwise.
  180. func (u *User) DisplayName() string {
  181. if len(u.FullName) > 0 {
  182. return u.FullName
  183. }
  184. return u.Name
  185. }
  186. func (u *User) ShortName(length int) string {
  187. return strutil.Ellipsis(u.Name, length)
  188. }
  189. // IsMailable checks if a user is eligible
  190. // to receive emails.
  191. func (u *User) IsMailable() bool {
  192. return u.IsActive
  193. }
  194. // IsUserExist checks if given user name exist,
  195. // the user name should be noncased unique.
  196. // If uid is presented, then check will rule out that one,
  197. // it is used when update a user name in settings page.
  198. func IsUserExist(uid int64, name string) (bool, error) {
  199. if name == "" {
  200. return false, nil
  201. }
  202. return x.Where("id != ?", uid).Get(&User{LowerName: strings.ToLower(name)})
  203. }
  204. // GetUserSalt returns a random user salt token.
  205. func GetUserSalt() (string, error) {
  206. return strutil.RandomChars(10)
  207. }
  208. // NewGhostUser creates and returns a fake user for someone who has deleted his/her account.
  209. func NewGhostUser() *User {
  210. return &User{
  211. ID: -1,
  212. Name: "Ghost",
  213. LowerName: "ghost",
  214. }
  215. }
  216. var (
  217. reservedUsernames = []string{"-", "explore", "create", "assets", "css", "img", "js", "less", "plugins", "debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new", ".", ".."}
  218. reservedUserPatterns = []string{"*.keys"}
  219. )
  220. type ErrNameNotAllowed struct {
  221. args errutil.Args
  222. }
  223. func IsErrNameNotAllowed(err error) bool {
  224. _, ok := err.(ErrNameNotAllowed)
  225. return ok
  226. }
  227. func (err ErrNameNotAllowed) Value() string {
  228. val, ok := err.args["name"].(string)
  229. if ok {
  230. return val
  231. }
  232. val, ok = err.args["pattern"].(string)
  233. if ok {
  234. return val
  235. }
  236. return "<value not found>"
  237. }
  238. func (err ErrNameNotAllowed) Error() string {
  239. return fmt.Sprintf("name is not allowed: %v", err.args)
  240. }
  241. // isNameAllowed checks if name is reserved or pattern of name is not allowed
  242. // based on given reserved names and patterns.
  243. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  244. func isNameAllowed(names, patterns []string, name string) error {
  245. name = strings.TrimSpace(strings.ToLower(name))
  246. if utf8.RuneCountInString(name) == 0 {
  247. return ErrNameNotAllowed{args: errutil.Args{"reason": "empty name"}}
  248. }
  249. for i := range names {
  250. if name == names[i] {
  251. return ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "name": name}}
  252. }
  253. }
  254. for _, pat := range patterns {
  255. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  256. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  257. return ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "pattern": pat}}
  258. }
  259. }
  260. return nil
  261. }
  262. // isUsernameAllowed return an error if given name is a reserved name or pattern for users.
  263. func isUsernameAllowed(name string) error {
  264. return isNameAllowed(reservedUsernames, reservedUserPatterns, name)
  265. }
  266. // CreateUser creates record of a new user.
  267. // Deprecated: Use Users.Create instead.
  268. func CreateUser(u *User) (err error) {
  269. if err = isUsernameAllowed(u.Name); err != nil {
  270. return err
  271. }
  272. isExist, err := IsUserExist(0, u.Name)
  273. if err != nil {
  274. return err
  275. } else if isExist {
  276. return ErrUserAlreadyExist{args: errutil.Args{"name": u.Name}}
  277. }
  278. u.Email = strings.ToLower(u.Email)
  279. isExist, err = IsEmailUsed(u.Email)
  280. if err != nil {
  281. return err
  282. } else if isExist {
  283. return ErrEmailAlreadyUsed{args: errutil.Args{"email": u.Email}}
  284. }
  285. u.LowerName = strings.ToLower(u.Name)
  286. u.AvatarEmail = u.Email
  287. u.Avatar = tool.HashEmail(u.AvatarEmail)
  288. if u.Rands, err = GetUserSalt(); err != nil {
  289. return err
  290. }
  291. if u.Salt, err = GetUserSalt(); err != nil {
  292. return err
  293. }
  294. u.EncodePassword()
  295. u.MaxRepoCreation = -1
  296. sess := x.NewSession()
  297. defer sess.Close()
  298. if err = sess.Begin(); err != nil {
  299. return err
  300. }
  301. if _, err = sess.Insert(u); err != nil {
  302. return err
  303. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  304. return err
  305. }
  306. return sess.Commit()
  307. }
  308. func countUsers(e Engine) int64 {
  309. count, _ := e.Where("type=0").Count(new(User))
  310. return count
  311. }
  312. // CountUsers returns number of users.
  313. func CountUsers() int64 {
  314. return countUsers(x)
  315. }
  316. // Users returns number of users in given page.
  317. func ListUsers(page, pageSize int) ([]*User, error) {
  318. users := make([]*User, 0, pageSize)
  319. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  320. }
  321. // parseUserFromCode returns user by username encoded in code.
  322. // It returns nil if code or username is invalid.
  323. func parseUserFromCode(code string) (user *User) {
  324. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  325. return nil
  326. }
  327. // Use tail hex username to query user
  328. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  329. if b, err := hex.DecodeString(hexStr); err == nil {
  330. if user, err = GetUserByName(string(b)); user != nil {
  331. return user
  332. } else if !IsErrUserNotExist(err) {
  333. log.Error("Failed to get user by name %q: %v", string(b), err)
  334. }
  335. }
  336. return nil
  337. }
  338. // verify active code when active account
  339. func VerifyUserActiveCode(code string) (user *User) {
  340. minutes := conf.Auth.ActivateCodeLives
  341. if user = parseUserFromCode(code); user != nil {
  342. // time limit code
  343. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  344. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Password + user.Rands
  345. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  346. return user
  347. }
  348. }
  349. return nil
  350. }
  351. // verify active code when active account
  352. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  353. minutes := conf.Auth.ActivateCodeLives
  354. if user := parseUserFromCode(code); user != nil {
  355. // time limit code
  356. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  357. data := com.ToStr(user.ID) + email + user.LowerName + user.Password + user.Rands
  358. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  359. emailAddress := &EmailAddress{Email: email}
  360. if has, _ := x.Get(emailAddress); has {
  361. return emailAddress
  362. }
  363. }
  364. }
  365. return nil
  366. }
  367. // ChangeUserName changes all corresponding setting from old user name to new one.
  368. func ChangeUserName(u *User, newUserName string) (err error) {
  369. if err = isUsernameAllowed(newUserName); err != nil {
  370. return err
  371. }
  372. isExist, err := IsUserExist(0, newUserName)
  373. if err != nil {
  374. return err
  375. } else if isExist {
  376. return ErrUserAlreadyExist{args: errutil.Args{"name": newUserName}}
  377. }
  378. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  379. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  380. }
  381. // Delete all local copies of repositories and wikis the user owns.
  382. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  383. repo := bean.(*Repository)
  384. deleteRepoLocalCopy(repo)
  385. // TODO: By the same reasoning, shouldn't we also sync access to the local wiki path?
  386. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  387. return nil
  388. }); err != nil {
  389. return fmt.Errorf("delete repository and wiki local copy: %v", err)
  390. }
  391. // Rename or create user base directory
  392. baseDir := UserPath(u.Name)
  393. newBaseDir := UserPath(newUserName)
  394. if com.IsExist(baseDir) {
  395. return os.Rename(baseDir, newBaseDir)
  396. }
  397. return os.MkdirAll(newBaseDir, os.ModePerm)
  398. }
  399. func updateUser(e Engine, u *User) error {
  400. // Organization does not need email
  401. if !u.IsOrganization() {
  402. u.Email = strings.ToLower(u.Email)
  403. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  404. if err != nil {
  405. return err
  406. } else if has {
  407. return ErrEmailAlreadyUsed{args: errutil.Args{"email": u.Email}}
  408. }
  409. if u.AvatarEmail == "" {
  410. u.AvatarEmail = u.Email
  411. }
  412. u.Avatar = tool.HashEmail(u.AvatarEmail)
  413. }
  414. u.LowerName = strings.ToLower(u.Name)
  415. u.Location = tool.TruncateString(u.Location, 255)
  416. u.Website = tool.TruncateString(u.Website, 255)
  417. u.Description = tool.TruncateString(u.Description, 255)
  418. _, err := e.ID(u.ID).AllCols().Update(u)
  419. return err
  420. }
  421. // UpdateUser updates user's information.
  422. func UpdateUser(u *User) error {
  423. return updateUser(x, u)
  424. }
  425. // deleteBeans deletes all given beans, beans should contain delete conditions.
  426. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  427. for i := range beans {
  428. if _, err = e.Delete(beans[i]); err != nil {
  429. return err
  430. }
  431. }
  432. return nil
  433. }
  434. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  435. func deleteUser(e *xorm.Session, u *User) error {
  436. // Note: A user owns any repository or belongs to any organization
  437. // cannot perform delete operation.
  438. // Check ownership of repository.
  439. count, err := getRepositoryCount(e, u)
  440. if err != nil {
  441. return fmt.Errorf("GetRepositoryCount: %v", err)
  442. } else if count > 0 {
  443. return ErrUserOwnRepos{UID: u.ID}
  444. }
  445. // Check membership of organization.
  446. count, err = u.getOrganizationCount(e)
  447. if err != nil {
  448. return fmt.Errorf("GetOrganizationCount: %v", err)
  449. } else if count > 0 {
  450. return ErrUserHasOrgs{UID: u.ID}
  451. }
  452. // ***** START: Watch *****
  453. watches := make([]*Watch, 0, 10)
  454. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  455. return fmt.Errorf("get all watches: %v", err)
  456. }
  457. for i := range watches {
  458. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  459. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  460. }
  461. }
  462. // ***** END: Watch *****
  463. // ***** START: Star *****
  464. stars := make([]*Star, 0, 10)
  465. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  466. return fmt.Errorf("get all stars: %v", err)
  467. }
  468. for i := range stars {
  469. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  470. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  471. }
  472. }
  473. // ***** END: Star *****
  474. // ***** START: Follow *****
  475. followers := make([]*Follow, 0, 10)
  476. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  477. return fmt.Errorf("get all followers: %v", err)
  478. }
  479. for i := range followers {
  480. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  481. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  482. }
  483. }
  484. // ***** END: Follow *****
  485. if err = deleteBeans(e,
  486. &AccessToken{UserID: u.ID},
  487. &Collaboration{UserID: u.ID},
  488. &Access{UserID: u.ID},
  489. &Watch{UserID: u.ID},
  490. &Star{UID: u.ID},
  491. &Follow{FollowID: u.ID},
  492. &Action{UserID: u.ID},
  493. &IssueUser{UID: u.ID},
  494. &EmailAddress{UID: u.ID},
  495. ); err != nil {
  496. return fmt.Errorf("deleteBeans: %v", err)
  497. }
  498. // ***** START: PublicKey *****
  499. keys := make([]*PublicKey, 0, 10)
  500. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  501. return fmt.Errorf("get all public keys: %v", err)
  502. }
  503. keyIDs := make([]int64, len(keys))
  504. for i := range keys {
  505. keyIDs[i] = keys[i].ID
  506. }
  507. if err = deletePublicKeys(e, keyIDs...); err != nil {
  508. return fmt.Errorf("deletePublicKeys: %v", err)
  509. }
  510. // ***** END: PublicKey *****
  511. // Clear assignee.
  512. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  513. return fmt.Errorf("clear assignee: %v", err)
  514. }
  515. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  516. return fmt.Errorf("Delete: %v", err)
  517. }
  518. // FIXME: system notice
  519. // Note: There are something just cannot be roll back,
  520. // so just keep error logs of those operations.
  521. _ = os.RemoveAll(UserPath(u.Name))
  522. _ = os.Remove(userutil.CustomAvatarPath(u.ID))
  523. return nil
  524. }
  525. // DeleteUser completely and permanently deletes everything of a user,
  526. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  527. func DeleteUser(u *User) (err error) {
  528. sess := x.NewSession()
  529. defer sess.Close()
  530. if err = sess.Begin(); err != nil {
  531. return err
  532. }
  533. if err = deleteUser(sess, u); err != nil {
  534. // Note: don't wrapper error here.
  535. return err
  536. }
  537. if err = sess.Commit(); err != nil {
  538. return err
  539. }
  540. return RewriteAuthorizedKeys()
  541. }
  542. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  543. func DeleteInactivateUsers() (err error) {
  544. users := make([]*User, 0, 10)
  545. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  546. return fmt.Errorf("get all inactive users: %v", err)
  547. }
  548. // FIXME: should only update authorized_keys file once after all deletions.
  549. for _, u := range users {
  550. if err = DeleteUser(u); err != nil {
  551. // Ignore users that were set inactive by admin.
  552. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  553. continue
  554. }
  555. return err
  556. }
  557. }
  558. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  559. return err
  560. }
  561. // UserPath returns the path absolute path of user repositories.
  562. //
  563. // Deprecated: Use repoutil.UserPath instead.
  564. func UserPath(username string) string {
  565. return filepath.Join(conf.Repository.Root, strings.ToLower(username))
  566. }
  567. func GetUserByKeyID(keyID int64) (*User, error) {
  568. user := new(User)
  569. has, err := x.SQL("SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?", keyID).Get(user)
  570. if err != nil {
  571. return nil, err
  572. } else if !has {
  573. return nil, errors.UserNotKeyOwner{KeyID: keyID}
  574. }
  575. return user, nil
  576. }
  577. func getUserByID(e Engine, id int64) (*User, error) {
  578. u := new(User)
  579. has, err := e.ID(id).Get(u)
  580. if err != nil {
  581. return nil, err
  582. } else if !has {
  583. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": id}}
  584. }
  585. return u, nil
  586. }
  587. // GetUserByID returns the user object by given ID if exists.
  588. // Deprecated: Use Users.GetByID instead.
  589. func GetUserByID(id int64) (*User, error) {
  590. return getUserByID(x, id)
  591. }
  592. // GetAssigneeByID returns the user with read access of repository by given ID.
  593. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  594. ctx := context.TODO()
  595. if !Perms.Authorize(ctx, userID, repo.ID, AccessModeRead,
  596. AccessModeOptions{
  597. OwnerID: repo.OwnerID,
  598. Private: repo.IsPrivate,
  599. },
  600. ) {
  601. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": userID}}
  602. }
  603. return Users.GetByID(ctx, userID)
  604. }
  605. // GetUserByName returns a user by given name.
  606. // Deprecated: Use Users.GetByUsername instead.
  607. func GetUserByName(name string) (*User, error) {
  608. if name == "" {
  609. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  610. }
  611. u := &User{LowerName: strings.ToLower(name)}
  612. has, err := x.Get(u)
  613. if err != nil {
  614. return nil, err
  615. } else if !has {
  616. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  617. }
  618. return u, nil
  619. }
  620. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  621. func GetUserEmailsByNames(names []string) []string {
  622. mails := make([]string, 0, len(names))
  623. for _, name := range names {
  624. u, err := GetUserByName(name)
  625. if err != nil {
  626. continue
  627. }
  628. if u.IsMailable() {
  629. mails = append(mails, u.Email)
  630. }
  631. }
  632. return mails
  633. }
  634. // GetUserIDsByNames returns a slice of ids corresponds to names.
  635. func GetUserIDsByNames(names []string) []int64 {
  636. ids := make([]int64, 0, len(names))
  637. for _, name := range names {
  638. u, err := GetUserByName(name)
  639. if err != nil {
  640. continue
  641. }
  642. ids = append(ids, u.ID)
  643. }
  644. return ids
  645. }
  646. // UserCommit represents a commit with validation of user.
  647. type UserCommit struct {
  648. User *User
  649. *git.Commit
  650. }
  651. // ValidateCommitWithEmail checks if author's e-mail of commit is corresponding to a user.
  652. func ValidateCommitWithEmail(c *git.Commit) *User {
  653. u, err := GetUserByEmail(c.Author.Email)
  654. if err != nil {
  655. return nil
  656. }
  657. return u
  658. }
  659. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  660. func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
  661. emails := make(map[string]*User)
  662. newCommits := make([]*UserCommit, len(oldCommits))
  663. for i := range oldCommits {
  664. var u *User
  665. if v, ok := emails[oldCommits[i].Author.Email]; !ok {
  666. u, _ = GetUserByEmail(oldCommits[i].Author.Email)
  667. emails[oldCommits[i].Author.Email] = u
  668. } else {
  669. u = v
  670. }
  671. newCommits[i] = &UserCommit{
  672. User: u,
  673. Commit: oldCommits[i],
  674. }
  675. }
  676. return newCommits
  677. }
  678. // GetUserByEmail returns the user object by given e-mail if exists.
  679. // Deprecated: Use Users.GetByEmail instead.
  680. func GetUserByEmail(email string) (*User, error) {
  681. if email == "" {
  682. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  683. }
  684. email = strings.ToLower(email)
  685. // First try to find the user by primary email
  686. user := &User{Email: email}
  687. has, err := x.Get(user)
  688. if err != nil {
  689. return nil, err
  690. }
  691. if has {
  692. return user, nil
  693. }
  694. // Otherwise, check in alternative list for activated email addresses
  695. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  696. has, err = x.Get(emailAddress)
  697. if err != nil {
  698. return nil, err
  699. }
  700. if has {
  701. return GetUserByID(emailAddress.UID)
  702. }
  703. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  704. }
  705. type SearchUserOptions struct {
  706. Keyword string
  707. Type UserType
  708. OrderBy string
  709. Page int
  710. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  711. }
  712. // SearchUserByName takes keyword and part of user name to search,
  713. // it returns results in given range and number of total results.
  714. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  715. if opts.Keyword == "" {
  716. return users, 0, nil
  717. }
  718. opts.Keyword = strings.ToLower(opts.Keyword)
  719. if opts.PageSize <= 0 || opts.PageSize > conf.UI.ExplorePagingNum {
  720. opts.PageSize = conf.UI.ExplorePagingNum
  721. }
  722. if opts.Page <= 0 {
  723. opts.Page = 1
  724. }
  725. searchQuery := "%" + opts.Keyword + "%"
  726. users = make([]*User, 0, opts.PageSize)
  727. // Append conditions
  728. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  729. Or("LOWER(full_name) LIKE ?", searchQuery).
  730. And("type = ?", opts.Type)
  731. countSess := *sess
  732. count, err := countSess.Count(new(User))
  733. if err != nil {
  734. return nil, 0, fmt.Errorf("Count: %v", err)
  735. }
  736. if len(opts.OrderBy) > 0 {
  737. sess.OrderBy(opts.OrderBy)
  738. }
  739. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  740. }
  741. // GetRepositoryAccesses finds all repositories with their access mode where a user has access but does not own.
  742. func (u *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) {
  743. accesses := make([]*Access, 0, 10)
  744. if err := x.Find(&accesses, &Access{UserID: u.ID}); err != nil {
  745. return nil, err
  746. }
  747. repos := make(map[*Repository]AccessMode, len(accesses))
  748. for _, access := range accesses {
  749. repo, err := GetRepositoryByID(access.RepoID)
  750. if err != nil {
  751. if IsErrRepoNotExist(err) {
  752. log.Error("Failed to get repository by ID: %v", err)
  753. continue
  754. }
  755. return nil, err
  756. }
  757. if repo.OwnerID == u.ID {
  758. continue
  759. }
  760. repos[repo] = access.Mode
  761. }
  762. return repos, nil
  763. }
  764. // GetAccessibleRepositories finds repositories which the user has access but does not own.
  765. // If limit is smaller than 1 means returns all found results.
  766. func (user *User) GetAccessibleRepositories(limit int) (repos []*Repository, _ error) {
  767. sess := x.Where("owner_id !=? ", user.ID).Desc("updated_unix")
  768. if limit > 0 {
  769. sess.Limit(limit)
  770. repos = make([]*Repository, 0, limit)
  771. } else {
  772. repos = make([]*Repository, 0, 10)
  773. }
  774. return repos, sess.Join("INNER", "access", "access.user_id = ? AND access.repo_id = repository.id", user.ID).Find(&repos)
  775. }