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.

1053 lines
26 KiB

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