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

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