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.

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