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.

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