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.

user.go 21KB

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