user.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. "context"
  7. "encoding/hex"
  8. "fmt"
  9. _ "image/jpeg"
  10. "os"
  11. "path/filepath"
  12. "strings"
  13. "time"
  14. "github.com/unknwon/com"
  15. log "unknwon.dev/clog/v2"
  16. "xorm.io/xorm"
  17. "github.com/gogs/git-module"
  18. "gogs.io/gogs/internal/conf"
  19. "gogs.io/gogs/internal/db/errors"
  20. "gogs.io/gogs/internal/errutil"
  21. "gogs.io/gogs/internal/tool"
  22. "gogs.io/gogs/internal/userutil"
  23. )
  24. // TODO(unknwon): Delete me once refactoring is done.
  25. func (u *User) BeforeInsert() {
  26. u.CreatedUnix = time.Now().Unix()
  27. u.UpdatedUnix = u.CreatedUnix
  28. }
  29. // TODO(unknwon): Refactoring together with methods that do updates.
  30. func (u *User) BeforeUpdate() {
  31. if u.MaxRepoCreation < -1 {
  32. u.MaxRepoCreation = -1
  33. }
  34. u.UpdatedUnix = time.Now().Unix()
  35. }
  36. // TODO(unknwon): Delete me once refactoring is done.
  37. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  38. switch colName {
  39. case "created_unix":
  40. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  41. case "updated_unix":
  42. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  43. }
  44. }
  45. // Deprecated: Use OrgsUsers.CountByUser instead.
  46. //
  47. // TODO(unknwon): Delete me once no more call sites in this file.
  48. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  49. return e.Where("uid=?", u.ID).Count(new(OrgUser))
  50. }
  51. func countUsers(e Engine) int64 {
  52. count, _ := e.Where("type=0").Count(new(User))
  53. return count
  54. }
  55. // CountUsers returns number of users.
  56. func CountUsers() int64 {
  57. return countUsers(x)
  58. }
  59. // Users returns number of users in given page.
  60. func ListUsers(page, pageSize int) ([]*User, error) {
  61. users := make([]*User, 0, pageSize)
  62. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  63. }
  64. // parseUserFromCode returns user by username encoded in code.
  65. // It returns nil if code or username is invalid.
  66. func parseUserFromCode(code string) (user *User) {
  67. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  68. return nil
  69. }
  70. // Use tail hex username to query user
  71. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  72. if b, err := hex.DecodeString(hexStr); err == nil {
  73. if user, err = GetUserByName(string(b)); user != nil {
  74. return user
  75. } else if !IsErrUserNotExist(err) {
  76. log.Error("Failed to get user by name %q: %v", string(b), err)
  77. }
  78. }
  79. return nil
  80. }
  81. // verify active code when active account
  82. func VerifyUserActiveCode(code string) (user *User) {
  83. minutes := conf.Auth.ActivateCodeLives
  84. if user = parseUserFromCode(code); user != nil {
  85. // time limit code
  86. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  87. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Password + user.Rands
  88. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  89. return user
  90. }
  91. }
  92. return nil
  93. }
  94. // verify active code when active account
  95. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  96. minutes := conf.Auth.ActivateCodeLives
  97. if user := parseUserFromCode(code); user != nil {
  98. // time limit code
  99. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  100. data := com.ToStr(user.ID) + email + user.LowerName + user.Password + user.Rands
  101. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  102. emailAddress := &EmailAddress{Email: email}
  103. if has, _ := x.Get(emailAddress); has {
  104. return emailAddress
  105. }
  106. }
  107. }
  108. return nil
  109. }
  110. // ChangeUserName changes all corresponding setting from old user name to new one.
  111. func ChangeUserName(u *User, newUserName string) (err error) {
  112. if err = isUsernameAllowed(newUserName); err != nil {
  113. return err
  114. }
  115. if Users.IsUsernameUsed(context.TODO(), newUserName) {
  116. return ErrUserAlreadyExist{args: errutil.Args{"name": newUserName}}
  117. }
  118. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  119. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  120. }
  121. // Delete all local copies of repositories and wikis the user owns.
  122. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  123. repo := bean.(*Repository)
  124. deleteRepoLocalCopy(repo)
  125. // TODO: By the same reasoning, shouldn't we also sync access to the local wiki path?
  126. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  127. return nil
  128. }); err != nil {
  129. return fmt.Errorf("delete repository and wiki local copy: %v", err)
  130. }
  131. // Rename or create user base directory
  132. baseDir := UserPath(u.Name)
  133. newBaseDir := UserPath(newUserName)
  134. if com.IsExist(baseDir) {
  135. return os.Rename(baseDir, newBaseDir)
  136. }
  137. return os.MkdirAll(newBaseDir, os.ModePerm)
  138. }
  139. func updateUser(e Engine, u *User) error {
  140. // Organization does not need email
  141. if !u.IsOrganization() {
  142. u.Email = strings.ToLower(u.Email)
  143. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  144. if err != nil {
  145. return err
  146. } else if has {
  147. return ErrEmailAlreadyUsed{args: errutil.Args{"email": u.Email}}
  148. }
  149. if u.AvatarEmail == "" {
  150. u.AvatarEmail = u.Email
  151. }
  152. u.Avatar = tool.HashEmail(u.AvatarEmail)
  153. }
  154. u.LowerName = strings.ToLower(u.Name)
  155. u.Location = tool.TruncateString(u.Location, 255)
  156. u.Website = tool.TruncateString(u.Website, 255)
  157. u.Description = tool.TruncateString(u.Description, 255)
  158. _, err := e.ID(u.ID).AllCols().Update(u)
  159. return err
  160. }
  161. // UpdateUser updates user's information.
  162. func UpdateUser(u *User) error {
  163. return updateUser(x, u)
  164. }
  165. // deleteBeans deletes all given beans, beans should contain delete conditions.
  166. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  167. for i := range beans {
  168. if _, err = e.Delete(beans[i]); err != nil {
  169. return err
  170. }
  171. }
  172. return nil
  173. }
  174. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  175. func deleteUser(e *xorm.Session, u *User) error {
  176. // Note: A user owns any repository or belongs to any organization
  177. // cannot perform delete operation.
  178. // Check ownership of repository.
  179. count, err := getRepositoryCount(e, u)
  180. if err != nil {
  181. return fmt.Errorf("GetRepositoryCount: %v", err)
  182. } else if count > 0 {
  183. return ErrUserOwnRepos{UID: u.ID}
  184. }
  185. // Check membership of organization.
  186. count, err = u.getOrganizationCount(e)
  187. if err != nil {
  188. return fmt.Errorf("GetOrganizationCount: %v", err)
  189. } else if count > 0 {
  190. return ErrUserHasOrgs{UID: u.ID}
  191. }
  192. // ***** START: Watch *****
  193. watches := make([]*Watch, 0, 10)
  194. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  195. return fmt.Errorf("get all watches: %v", err)
  196. }
  197. for i := range watches {
  198. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  199. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  200. }
  201. }
  202. // ***** END: Watch *****
  203. // ***** START: Star *****
  204. stars := make([]*Star, 0, 10)
  205. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  206. return fmt.Errorf("get all stars: %v", err)
  207. }
  208. for i := range stars {
  209. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  210. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  211. }
  212. }
  213. // ***** END: Star *****
  214. // ***** START: Follow *****
  215. followers := make([]*Follow, 0, 10)
  216. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  217. return fmt.Errorf("get all followers: %v", err)
  218. }
  219. for i := range followers {
  220. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  221. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  222. }
  223. }
  224. // ***** END: Follow *****
  225. if err = deleteBeans(e,
  226. &AccessToken{UserID: u.ID},
  227. &Collaboration{UserID: u.ID},
  228. &Access{UserID: u.ID},
  229. &Watch{UserID: u.ID},
  230. &Star{UID: u.ID},
  231. &Follow{FollowID: u.ID},
  232. &Action{UserID: u.ID},
  233. &IssueUser{UID: u.ID},
  234. &EmailAddress{UID: u.ID},
  235. ); err != nil {
  236. return fmt.Errorf("deleteBeans: %v", err)
  237. }
  238. // ***** START: PublicKey *****
  239. keys := make([]*PublicKey, 0, 10)
  240. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  241. return fmt.Errorf("get all public keys: %v", err)
  242. }
  243. keyIDs := make([]int64, len(keys))
  244. for i := range keys {
  245. keyIDs[i] = keys[i].ID
  246. }
  247. if err = deletePublicKeys(e, keyIDs...); err != nil {
  248. return fmt.Errorf("deletePublicKeys: %v", err)
  249. }
  250. // ***** END: PublicKey *****
  251. // Clear assignee.
  252. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  253. return fmt.Errorf("clear assignee: %v", err)
  254. }
  255. if _, err = e.ID(u.ID).Delete(new(User)); err != nil {
  256. return fmt.Errorf("Delete: %v", err)
  257. }
  258. // FIXME: system notice
  259. // Note: There are something just cannot be roll back,
  260. // so just keep error logs of those operations.
  261. _ = os.RemoveAll(UserPath(u.Name))
  262. _ = os.Remove(userutil.CustomAvatarPath(u.ID))
  263. return nil
  264. }
  265. // DeleteUser completely and permanently deletes everything of a user,
  266. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  267. func DeleteUser(u *User) (err error) {
  268. sess := x.NewSession()
  269. defer sess.Close()
  270. if err = sess.Begin(); err != nil {
  271. return err
  272. }
  273. if err = deleteUser(sess, u); err != nil {
  274. // Note: don't wrapper error here.
  275. return err
  276. }
  277. if err = sess.Commit(); err != nil {
  278. return err
  279. }
  280. return RewriteAuthorizedKeys()
  281. }
  282. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  283. func DeleteInactivateUsers() (err error) {
  284. users := make([]*User, 0, 10)
  285. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  286. return fmt.Errorf("get all inactive users: %v", err)
  287. }
  288. // FIXME: should only update authorized_keys file once after all deletions.
  289. for _, u := range users {
  290. if err = DeleteUser(u); err != nil {
  291. // Ignore users that were set inactive by admin.
  292. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  293. continue
  294. }
  295. return err
  296. }
  297. }
  298. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  299. return err
  300. }
  301. // UserPath returns the path absolute path of user repositories.
  302. //
  303. // Deprecated: Use repoutil.UserPath instead.
  304. func UserPath(username string) string {
  305. return filepath.Join(conf.Repository.Root, strings.ToLower(username))
  306. }
  307. func GetUserByKeyID(keyID int64) (*User, error) {
  308. user := new(User)
  309. 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)
  310. if err != nil {
  311. return nil, err
  312. } else if !has {
  313. return nil, errors.UserNotKeyOwner{KeyID: keyID}
  314. }
  315. return user, nil
  316. }
  317. func getUserByID(e Engine, id int64) (*User, error) {
  318. u := new(User)
  319. has, err := e.ID(id).Get(u)
  320. if err != nil {
  321. return nil, err
  322. } else if !has {
  323. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": id}}
  324. }
  325. return u, nil
  326. }
  327. // GetUserByID returns the user object by given ID if exists.
  328. // Deprecated: Use Users.GetByID instead.
  329. func GetUserByID(id int64) (*User, error) {
  330. return getUserByID(x, id)
  331. }
  332. // GetAssigneeByID returns the user with read access of repository by given ID.
  333. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  334. ctx := context.TODO()
  335. if !Perms.Authorize(ctx, userID, repo.ID, AccessModeRead,
  336. AccessModeOptions{
  337. OwnerID: repo.OwnerID,
  338. Private: repo.IsPrivate,
  339. },
  340. ) {
  341. return nil, ErrUserNotExist{args: map[string]interface{}{"userID": userID}}
  342. }
  343. return Users.GetByID(ctx, userID)
  344. }
  345. // GetUserByName returns a user by given name.
  346. // Deprecated: Use Users.GetByUsername instead.
  347. func GetUserByName(name string) (*User, error) {
  348. if name == "" {
  349. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  350. }
  351. u := &User{LowerName: strings.ToLower(name)}
  352. has, err := x.Get(u)
  353. if err != nil {
  354. return nil, err
  355. } else if !has {
  356. return nil, ErrUserNotExist{args: map[string]interface{}{"name": name}}
  357. }
  358. return u, nil
  359. }
  360. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  361. func GetUserEmailsByNames(names []string) []string {
  362. mails := make([]string, 0, len(names))
  363. for _, name := range names {
  364. u, err := GetUserByName(name)
  365. if err != nil {
  366. continue
  367. }
  368. if u.IsMailable() {
  369. mails = append(mails, u.Email)
  370. }
  371. }
  372. return mails
  373. }
  374. // GetUserIDsByNames returns a slice of ids corresponds to names.
  375. func GetUserIDsByNames(names []string) []int64 {
  376. ids := make([]int64, 0, len(names))
  377. for _, name := range names {
  378. u, err := GetUserByName(name)
  379. if err != nil {
  380. continue
  381. }
  382. ids = append(ids, u.ID)
  383. }
  384. return ids
  385. }
  386. // UserCommit represents a commit with validation of user.
  387. type UserCommit struct {
  388. User *User
  389. *git.Commit
  390. }
  391. // ValidateCommitWithEmail checks if author's e-mail of commit is corresponding to a user.
  392. func ValidateCommitWithEmail(c *git.Commit) *User {
  393. u, err := GetUserByEmail(c.Author.Email)
  394. if err != nil {
  395. return nil
  396. }
  397. return u
  398. }
  399. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  400. func ValidateCommitsWithEmails(oldCommits []*git.Commit) []*UserCommit {
  401. emails := make(map[string]*User)
  402. newCommits := make([]*UserCommit, len(oldCommits))
  403. for i := range oldCommits {
  404. var u *User
  405. if v, ok := emails[oldCommits[i].Author.Email]; !ok {
  406. u, _ = GetUserByEmail(oldCommits[i].Author.Email)
  407. emails[oldCommits[i].Author.Email] = u
  408. } else {
  409. u = v
  410. }
  411. newCommits[i] = &UserCommit{
  412. User: u,
  413. Commit: oldCommits[i],
  414. }
  415. }
  416. return newCommits
  417. }
  418. // GetUserByEmail returns the user object by given e-mail if exists.
  419. // Deprecated: Use Users.GetByEmail instead.
  420. func GetUserByEmail(email string) (*User, error) {
  421. if email == "" {
  422. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  423. }
  424. email = strings.ToLower(email)
  425. // First try to find the user by primary email
  426. user := &User{Email: email}
  427. has, err := x.Get(user)
  428. if err != nil {
  429. return nil, err
  430. }
  431. if has {
  432. return user, nil
  433. }
  434. // Otherwise, check in alternative list for activated email addresses
  435. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  436. has, err = x.Get(emailAddress)
  437. if err != nil {
  438. return nil, err
  439. }
  440. if has {
  441. return GetUserByID(emailAddress.UID)
  442. }
  443. return nil, ErrUserNotExist{args: map[string]interface{}{"email": email}}
  444. }
  445. type SearchUserOptions struct {
  446. Keyword string
  447. Type UserType
  448. OrderBy string
  449. Page int
  450. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  451. }
  452. // SearchUserByName takes keyword and part of user name to search,
  453. // it returns results in given range and number of total results.
  454. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  455. if opts.Keyword == "" {
  456. return users, 0, nil
  457. }
  458. opts.Keyword = strings.ToLower(opts.Keyword)
  459. if opts.PageSize <= 0 || opts.PageSize > conf.UI.ExplorePagingNum {
  460. opts.PageSize = conf.UI.ExplorePagingNum
  461. }
  462. if opts.Page <= 0 {
  463. opts.Page = 1
  464. }
  465. searchQuery := "%" + opts.Keyword + "%"
  466. users = make([]*User, 0, opts.PageSize)
  467. // Append conditions
  468. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  469. Or("LOWER(full_name) LIKE ?", searchQuery).
  470. And("type = ?", opts.Type)
  471. countSess := *sess
  472. count, err := countSess.Count(new(User))
  473. if err != nil {
  474. return nil, 0, fmt.Errorf("Count: %v", err)
  475. }
  476. if len(opts.OrderBy) > 0 {
  477. sess.OrderBy(opts.OrderBy)
  478. }
  479. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  480. }
  481. // GetRepositoryAccesses finds all repositories with their access mode where a user has access but does not own.
  482. func (u *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) {
  483. accesses := make([]*Access, 0, 10)
  484. if err := x.Find(&accesses, &Access{UserID: u.ID}); err != nil {
  485. return nil, err
  486. }
  487. repos := make(map[*Repository]AccessMode, len(accesses))
  488. for _, access := range accesses {
  489. repo, err := GetRepositoryByID(access.RepoID)
  490. if err != nil {
  491. if IsErrRepoNotExist(err) {
  492. log.Error("Failed to get repository by ID: %v", err)
  493. continue
  494. }
  495. return nil, err
  496. }
  497. if repo.OwnerID == u.ID {
  498. continue
  499. }
  500. repos[repo] = access.Mode
  501. }
  502. return repos, nil
  503. }
  504. // GetAccessibleRepositories finds repositories which the user has access but does not own.
  505. // If limit is smaller than 1 means returns all found results.
  506. func (user *User) GetAccessibleRepositories(limit int) (repos []*Repository, _ error) {
  507. sess := x.Where("owner_id !=? ", user.ID).Desc("updated_unix")
  508. if limit > 0 {
  509. sess.Limit(limit)
  510. repos = make([]*Repository, 0, limit)
  511. } else {
  512. repos = make([]*Repository, 0, 10)
  513. }
  514. return repos, sess.Join("INNER", "access", "access.user_id = ? AND access.repo_id = repository.id", user.ID).Find(&repos)
  515. }