You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

869 lines
21 KiB

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