user.go 22 KB

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