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.

1179 lines
30 KiB

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