user.go 22 KB

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