user.go 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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 models
  5. import (
  6. "bytes"
  7. "container/list"
  8. "crypto/sha256"
  9. "encoding/hex"
  10. "errors"
  11. "fmt"
  12. "image"
  13. "image/jpeg"
  14. _ "image/jpeg"
  15. "os"
  16. "path"
  17. "path/filepath"
  18. "strings"
  19. "time"
  20. "github.com/Unknwon/com"
  21. "github.com/nfnt/resize"
  22. "github.com/gogits/gogs/modules/avatar"
  23. "github.com/gogits/gogs/modules/base"
  24. "github.com/gogits/gogs/modules/git"
  25. "github.com/gogits/gogs/modules/log"
  26. "github.com/gogits/gogs/modules/setting"
  27. )
  28. type UserType int
  29. const (
  30. INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  31. ORGANIZATION
  32. )
  33. var (
  34. ErrUserNotKeyOwner = errors.New("User does not the owner of public key")
  35. ErrEmailNotExist = errors.New("E-mail does not exist")
  36. ErrEmailNotActivated = errors.New("E-mail address has not been activated")
  37. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  38. ErrLoginSourceNotExist = errors.New("Login source does not exist")
  39. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  40. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  41. )
  42. // User represents the object of individual and member of organization.
  43. type User struct {
  44. Id int64
  45. LowerName string `xorm:"UNIQUE NOT NULL"`
  46. Name string `xorm:"UNIQUE NOT NULL"`
  47. FullName string
  48. // Email is the primary email address (to be used for communication).
  49. Email string `xorm:"UNIQUE(s) NOT NULL"`
  50. Passwd string `xorm:"NOT NULL"`
  51. LoginType LoginType
  52. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  53. LoginName string
  54. Type UserType `xorm:"UNIQUE(s)"`
  55. Orgs []*User `xorm:"-"`
  56. Repos []*Repository `xorm:"-"`
  57. Location string
  58. Website string
  59. Rands string `xorm:"VARCHAR(10)"`
  60. Salt string `xorm:"VARCHAR(10)"`
  61. Created time.Time `xorm:"CREATED"`
  62. Updated time.Time `xorm:"UPDATED"`
  63. // Permissions.
  64. IsActive bool
  65. IsAdmin bool
  66. AllowGitHook bool
  67. // Avatar.
  68. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  69. AvatarEmail string `xorm:"NOT NULL"`
  70. UseCustomAvatar bool
  71. // Counters.
  72. NumFollowers int
  73. NumFollowings int
  74. NumStars int
  75. NumRepos int
  76. // For organization.
  77. Description string
  78. NumTeams int
  79. NumMembers int
  80. Teams []*Team `xorm:"-"`
  81. Members []*User `xorm:"-"`
  82. }
  83. // EmailAdresses is the list of all email addresses of a user. Can contain the
  84. // primary email address, but is not obligatory
  85. type EmailAddress struct {
  86. Id int64
  87. Uid int64 `xorm:"INDEX NOT NULL"`
  88. Email string `xorm:"UNIQUE NOT NULL"`
  89. IsActivated bool
  90. IsPrimary bool `xorm:"-"`
  91. }
  92. // DashboardLink returns the user dashboard page link.
  93. func (u *User) DashboardLink() string {
  94. if u.IsOrganization() {
  95. return setting.AppSubUrl + "/org/" + u.Name + "/dashboard/"
  96. }
  97. return setting.AppSubUrl + "/"
  98. }
  99. // HomeLink returns the user home page link.
  100. func (u *User) HomeLink() string {
  101. return setting.AppSubUrl + "/" + u.Name
  102. }
  103. // AvatarLink returns user gravatar link.
  104. func (u *User) AvatarLink() string {
  105. defaultImgUrl := setting.AppSubUrl + "/img/avatar_default.jpg"
  106. if u.Id == -1 {
  107. return defaultImgUrl
  108. }
  109. imgPath := path.Join(setting.AvatarUploadPath, com.ToStr(u.Id))
  110. switch {
  111. case u.UseCustomAvatar:
  112. if !com.IsExist(imgPath) {
  113. return defaultImgUrl
  114. }
  115. return setting.AppSubUrl + "/avatars/" + com.ToStr(u.Id)
  116. case setting.DisableGravatar, setting.OfflineMode:
  117. if !com.IsExist(imgPath) {
  118. img, err := avatar.RandomImage([]byte(u.Email))
  119. if err != nil {
  120. log.Error(3, "RandomImage: %v", err)
  121. return defaultImgUrl
  122. }
  123. if err = os.MkdirAll(path.Dir(imgPath), os.ModePerm); err != nil {
  124. log.Error(3, "MkdirAll: %v", err)
  125. return defaultImgUrl
  126. }
  127. fw, err := os.Create(imgPath)
  128. if err != nil {
  129. log.Error(3, "Create: %v", err)
  130. return defaultImgUrl
  131. }
  132. defer fw.Close()
  133. if err = jpeg.Encode(fw, img, nil); err != nil {
  134. log.Error(3, "Encode: %v", err)
  135. return defaultImgUrl
  136. }
  137. log.Info("New random avatar created: %d", u.Id)
  138. }
  139. return setting.AppSubUrl + "/avatars/" + com.ToStr(u.Id)
  140. case setting.Service.EnableCacheAvatar:
  141. return setting.AppSubUrl + "/avatar/" + u.Avatar
  142. }
  143. return setting.GravatarSource + u.Avatar
  144. }
  145. // NewGitSig generates and returns the signature of given user.
  146. func (u *User) NewGitSig() *git.Signature {
  147. return &git.Signature{
  148. Name: u.Name,
  149. Email: u.Email,
  150. When: time.Now(),
  151. }
  152. }
  153. // EncodePasswd encodes password to safe format.
  154. func (u *User) EncodePasswd() {
  155. newPasswd := base.PBKDF2([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  156. u.Passwd = fmt.Sprintf("%x", newPasswd)
  157. }
  158. // ValidatePassword checks if given password matches the one belongs to the user.
  159. func (u *User) ValidatePassword(passwd string) bool {
  160. newUser := &User{Passwd: passwd, Salt: u.Salt}
  161. newUser.EncodePasswd()
  162. return u.Passwd == newUser.Passwd
  163. }
  164. // CustomAvatarPath returns user custom avatar file path.
  165. func (u *User) CustomAvatarPath() string {
  166. return filepath.Join(setting.AvatarUploadPath, com.ToStr(u.Id))
  167. }
  168. // UploadAvatar saves custom avatar for user.
  169. // FIXME: split uploads to different subdirs in case we have massive users.
  170. func (u *User) UploadAvatar(data []byte) error {
  171. u.UseCustomAvatar = true
  172. img, _, err := image.Decode(bytes.NewReader(data))
  173. if err != nil {
  174. return err
  175. }
  176. m := resize.Resize(234, 234, img, resize.NearestNeighbor)
  177. sess := x.NewSession()
  178. defer sess.Close()
  179. if err = sess.Begin(); err != nil {
  180. return err
  181. }
  182. if _, err = sess.Id(u.Id).AllCols().Update(u); err != nil {
  183. sess.Rollback()
  184. return err
  185. }
  186. os.MkdirAll(setting.AvatarUploadPath, os.ModePerm)
  187. fw, err := os.Create(u.CustomAvatarPath())
  188. if err != nil {
  189. sess.Rollback()
  190. return err
  191. }
  192. defer fw.Close()
  193. if err = jpeg.Encode(fw, m, nil); err != nil {
  194. sess.Rollback()
  195. return err
  196. }
  197. return sess.Commit()
  198. }
  199. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  200. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  201. if err := repo.GetOwner(); err != nil {
  202. log.Error(3, "GetOwner: %v", err)
  203. return false
  204. }
  205. if repo.Owner.IsOrganization() {
  206. has, err := HasAccess(u, repo, ACCESS_MODE_ADMIN)
  207. if err != nil {
  208. log.Error(3, "HasAccess: %v", err)
  209. return false
  210. }
  211. return has
  212. }
  213. return repo.IsOwnedBy(u.Id)
  214. }
  215. // IsOrganization returns true if user is actually a organization.
  216. func (u *User) IsOrganization() bool {
  217. return u.Type == ORGANIZATION
  218. }
  219. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  220. func (u *User) IsUserOrgOwner(orgId int64) bool {
  221. return IsOrganizationOwner(orgId, u.Id)
  222. }
  223. // IsPublicMember returns true if user public his/her membership in give organization.
  224. func (u *User) IsPublicMember(orgId int64) bool {
  225. return IsPublicMembership(orgId, u.Id)
  226. }
  227. // GetOrganizationCount returns count of membership of organization of user.
  228. func (u *User) GetOrganizationCount() (int64, error) {
  229. return x.Where("uid=?", u.Id).Count(new(OrgUser))
  230. }
  231. // GetRepositories returns all repositories that user owns, including private repositories.
  232. func (u *User) GetRepositories() (err error) {
  233. u.Repos, err = GetRepositories(u.Id, true)
  234. return err
  235. }
  236. // GetOrganizations returns all organizations that user belongs to.
  237. func (u *User) GetOrganizations() error {
  238. ous, err := GetOrgUsersByUserId(u.Id)
  239. if err != nil {
  240. return err
  241. }
  242. u.Orgs = make([]*User, len(ous))
  243. for i, ou := range ous {
  244. u.Orgs[i], err = GetUserByID(ou.OrgID)
  245. if err != nil {
  246. return err
  247. }
  248. }
  249. return nil
  250. }
  251. // GetFullNameFallback returns Full Name if set, otherwise username
  252. func (u *User) GetFullNameFallback() string {
  253. if u.FullName == "" {
  254. return u.Name
  255. }
  256. return u.FullName
  257. }
  258. // IsUserExist checks if given user name exist,
  259. // the user name should be noncased unique.
  260. // If uid is presented, then check will rule out that one,
  261. // it is used when update a user name in settings page.
  262. func IsUserExist(uid int64, name string) (bool, error) {
  263. if len(name) == 0 {
  264. return false, nil
  265. }
  266. return x.Where("id!=?", uid).Get(&User{LowerName: strings.ToLower(name)})
  267. }
  268. // IsEmailUsed returns true if the e-mail has been used.
  269. func IsEmailUsed(email string) (bool, error) {
  270. if len(email) == 0 {
  271. return false, nil
  272. }
  273. email = strings.ToLower(email)
  274. if has, err := x.Get(&EmailAddress{Email: email}); has || err != nil {
  275. return has, err
  276. }
  277. return x.Get(&User{Email: email})
  278. }
  279. // GetUserSalt returns a ramdom user salt token.
  280. func GetUserSalt() string {
  281. return base.GetRandomString(10)
  282. }
  283. // NewFakeUser creates and returns a fake user for someone has deleted his/her account.
  284. func NewFakeUser() *User {
  285. return &User{
  286. Id: -1,
  287. Name: "Someone",
  288. LowerName: "someone",
  289. }
  290. }
  291. // CreateUser creates record of a new user.
  292. func CreateUser(u *User) (err error) {
  293. if err = IsUsableName(u.Name); err != nil {
  294. return err
  295. }
  296. isExist, err := IsUserExist(0, u.Name)
  297. if err != nil {
  298. return err
  299. } else if isExist {
  300. return ErrUserAlreadyExist{u.Name}
  301. }
  302. isExist, err = IsEmailUsed(u.Email)
  303. if err != nil {
  304. return err
  305. } else if isExist {
  306. return ErrEmailAlreadyUsed{u.Email}
  307. }
  308. u.LowerName = strings.ToLower(u.Name)
  309. u.AvatarEmail = u.Email
  310. u.Avatar = avatar.HashEmail(u.AvatarEmail)
  311. u.Rands = GetUserSalt()
  312. u.Salt = GetUserSalt()
  313. u.EncodePasswd()
  314. sess := x.NewSession()
  315. defer sess.Close()
  316. if err = sess.Begin(); err != nil {
  317. return err
  318. }
  319. if _, err = sess.Insert(u); err != nil {
  320. sess.Rollback()
  321. return err
  322. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  323. sess.Rollback()
  324. return err
  325. }
  326. return sess.Commit()
  327. }
  328. func countUsers(e Engine) int64 {
  329. count, _ := e.Where("type=0").Count(new(User))
  330. return count
  331. }
  332. // CountUsers returns number of users.
  333. func CountUsers() int64 {
  334. return countUsers(x)
  335. }
  336. // GetUsers returns given number of user objects with offset.
  337. func GetUsers(num, offset int) ([]*User, error) {
  338. users := make([]*User, 0, num)
  339. err := x.Limit(num, offset).Where("type=0").Asc("id").Find(&users)
  340. return users, err
  341. }
  342. // get user by erify code
  343. func getVerifyUser(code string) (user *User) {
  344. if len(code) <= base.TimeLimitCodeLength {
  345. return nil
  346. }
  347. // use tail hex username query user
  348. hexStr := code[base.TimeLimitCodeLength:]
  349. if b, err := hex.DecodeString(hexStr); err == nil {
  350. if user, err = GetUserByName(string(b)); user != nil {
  351. return user
  352. }
  353. log.Error(4, "user.getVerifyUser: %v", err)
  354. }
  355. return nil
  356. }
  357. // verify active code when active account
  358. func VerifyUserActiveCode(code string) (user *User) {
  359. minutes := setting.Service.ActiveCodeLives
  360. if user = getVerifyUser(code); user != nil {
  361. // time limit code
  362. prefix := code[:base.TimeLimitCodeLength]
  363. data := com.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  364. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  365. return user
  366. }
  367. }
  368. return nil
  369. }
  370. // verify active code when active account
  371. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  372. minutes := setting.Service.ActiveCodeLives
  373. if user := getVerifyUser(code); user != nil {
  374. // time limit code
  375. prefix := code[:base.TimeLimitCodeLength]
  376. data := com.ToStr(user.Id) + email + user.LowerName + user.Passwd + user.Rands
  377. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  378. emailAddress := &EmailAddress{Email: email}
  379. if has, _ := x.Get(emailAddress); has {
  380. return emailAddress
  381. }
  382. }
  383. }
  384. return nil
  385. }
  386. // ChangeUserName changes all corresponding setting from old user name to new one.
  387. func ChangeUserName(u *User, newUserName string) (err error) {
  388. if err = IsUsableName(newUserName); err != nil {
  389. return err
  390. }
  391. isExist, err := IsUserExist(0, newUserName)
  392. if err != nil {
  393. return err
  394. } else if isExist {
  395. return ErrUserAlreadyExist{newUserName}
  396. }
  397. return os.Rename(UserPath(u.LowerName), UserPath(newUserName))
  398. }
  399. // UpdateUser updates user's information.
  400. func UpdateUser(u *User) error {
  401. u.Email = strings.ToLower(u.Email)
  402. has, err := x.Where("id!=?", u.Id).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  403. if err != nil {
  404. return err
  405. } else if has {
  406. return ErrEmailAlreadyUsed{u.Email}
  407. }
  408. u.LowerName = strings.ToLower(u.Name)
  409. if len(u.Location) > 255 {
  410. u.Location = u.Location[:255]
  411. }
  412. if len(u.Website) > 255 {
  413. u.Website = u.Website[:255]
  414. }
  415. if len(u.Description) > 255 {
  416. u.Description = u.Description[:255]
  417. }
  418. if u.AvatarEmail == "" {
  419. u.AvatarEmail = u.Email
  420. }
  421. u.Avatar = avatar.HashEmail(u.AvatarEmail)
  422. u.FullName = base.Sanitizer.Sanitize(u.FullName)
  423. _, err = x.Id(u.Id).AllCols().Update(u)
  424. return err
  425. }
  426. // DeleteBeans deletes all given beans, beans should contain delete conditions.
  427. func DeleteBeans(e Engine, beans ...interface{}) (err error) {
  428. for i := range beans {
  429. if _, err = e.Delete(beans[i]); err != nil {
  430. return err
  431. }
  432. }
  433. return nil
  434. }
  435. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  436. // DeleteUser completely and permanently deletes everything of a user,
  437. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  438. func DeleteUser(u *User) error {
  439. // Note: A user owns any repository or belongs to any organization
  440. // cannot perform delete operation.
  441. // Check ownership of repository.
  442. count, err := GetRepositoryCount(u)
  443. if err != nil {
  444. return fmt.Errorf("GetRepositoryCount: %v", err)
  445. } else if count > 0 {
  446. return ErrUserOwnRepos{UID: u.Id}
  447. }
  448. // Check membership of organization.
  449. count, err = u.GetOrganizationCount()
  450. if err != nil {
  451. return fmt.Errorf("GetOrganizationCount: %v", err)
  452. } else if count > 0 {
  453. return ErrUserHasOrgs{UID: u.Id}
  454. }
  455. sess := x.NewSession()
  456. defer sessionRelease(sess)
  457. if err = sess.Begin(); err != nil {
  458. return err
  459. }
  460. // ***** START: Watch *****
  461. watches := make([]*Watch, 0, 10)
  462. if err = x.Find(&watches, &Watch{UserID: u.Id}); err != nil {
  463. return fmt.Errorf("get all watches: %v", err)
  464. }
  465. for i := range watches {
  466. if _, err = sess.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  467. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  468. }
  469. }
  470. // ***** END: Watch *****
  471. // ***** START: Star *****
  472. stars := make([]*Star, 0, 10)
  473. if err = x.Find(&stars, &Star{UID: u.Id}); err != nil {
  474. return fmt.Errorf("get all stars: %v", err)
  475. }
  476. for i := range stars {
  477. if _, err = sess.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  478. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  479. }
  480. }
  481. // ***** END: Star *****
  482. // ***** START: Follow *****
  483. followers := make([]*Follow, 0, 10)
  484. if err = x.Find(&followers, &Follow{UserID: u.Id}); err != nil {
  485. return fmt.Errorf("get all followers: %v", err)
  486. }
  487. for i := range followers {
  488. if _, err = sess.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  489. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  490. }
  491. }
  492. // ***** END: Follow *****
  493. if err = DeleteBeans(sess,
  494. &Oauth2{Uid: u.Id},
  495. &AccessToken{UID: u.Id},
  496. &Collaboration{UserID: u.Id},
  497. &Access{UserID: u.Id},
  498. &Watch{UserID: u.Id},
  499. &Star{UID: u.Id},
  500. &Follow{FollowID: u.Id},
  501. &Action{UserID: u.Id},
  502. &IssueUser{UID: u.Id},
  503. &EmailAddress{Uid: u.Id},
  504. ); err != nil {
  505. return fmt.Errorf("DeleteBeans: %v", err)
  506. }
  507. // ***** START: PublicKey *****
  508. keys := make([]*PublicKey, 0, 10)
  509. if err = sess.Find(&keys, &PublicKey{OwnerID: u.Id}); err != nil {
  510. return fmt.Errorf("get all public keys: %v", err)
  511. }
  512. for _, key := range keys {
  513. if err = deletePublicKey(sess, key); err != nil {
  514. return fmt.Errorf("deletePublicKey: %v", err)
  515. }
  516. }
  517. // ***** END: PublicKey *****
  518. // Clear assignee.
  519. if _, err = sess.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.Id); err != nil {
  520. return fmt.Errorf("clear assignee: %v", err)
  521. }
  522. if _, err = sess.Delete(u); err != nil {
  523. return fmt.Errorf("Delete: %v", err)
  524. }
  525. if err = sess.Commit(); err != nil {
  526. return fmt.Errorf("Commit: %v", err)
  527. }
  528. // FIXME: system notice
  529. // Note: There are something just cannot be roll back,
  530. // so just keep error logs of those operations.
  531. RewriteAllPublicKeys()
  532. os.RemoveAll(UserPath(u.Name))
  533. os.Remove(u.CustomAvatarPath())
  534. return nil
  535. }
  536. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  537. func DeleteInactivateUsers() (err error) {
  538. users := make([]*User, 0, 10)
  539. if err = x.Where("is_active=?", false).Find(&users); err != nil {
  540. return fmt.Errorf("get all inactive users: %v", err)
  541. }
  542. for _, u := range users {
  543. if err = DeleteUser(u); err != nil {
  544. // Ignore users that were set inactive by admin.
  545. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  546. continue
  547. }
  548. return err
  549. }
  550. }
  551. _, err = x.Where("is_activated=?", false).Delete(new(EmailAddress))
  552. return err
  553. }
  554. // UserPath returns the path absolute path of user repositories.
  555. func UserPath(userName string) string {
  556. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  557. }
  558. func GetUserByKeyId(keyId int64) (*User, error) {
  559. user := new(User)
  560. 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)
  561. if err != nil {
  562. return nil, err
  563. } else if !has {
  564. return nil, ErrUserNotKeyOwner
  565. }
  566. return user, nil
  567. }
  568. func getUserByID(e Engine, id int64) (*User, error) {
  569. u := new(User)
  570. has, err := e.Id(id).Get(u)
  571. if err != nil {
  572. return nil, err
  573. } else if !has {
  574. return nil, ErrUserNotExist{id, ""}
  575. }
  576. return u, nil
  577. }
  578. // GetUserByID returns the user object by given ID if exists.
  579. func GetUserByID(id int64) (*User, error) {
  580. return getUserByID(x, id)
  581. }
  582. // GetAssigneeByID returns the user with write access of repository by given ID.
  583. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  584. has, err := HasAccess(&User{Id: userID}, repo, ACCESS_MODE_WRITE)
  585. if err != nil {
  586. return nil, err
  587. } else if !has {
  588. return nil, ErrUserNotExist{userID, ""}
  589. }
  590. return GetUserByID(userID)
  591. }
  592. // GetUserByName returns user by given name.
  593. func GetUserByName(name string) (*User, error) {
  594. if len(name) == 0 {
  595. return nil, ErrUserNotExist{0, name}
  596. }
  597. u := &User{LowerName: strings.ToLower(name)}
  598. has, err := x.Get(u)
  599. if err != nil {
  600. return nil, err
  601. } else if !has {
  602. return nil, ErrUserNotExist{0, name}
  603. }
  604. return u, nil
  605. }
  606. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  607. func GetUserEmailsByNames(names []string) []string {
  608. mails := make([]string, 0, len(names))
  609. for _, name := range names {
  610. u, err := GetUserByName(name)
  611. if err != nil {
  612. continue
  613. }
  614. mails = append(mails, u.Email)
  615. }
  616. return mails
  617. }
  618. // GetUserIdsByNames returns a slice of ids corresponds to names.
  619. func GetUserIdsByNames(names []string) []int64 {
  620. ids := make([]int64, 0, len(names))
  621. for _, name := range names {
  622. u, err := GetUserByName(name)
  623. if err != nil {
  624. continue
  625. }
  626. ids = append(ids, u.Id)
  627. }
  628. return ids
  629. }
  630. // GetEmailAddresses returns all e-mail addresses belongs to given user.
  631. func GetEmailAddresses(uid int64) ([]*EmailAddress, error) {
  632. emails := make([]*EmailAddress, 0, 5)
  633. err := x.Where("uid=?", uid).Find(&emails)
  634. if err != nil {
  635. return nil, err
  636. }
  637. u, err := GetUserByID(uid)
  638. if err != nil {
  639. return nil, err
  640. }
  641. isPrimaryFound := false
  642. for _, email := range emails {
  643. if email.Email == u.Email {
  644. isPrimaryFound = true
  645. email.IsPrimary = true
  646. } else {
  647. email.IsPrimary = false
  648. }
  649. }
  650. // We alway want the primary email address displayed, even if it's not in
  651. // the emailaddress table (yet)
  652. if !isPrimaryFound {
  653. emails = append(emails, &EmailAddress{
  654. Email: u.Email,
  655. IsActivated: true,
  656. IsPrimary: true,
  657. })
  658. }
  659. return emails, nil
  660. }
  661. func AddEmailAddress(email *EmailAddress) error {
  662. email.Email = strings.ToLower(email.Email)
  663. used, err := IsEmailUsed(email.Email)
  664. if err != nil {
  665. return err
  666. } else if used {
  667. return ErrEmailAlreadyUsed{email.Email}
  668. }
  669. _, err = x.Insert(email)
  670. return err
  671. }
  672. func (email *EmailAddress) Activate() error {
  673. email.IsActivated = true
  674. if _, err := x.Id(email.Id).AllCols().Update(email); err != nil {
  675. return err
  676. }
  677. if user, err := GetUserByID(email.Uid); err != nil {
  678. return err
  679. } else {
  680. user.Rands = GetUserSalt()
  681. return UpdateUser(user)
  682. }
  683. }
  684. func DeleteEmailAddress(email *EmailAddress) error {
  685. has, err := x.Get(email)
  686. if err != nil {
  687. return err
  688. } else if !has {
  689. return ErrEmailNotExist
  690. }
  691. if _, err = x.Id(email.Id).Delete(email); err != nil {
  692. return err
  693. }
  694. return nil
  695. }
  696. func MakeEmailPrimary(email *EmailAddress) error {
  697. has, err := x.Get(email)
  698. if err != nil {
  699. return err
  700. } else if !has {
  701. return ErrEmailNotExist
  702. }
  703. if !email.IsActivated {
  704. return ErrEmailNotActivated
  705. }
  706. user := &User{Id: email.Uid}
  707. has, err = x.Get(user)
  708. if err != nil {
  709. return err
  710. } else if !has {
  711. return ErrUserNotExist{email.Uid, ""}
  712. }
  713. // Make sure the former primary email doesn't disappear
  714. former_primary_email := &EmailAddress{Email: user.Email}
  715. has, err = x.Get(former_primary_email)
  716. if err != nil {
  717. return err
  718. } else if !has {
  719. former_primary_email.Uid = user.Id
  720. former_primary_email.IsActivated = user.IsActive
  721. x.Insert(former_primary_email)
  722. }
  723. user.Email = email.Email
  724. _, err = x.Id(user.Id).AllCols().Update(user)
  725. return err
  726. }
  727. // UserCommit represents a commit with validation of user.
  728. type UserCommit struct {
  729. User *User
  730. *git.Commit
  731. }
  732. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  733. func ValidateCommitWithEmail(c *git.Commit) *User {
  734. u, err := GetUserByEmail(c.Author.Email)
  735. if err != nil {
  736. return nil
  737. }
  738. return u
  739. }
  740. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  741. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  742. var (
  743. u *User
  744. emails = map[string]*User{}
  745. newCommits = list.New()
  746. e = oldCommits.Front()
  747. )
  748. for e != nil {
  749. c := e.Value.(*git.Commit)
  750. if v, ok := emails[c.Author.Email]; !ok {
  751. u, _ = GetUserByEmail(c.Author.Email)
  752. emails[c.Author.Email] = u
  753. } else {
  754. u = v
  755. }
  756. newCommits.PushBack(UserCommit{
  757. User: u,
  758. Commit: c,
  759. })
  760. e = e.Next()
  761. }
  762. return newCommits
  763. }
  764. // GetUserByEmail returns the user object by given e-mail if exists.
  765. func GetUserByEmail(email string) (*User, error) {
  766. if len(email) == 0 {
  767. return nil, ErrUserNotExist{0, "email"}
  768. }
  769. email = strings.ToLower(email)
  770. // First try to find the user by primary email
  771. user := &User{Email: email}
  772. has, err := x.Get(user)
  773. if err != nil {
  774. return nil, err
  775. }
  776. if has {
  777. return user, nil
  778. }
  779. // Otherwise, check in alternative list for activated email addresses
  780. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  781. has, err = x.Get(emailAddress)
  782. if err != nil {
  783. return nil, err
  784. }
  785. if has {
  786. return GetUserByID(emailAddress.Uid)
  787. }
  788. return nil, ErrUserNotExist{0, "email"}
  789. }
  790. // SearchUserByName returns given number of users whose name contains keyword.
  791. func SearchUserByName(opt SearchOption) (us []*User, err error) {
  792. if len(opt.Keyword) == 0 {
  793. return us, nil
  794. }
  795. opt.Keyword = strings.ToLower(opt.Keyword)
  796. us = make([]*User, 0, opt.Limit)
  797. err = x.Limit(opt.Limit).Where("type=0").And("lower_name like ?", "%"+opt.Keyword+"%").Find(&us)
  798. return us, err
  799. }
  800. // Follow is connection request for receiving user notification.
  801. type Follow struct {
  802. ID int64 `xorm:"pk autoincr"`
  803. UserID int64 `xorm:"UNIQUE(follow)"`
  804. FollowID int64 `xorm:"UNIQUE(follow)"`
  805. }
  806. // FollowUser marks someone be another's follower.
  807. func FollowUser(userId int64, followId int64) (err error) {
  808. sess := x.NewSession()
  809. defer sess.Close()
  810. sess.Begin()
  811. if _, err = sess.Insert(&Follow{UserID: userId, FollowID: followId}); err != nil {
  812. sess.Rollback()
  813. return err
  814. }
  815. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  816. if _, err = sess.Exec(rawSql, followId); err != nil {
  817. sess.Rollback()
  818. return err
  819. }
  820. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  821. if _, err = sess.Exec(rawSql, userId); err != nil {
  822. sess.Rollback()
  823. return err
  824. }
  825. return sess.Commit()
  826. }
  827. // UnFollowUser unmarks someone be another's follower.
  828. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  829. session := x.NewSession()
  830. defer session.Close()
  831. session.Begin()
  832. if _, err = session.Delete(&Follow{UserID: userId, FollowID: unFollowId}); err != nil {
  833. session.Rollback()
  834. return err
  835. }
  836. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  837. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  838. session.Rollback()
  839. return err
  840. }
  841. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  842. if _, err = session.Exec(rawSql, userId); err != nil {
  843. session.Rollback()
  844. return err
  845. }
  846. return session.Commit()
  847. }
  848. func UpdateMentions(userNames []string, issueId int64) error {
  849. for i := range userNames {
  850. userNames[i] = strings.ToLower(userNames[i])
  851. }
  852. users := make([]*User, 0, len(userNames))
  853. if err := x.Where("lower_name IN (?)", strings.Join(userNames, "\",\"")).OrderBy("lower_name ASC").Find(&users); err != nil {
  854. return err
  855. }
  856. ids := make([]int64, 0, len(userNames))
  857. for _, user := range users {
  858. ids = append(ids, user.Id)
  859. if !user.IsOrganization() {
  860. continue
  861. }
  862. if user.NumMembers == 0 {
  863. continue
  864. }
  865. tempIds := make([]int64, 0, user.NumMembers)
  866. orgUsers, err := GetOrgUsersByOrgId(user.Id)
  867. if err != nil {
  868. return err
  869. }
  870. for _, orgUser := range orgUsers {
  871. tempIds = append(tempIds, orgUser.ID)
  872. }
  873. ids = append(ids, tempIds...)
  874. }
  875. if err := UpdateIssueUsersByMentions(ids, issueId); err != nil {
  876. return err
  877. }
  878. return nil
  879. }