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 22KB

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