user.go 19 KB

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