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.

992 lines
24 KiB

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