user.go 27 KB

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