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.

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