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.

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