user.go 24 KB

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