user.go 20 KB

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