user.go 20 KB

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