user.go 29 KB

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