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.

user.go 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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"
  13. "path/filepath"
  14. "strings"
  15. "time"
  16. "github.com/Unknwon/com"
  17. "github.com/gogits/gogs/modules/base"
  18. "github.com/gogits/gogs/modules/git"
  19. "github.com/gogits/gogs/modules/log"
  20. "github.com/gogits/gogs/modules/setting"
  21. )
  22. type UserType int
  23. const (
  24. INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  25. ORGANIZATION
  26. )
  27. var (
  28. ErrUserOwnRepos = errors.New("User still have ownership of repositories")
  29. ErrUserHasOrgs = errors.New("User still have membership of organization")
  30. ErrUserAlreadyExist = errors.New("User already exist")
  31. ErrUserNotExist = errors.New("User does not exist")
  32. ErrUserNotKeyOwner = errors.New("User does not the owner of public key")
  33. ErrEmailAlreadyUsed = errors.New("E-mail already used")
  34. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  35. ErrLoginSourceNotExist = errors.New("Login source does not exist")
  36. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  37. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  38. )
  39. // User represents the object of individual and member of organization.
  40. type User struct {
  41. Id int64
  42. LowerName string `xorm:"UNIQUE NOT NULL"`
  43. Name string `xorm:"UNIQUE NOT NULL"`
  44. FullName string
  45. Email string `xorm:"UNIQUE NOT NULL"`
  46. Passwd string `xorm:"NOT NULL"`
  47. LoginType LoginType
  48. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  49. LoginName string
  50. Type UserType
  51. Orgs []*User `xorm:"-"`
  52. Repos []*Repository `xorm:"-"`
  53. NumFollowers int
  54. NumFollowings int
  55. NumStars int
  56. NumRepos int
  57. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  58. AvatarEmail string `xorm:"NOT NULL"`
  59. Location string
  60. Website string
  61. IsActive bool
  62. IsAdmin 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 "/" + path.Join(setting.AppSubUrl, u.Name)
  84. }
  85. // AvatarLink returns user gravatar link.
  86. func (u *User) AvatarLink() string {
  87. if setting.DisableGravatar {
  88. return "/img/avatar_default.jpg"
  89. } else if setting.Service.EnableCacheAvatar {
  90. return "/avatar/" + u.Avatar
  91. }
  92. return "//1.gravatar.com/avatar/" + 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 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. // TODO: need some kind of mechanism to record failure.
  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("modesl.GetRepositories(GetOrganizationCount): " + err.Error())
  340. } else if count > 0 {
  341. return ErrUserHasOrgs
  342. }
  343. // TODO: check issues, other repos' commits
  344. // TODO: 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 the user object by given name if exists.
  414. func GetUserByName(name string) (*User, error) {
  415. if len(name) == 0 {
  416. return nil, ErrUserNotExist
  417. }
  418. user := &User{LowerName: strings.ToLower(name)}
  419. has, err := x.Get(user)
  420. if err != nil {
  421. return nil, err
  422. } else if !has {
  423. return nil, ErrUserNotExist
  424. }
  425. return user, nil
  426. }
  427. // GetUserEmailsByNames returns a slice 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. // ValidCommitsWithEmails checks if authors' e-mails of commits are correcponding to users.
  457. func ValidCommitsWithEmails(oldCommits *list.List) *list.List {
  458. emails := map[string]string{}
  459. newCommits := list.New()
  460. e := oldCommits.Front()
  461. for e != nil {
  462. c := e.Value.(*git.Commit)
  463. uname := ""
  464. if v, ok := emails[c.Author.Email]; !ok {
  465. u, err := GetUserByEmail(c.Author.Email)
  466. if err == nil {
  467. uname = u.Name
  468. }
  469. emails[c.Author.Email] = uname
  470. } else {
  471. uname = v
  472. }
  473. newCommits.PushBack(UserCommit{
  474. UserName: uname,
  475. Commit: c,
  476. })
  477. e = e.Next()
  478. }
  479. return newCommits
  480. }
  481. // GetUserByEmail returns the user object by given e-mail if exists.
  482. func GetUserByEmail(email string) (*User, error) {
  483. if len(email) == 0 {
  484. return nil, ErrUserNotExist
  485. }
  486. user := &User{Email: strings.ToLower(email)}
  487. has, err := x.Get(user)
  488. if err != nil {
  489. return nil, err
  490. } else if !has {
  491. return nil, ErrUserNotExist
  492. }
  493. return user, nil
  494. }
  495. // SearchUserByName returns given number of users whose name contains keyword.
  496. func SearchUserByName(opt SearchOption) (us []*User, err error) {
  497. // Prevent SQL inject.
  498. opt.Keyword = strings.TrimSpace(opt.Keyword)
  499. if len(opt.Keyword) == 0 {
  500. return us, nil
  501. }
  502. opt.Keyword = strings.Split(opt.Keyword, " ")[0]
  503. if len(opt.Keyword) == 0 {
  504. return us, nil
  505. }
  506. opt.Keyword = strings.ToLower(opt.Keyword)
  507. us = make([]*User, 0, opt.Limit)
  508. err = x.Limit(opt.Limit).Where("type=0").And("lower_name like '%" + opt.Keyword + "%'").Find(&us)
  509. return us, err
  510. }
  511. // Follow is connection request for receiving user notifycation.
  512. type Follow struct {
  513. Id int64
  514. UserId int64 `xorm:"unique(follow)"`
  515. FollowId int64 `xorm:"unique(follow)"`
  516. }
  517. // FollowUser marks someone be another's follower.
  518. func FollowUser(userId int64, followId int64) (err error) {
  519. session := x.NewSession()
  520. defer session.Close()
  521. session.Begin()
  522. if _, err = session.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  523. session.Rollback()
  524. return err
  525. }
  526. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  527. if _, err = session.Exec(rawSql, followId); err != nil {
  528. session.Rollback()
  529. return err
  530. }
  531. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  532. if _, err = session.Exec(rawSql, userId); err != nil {
  533. session.Rollback()
  534. return err
  535. }
  536. return session.Commit()
  537. }
  538. // UnFollowUser unmarks someone be another's follower.
  539. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  540. session := x.NewSession()
  541. defer session.Close()
  542. session.Begin()
  543. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
  544. session.Rollback()
  545. return err
  546. }
  547. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  548. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  549. session.Rollback()
  550. return err
  551. }
  552. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  553. if _, err = session.Exec(rawSql, userId); err != nil {
  554. session.Rollback()
  555. return err
  556. }
  557. return session.Commit()
  558. }
  559. func UpdateMentions(userNames []string, issueId int64) error {
  560. users := make([]*User, 0, len(userNames))
  561. if err := x.Where("name IN (?)", strings.Join(userNames, "\",\"")).OrderBy("name ASC").Find(&users); err != nil {
  562. return err
  563. }
  564. ids := make([]int64, 0, len(userNames))
  565. for _, user := range users {
  566. ids = append(ids, user.Id)
  567. if user.Type == INDIVIDUAL {
  568. continue
  569. }
  570. if user.NumMembers == 0 {
  571. continue
  572. }
  573. tempIds := make([]int64, 0, user.NumMembers)
  574. orgUsers, err := GetOrgUsersByOrgId(user.Id)
  575. if err != nil {
  576. return err
  577. }
  578. for _, orgUser := range orgUsers {
  579. tempIds = append(tempIds, orgUser.Id)
  580. }
  581. ids = append(ids, tempIds...)
  582. }
  583. if err := UpdateIssueUserPairsByMentions(ids, issueId); err != nil {
  584. return err
  585. }
  586. return nil
  587. }