user.go 23 KB

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