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.

686 lines
17 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
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
  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. "container/list"
  7. "crypto/sha256"
  8. "encoding/hex"
  9. "errors"
  10. "fmt"
  11. "os"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "github.com/Unknwon/com"
  16. "github.com/gogits/gogs/modules/base"
  17. "github.com/gogits/gogs/modules/git"
  18. "github.com/gogits/gogs/modules/log"
  19. "github.com/gogits/gogs/modules/setting"
  20. )
  21. type UserType int
  22. const (
  23. INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  24. ORGANIZATION
  25. )
  26. var (
  27. ErrUserOwnRepos = errors.New("User still have ownership of repositories")
  28. ErrUserHasOrgs = errors.New("User still have membership of organization")
  29. ErrUserAlreadyExist = errors.New("User already exist")
  30. ErrUserNotExist = errors.New("User does not exist")
  31. ErrUserNotKeyOwner = errors.New("User does not the owner of public key")
  32. ErrEmailAlreadyUsed = errors.New("E-mail already used")
  33. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  34. ErrLoginSourceNotExist = errors.New("Login source does not exist")
  35. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  36. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  37. )
  38. // User represents the object of individual and member of organization.
  39. type User struct {
  40. Id int64
  41. LowerName string `xorm:"UNIQUE NOT NULL"`
  42. Name string `xorm:"UNIQUE NOT NULL"`
  43. FullName string
  44. Email string `xorm:"UNIQUE NOT NULL"`
  45. Passwd string `xorm:"NOT NULL"`
  46. LoginType LoginType
  47. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  48. LoginName string
  49. Type UserType
  50. Orgs []*User `xorm:"-"`
  51. Repos []*Repository `xorm:"-"`
  52. NumFollowers int
  53. NumFollowings int
  54. NumStars int
  55. NumRepos int
  56. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  57. AvatarEmail string `xorm:"NOT NULL"`
  58. Location string
  59. Website string
  60. IsActive bool
  61. IsAdmin bool
  62. AllowGitHook bool
  63. Rands string `xorm:"VARCHAR(10)"`
  64. Salt string `xorm:"VARCHAR(10)"`
  65. Created time.Time `xorm:"CREATED"`
  66. Updated time.Time `xorm:"UPDATED"`
  67. // For organization.
  68. Description string
  69. NumTeams int
  70. NumMembers int
  71. Teams []*Team `xorm:"-"`
  72. Members []*User `xorm:"-"`
  73. }
  74. // DashboardLink returns the user dashboard page link.
  75. func (u *User) DashboardLink() string {
  76. if u.IsOrganization() {
  77. return setting.AppSubUrl + "/org/" + u.Name + "/dashboard/"
  78. }
  79. return setting.AppSubUrl + "/"
  80. }
  81. // HomeLink returns the user home page link.
  82. func (u *User) HomeLink() string {
  83. return setting.AppSubUrl + "/" + u.Name
  84. }
  85. // AvatarLink returns user gravatar link.
  86. func (u *User) AvatarLink() string {
  87. if setting.DisableGravatar {
  88. return setting.AppSubUrl + "/img/avatar_default.jpg"
  89. } else if setting.Service.EnableCacheAvatar {
  90. return setting.AppSubUrl + "/avatar/" + u.Avatar
  91. }
  92. return setting.GravatarSource + u.Avatar
  93. }
  94. // NewGitSig generates and returns the signature of given user.
  95. func (u *User) NewGitSig() *git.Signature {
  96. return &git.Signature{
  97. Name: u.Name,
  98. Email: u.Email,
  99. When: time.Now(),
  100. }
  101. }
  102. // EncodePasswd encodes password to safe format.
  103. func (u *User) EncodePasswd() {
  104. newPasswd := base.PBKDF2([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  105. u.Passwd = fmt.Sprintf("%x", newPasswd)
  106. }
  107. // ValidtePassword checks if given password matches the one belongs to the user.
  108. func (u *User) ValidtePassword(passwd string) bool {
  109. newUser := &User{Passwd: passwd, Salt: u.Salt}
  110. newUser.EncodePasswd()
  111. return u.Passwd == newUser.Passwd
  112. }
  113. // IsOrganization returns true if user is actually a organization.
  114. func (u *User) IsOrganization() bool {
  115. return u.Type == ORGANIZATION
  116. }
  117. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  118. func (u *User) IsUserOrgOwner(orgId int64) bool {
  119. return IsOrganizationOwner(orgId, u.Id)
  120. }
  121. // IsPublicMember returns true if user public his/her membership in give organization.
  122. func (u *User) IsPublicMember(orgId int64) bool {
  123. return IsPublicMembership(orgId, u.Id)
  124. }
  125. // GetOrganizationCount returns count of membership of organization of user.
  126. func (u *User) GetOrganizationCount() (int64, error) {
  127. return x.Where("uid=?", u.Id).Count(new(OrgUser))
  128. }
  129. // GetRepositories returns all repositories that user owns, including private repositories.
  130. func (u *User) GetRepositories() (err error) {
  131. u.Repos, err = GetRepositories(u.Id, true)
  132. return err
  133. }
  134. // GetOrganizations returns all organizations that user belongs to.
  135. func (u *User) GetOrganizations() error {
  136. ous, err := GetOrgUsersByUserId(u.Id)
  137. if err != nil {
  138. return err
  139. }
  140. u.Orgs = make([]*User, len(ous))
  141. for i, ou := range ous {
  142. u.Orgs[i], err = GetUserById(ou.OrgId)
  143. if err != nil {
  144. return err
  145. }
  146. }
  147. return nil
  148. }
  149. // GetFullNameFallback returns Full Name if set, otherwise username
  150. func (u *User) GetFullNameFallback() string {
  151. if u.FullName == "" {
  152. return u.Name
  153. }
  154. return u.FullName
  155. }
  156. // IsUserExist checks if given user name exist,
  157. // the user name should be noncased unique.
  158. func IsUserExist(name string) (bool, error) {
  159. if len(name) == 0 {
  160. return false, nil
  161. }
  162. return x.Get(&User{LowerName: strings.ToLower(name)})
  163. }
  164. // IsEmailUsed returns true if the e-mail has been used.
  165. func IsEmailUsed(email string) (bool, error) {
  166. if len(email) == 0 {
  167. return false, nil
  168. }
  169. return x.Get(&User{Email: email})
  170. }
  171. // GetUserSalt returns a ramdom user salt token.
  172. func GetUserSalt() string {
  173. return base.GetRandomString(10)
  174. }
  175. // CreateUser creates record of a new user.
  176. func CreateUser(u *User) error {
  177. if !IsLegalName(u.Name) {
  178. return ErrUserNameIllegal
  179. }
  180. isExist, err := IsUserExist(u.Name)
  181. if err != nil {
  182. return err
  183. } else if isExist {
  184. return ErrUserAlreadyExist
  185. }
  186. isExist, err = IsEmailUsed(u.Email)
  187. if err != nil {
  188. return err
  189. } else if isExist {
  190. return ErrEmailAlreadyUsed
  191. }
  192. u.LowerName = strings.ToLower(u.Name)
  193. u.Avatar = base.EncodeMd5(u.Email)
  194. u.AvatarEmail = u.Email
  195. u.Rands = GetUserSalt()
  196. u.Salt = GetUserSalt()
  197. u.EncodePasswd()
  198. sess := x.NewSession()
  199. defer sess.Close()
  200. if err = sess.Begin(); err != nil {
  201. return err
  202. }
  203. if _, err = sess.Insert(u); err != nil {
  204. sess.Rollback()
  205. return err
  206. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  207. sess.Rollback()
  208. return err
  209. } else if err = sess.Commit(); err != nil {
  210. return err
  211. }
  212. // Auto-set admin for user whose ID is 1.
  213. if u.Id == 1 {
  214. u.IsAdmin = true
  215. u.IsActive = true
  216. _, err = x.Id(u.Id).UseBool().Update(u)
  217. }
  218. return err
  219. }
  220. // CountUsers returns number of users.
  221. func CountUsers() int64 {
  222. count, _ := x.Where("type=0").Count(new(User))
  223. return count
  224. }
  225. // GetUsers returns given number of user objects with offset.
  226. func GetUsers(num, offset int) ([]*User, error) {
  227. users := make([]*User, 0, num)
  228. err := x.Limit(num, offset).Where("type=0").Asc("id").Find(&users)
  229. return users, err
  230. }
  231. // get user by erify code
  232. func getVerifyUser(code string) (user *User) {
  233. if len(code) <= base.TimeLimitCodeLength {
  234. return nil
  235. }
  236. // use tail hex username query user
  237. hexStr := code[base.TimeLimitCodeLength:]
  238. if b, err := hex.DecodeString(hexStr); err == nil {
  239. if user, err = GetUserByName(string(b)); user != nil {
  240. return user
  241. }
  242. log.Error(4, "user.getVerifyUser: %v", err)
  243. }
  244. return nil
  245. }
  246. // verify active code when active account
  247. func VerifyUserActiveCode(code string) (user *User) {
  248. minutes := setting.Service.ActiveCodeLives
  249. if user = getVerifyUser(code); user != nil {
  250. // time limit code
  251. prefix := code[:base.TimeLimitCodeLength]
  252. data := com.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  253. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  254. return user
  255. }
  256. }
  257. return nil
  258. }
  259. // ChangeUserName changes all corresponding setting from old user name to new one.
  260. func ChangeUserName(u *User, newUserName string) (err error) {
  261. if !IsLegalName(newUserName) {
  262. return ErrUserNameIllegal
  263. }
  264. newUserName = strings.ToLower(newUserName)
  265. // Update accesses of user.
  266. accesses := make([]Access, 0, 10)
  267. if err = x.Find(&accesses, &Access{UserName: u.LowerName}); err != nil {
  268. return err
  269. }
  270. sess := x.NewSession()
  271. defer sess.Close()
  272. if err = sess.Begin(); err != nil {
  273. return err
  274. }
  275. for i := range accesses {
  276. accesses[i].UserName = newUserName
  277. if strings.HasPrefix(accesses[i].RepoName, u.LowerName+"/") {
  278. accesses[i].RepoName = strings.Replace(accesses[i].RepoName, u.LowerName, newUserName, 1)
  279. }
  280. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  281. return err
  282. }
  283. }
  284. repos, err := GetRepositories(u.Id, true)
  285. if err != nil {
  286. return err
  287. }
  288. for i := range repos {
  289. accesses = make([]Access, 0, 10)
  290. // Update accesses of user repository.
  291. if err = x.Find(&accesses, &Access{RepoName: u.LowerName + "/" + repos[i].LowerName}); err != nil {
  292. return err
  293. }
  294. for j := range accesses {
  295. // if the access is not the user's access (already updated above)
  296. if accesses[j].UserName != u.LowerName {
  297. accesses[j].RepoName = newUserName + "/" + repos[i].LowerName
  298. if err = UpdateAccessWithSession(sess, &accesses[j]); err != nil {
  299. return err
  300. }
  301. }
  302. }
  303. }
  304. // Change user directory name.
  305. if err = os.Rename(UserPath(u.LowerName), UserPath(newUserName)); err != nil {
  306. sess.Rollback()
  307. return err
  308. }
  309. return sess.Commit()
  310. }
  311. // UpdateUser updates user's information.
  312. func UpdateUser(u *User) error {
  313. u.LowerName = strings.ToLower(u.Name)
  314. if len(u.Location) > 255 {
  315. u.Location = u.Location[:255]
  316. }
  317. if len(u.Website) > 255 {
  318. u.Website = u.Website[:255]
  319. }
  320. if len(u.Description) > 255 {
  321. u.Description = u.Description[:255]
  322. }
  323. _, err := x.Id(u.Id).AllCols().Update(u)
  324. return err
  325. }
  326. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  327. // DeleteUser completely and permanently deletes everything of user.
  328. func DeleteUser(u *User) error {
  329. // Check ownership of repository.
  330. count, err := GetRepositoryCount(u)
  331. if err != nil {
  332. return errors.New("GetRepositoryCount: " + err.Error())
  333. } else if count > 0 {
  334. return ErrUserOwnRepos
  335. }
  336. // Check membership of organization.
  337. count, err = u.GetOrganizationCount()
  338. if err != nil {
  339. return errors.New("GetOrganizationCount: " + err.Error())
  340. } else if count > 0 {
  341. return ErrUserHasOrgs
  342. }
  343. // FIXME: check issues, other repos' commits
  344. // FIXME: roll backable in some point.
  345. // Delete all followers.
  346. if _, err = x.Delete(&Follow{FollowId: u.Id}); err != nil {
  347. return err
  348. }
  349. // Delete oauth2.
  350. if _, err = x.Delete(&Oauth2{Uid: u.Id}); err != nil {
  351. return err
  352. }
  353. // Delete all feeds.
  354. if _, err = x.Delete(&Action{UserId: u.Id}); err != nil {
  355. return err
  356. }
  357. // Delete all watches.
  358. if _, err = x.Delete(&Watch{UserId: u.Id}); err != nil {
  359. return err
  360. }
  361. // Delete all accesses.
  362. if _, err = x.Delete(&Access{UserName: u.LowerName}); err != nil {
  363. return err
  364. }
  365. // Delete all SSH keys.
  366. keys := make([]*PublicKey, 0, 10)
  367. if err = x.Find(&keys, &PublicKey{OwnerId: u.Id}); err != nil {
  368. return err
  369. }
  370. for _, key := range keys {
  371. if err = DeletePublicKey(key); err != nil {
  372. return err
  373. }
  374. }
  375. // Delete user directory.
  376. if err = os.RemoveAll(UserPath(u.Name)); err != nil {
  377. return err
  378. }
  379. _, err = x.Delete(u)
  380. return err
  381. }
  382. // DeleteInactivateUsers deletes all inactivate users.
  383. func DeleteInactivateUsers() error {
  384. _, err := x.Where("is_active=?", false).Delete(new(User))
  385. return err
  386. }
  387. // UserPath returns the path absolute path of user repositories.
  388. func UserPath(userName string) string {
  389. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  390. }
  391. func GetUserByKeyId(keyId int64) (*User, error) {
  392. user := new(User)
  393. rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  394. has, err := x.Sql(rawSql, keyId).Get(user)
  395. if err != nil {
  396. return nil, err
  397. } else if !has {
  398. return nil, ErrUserNotKeyOwner
  399. }
  400. return user, nil
  401. }
  402. // GetUserById returns the user object by given ID if exists.
  403. func GetUserById(id int64) (*User, error) {
  404. u := new(User)
  405. has, err := x.Id(id).Get(u)
  406. if err != nil {
  407. return nil, err
  408. } else if !has {
  409. return nil, ErrUserNotExist
  410. }
  411. return u, nil
  412. }
  413. // GetUserByName returns user by given name.
  414. func GetUserByName(name string) (*User, error) {
  415. if len(name) == 0 {
  416. return nil, ErrUserNotExist
  417. }
  418. u := &User{LowerName: strings.ToLower(name)}
  419. has, err := x.Get(u)
  420. if err != nil {
  421. return nil, err
  422. } else if !has {
  423. return nil, ErrUserNotExist
  424. }
  425. return u, nil
  426. }
  427. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  428. func GetUserEmailsByNames(names []string) []string {
  429. mails := make([]string, 0, len(names))
  430. for _, name := range names {
  431. u, err := GetUserByName(name)
  432. if err != nil {
  433. continue
  434. }
  435. mails = append(mails, u.Email)
  436. }
  437. return mails
  438. }
  439. // GetUserIdsByNames returns a slice of ids corresponds to names.
  440. func GetUserIdsByNames(names []string) []int64 {
  441. ids := make([]int64, 0, len(names))
  442. for _, name := range names {
  443. u, err := GetUserByName(name)
  444. if err != nil {
  445. continue
  446. }
  447. ids = append(ids, u.Id)
  448. }
  449. return ids
  450. }
  451. // UserCommit represtns a commit with validation of user.
  452. type UserCommit struct {
  453. UserName string
  454. *git.Commit
  455. }
  456. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  457. func ValidateCommitWithEmail(c *git.Commit) (uname string) {
  458. u, err := GetUserByEmail(c.Author.Email)
  459. if err == nil {
  460. uname = u.Name
  461. }
  462. return uname
  463. }
  464. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  465. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  466. emails := map[string]string{}
  467. newCommits := list.New()
  468. e := oldCommits.Front()
  469. for e != nil {
  470. c := e.Value.(*git.Commit)
  471. uname := ""
  472. if v, ok := emails[c.Author.Email]; !ok {
  473. u, err := GetUserByEmail(c.Author.Email)
  474. if err == nil {
  475. uname = u.Name
  476. }
  477. emails[c.Author.Email] = uname
  478. } else {
  479. uname = v
  480. }
  481. newCommits.PushBack(UserCommit{
  482. UserName: uname,
  483. Commit: c,
  484. })
  485. e = e.Next()
  486. }
  487. return newCommits
  488. }
  489. // GetUserByEmail returns the user object by given e-mail if exists.
  490. func GetUserByEmail(email string) (*User, error) {
  491. if len(email) == 0 {
  492. return nil, ErrUserNotExist
  493. }
  494. user := &User{Email: strings.ToLower(email)}
  495. has, err := x.Get(user)
  496. if err != nil {
  497. return nil, err
  498. } else if !has {
  499. return nil, ErrUserNotExist
  500. }
  501. return user, nil
  502. }
  503. // SearchUserByName returns given number of users whose name contains keyword.
  504. func SearchUserByName(opt SearchOption) (us []*User, err error) {
  505. opt.Keyword = FilterSQLInject(opt.Keyword)
  506. if len(opt.Keyword) == 0 {
  507. return us, nil
  508. }
  509. opt.Keyword = strings.ToLower(opt.Keyword)
  510. us = make([]*User, 0, opt.Limit)
  511. err = x.Limit(opt.Limit).Where("type=0").And("lower_name like ?", "%"+opt.Keyword+"%").Find(&us)
  512. return us, err
  513. }
  514. // Follow is connection request for receiving user notifycation.
  515. type Follow struct {
  516. Id int64
  517. UserId int64 `xorm:"unique(follow)"`
  518. FollowId int64 `xorm:"unique(follow)"`
  519. }
  520. // FollowUser marks someone be another's follower.
  521. func FollowUser(userId int64, followId int64) (err error) {
  522. sess := x.NewSession()
  523. defer sess.Close()
  524. sess.Begin()
  525. if _, err = sess.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  526. sess.Rollback()
  527. return err
  528. }
  529. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  530. if _, err = sess.Exec(rawSql, followId); err != nil {
  531. sess.Rollback()
  532. return err
  533. }
  534. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  535. if _, err = sess.Exec(rawSql, userId); err != nil {
  536. sess.Rollback()
  537. return err
  538. }
  539. return sess.Commit()
  540. }
  541. // UnFollowUser unmarks someone be another's follower.
  542. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  543. session := x.NewSession()
  544. defer session.Close()
  545. session.Begin()
  546. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
  547. session.Rollback()
  548. return err
  549. }
  550. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  551. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  552. session.Rollback()
  553. return err
  554. }
  555. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  556. if _, err = session.Exec(rawSql, userId); err != nil {
  557. session.Rollback()
  558. return err
  559. }
  560. return session.Commit()
  561. }
  562. func UpdateMentions(userNames []string, issueId int64) error {
  563. users := make([]*User, 0, len(userNames))
  564. if err := x.Where("name IN (?)", strings.Join(userNames, "\",\"")).OrderBy("name ASC").Find(&users); err != nil {
  565. return err
  566. }
  567. ids := make([]int64, 0, len(userNames))
  568. for _, user := range users {
  569. ids = append(ids, user.Id)
  570. if user.Type == INDIVIDUAL {
  571. continue
  572. }
  573. if user.NumMembers == 0 {
  574. continue
  575. }
  576. tempIds := make([]int64, 0, user.NumMembers)
  577. orgUsers, err := GetOrgUsersByOrgId(user.Id)
  578. if err != nil {
  579. return err
  580. }
  581. for _, orgUser := range orgUsers {
  582. tempIds = append(tempIds, orgUser.Id)
  583. }
  584. ids = append(ids, tempIds...)
  585. }
  586. if err := UpdateIssueUserPairsByMentions(ids, issueId); err != nil {
  587. return err
  588. }
  589. return nil
  590. }