You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 16 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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 setting.AppSubUrl + "/org/" + u.Name + "/dashboard/"
  76. }
  77. return setting.AppSubUrl + "/"
  78. }
  79. // HomeLink returns the user home page link.
  80. func (u *User) HomeLink() string {
  81. return setting.AppSubUrl + "/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. // GetFullNameFallback returns Full Name if set, otherwise username
  148. func (u *User) GetFullNameFallback() string {
  149. if u.FullName == "" {
  150. return u.Name
  151. }
  152. return u.FullName
  153. }
  154. // IsUserExist checks if given user name exist,
  155. // the user name should be noncased unique.
  156. func IsUserExist(name string) (bool, error) {
  157. if len(name) == 0 {
  158. return false, nil
  159. }
  160. return x.Get(&User{LowerName: strings.ToLower(name)})
  161. }
  162. // IsEmailUsed returns true if the e-mail has been used.
  163. func IsEmailUsed(email string) (bool, error) {
  164. if len(email) == 0 {
  165. return false, nil
  166. }
  167. return x.Get(&User{Email: email})
  168. }
  169. // GetUserSalt returns a user salt token
  170. func GetUserSalt() string {
  171. return base.GetRandomString(10)
  172. }
  173. // CreateUser creates record of a new user.
  174. func CreateUser(u *User) error {
  175. if !IsLegalName(u.Name) {
  176. return ErrUserNameIllegal
  177. }
  178. isExist, err := IsUserExist(u.Name)
  179. if err != nil {
  180. return err
  181. } else if isExist {
  182. return ErrUserAlreadyExist
  183. }
  184. isExist, err = IsEmailUsed(u.Email)
  185. if err != nil {
  186. return err
  187. } else if isExist {
  188. return ErrEmailAlreadyUsed
  189. }
  190. u.LowerName = strings.ToLower(u.Name)
  191. u.Avatar = base.EncodeMd5(u.Email)
  192. u.AvatarEmail = u.Email
  193. u.Rands = GetUserSalt()
  194. u.Salt = GetUserSalt()
  195. u.EncodePasswd()
  196. sess := x.NewSession()
  197. defer sess.Close()
  198. if err = sess.Begin(); err != nil {
  199. return err
  200. }
  201. if _, err = sess.Insert(u); err != nil {
  202. sess.Rollback()
  203. return err
  204. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  205. sess.Rollback()
  206. return err
  207. } else if err = sess.Commit(); err != nil {
  208. return err
  209. }
  210. // Auto-set admin for user whose ID is 1.
  211. if u.Id == 1 {
  212. u.IsAdmin = true
  213. u.IsActive = true
  214. _, err = x.Id(u.Id).UseBool().Update(u)
  215. }
  216. return err
  217. }
  218. // CountUsers returns number of users.
  219. func CountUsers() int64 {
  220. count, _ := x.Where("type=0").Count(new(User))
  221. return count
  222. }
  223. // GetUsers returns given number of user objects with offset.
  224. func GetUsers(num, offset int) ([]*User, error) {
  225. users := make([]*User, 0, num)
  226. err := x.Limit(num, offset).Where("type=0").Asc("id").Find(&users)
  227. return users, err
  228. }
  229. // get user by erify code
  230. func getVerifyUser(code string) (user *User) {
  231. if len(code) <= base.TimeLimitCodeLength {
  232. return nil
  233. }
  234. // use tail hex username query user
  235. hexStr := code[base.TimeLimitCodeLength:]
  236. if b, err := hex.DecodeString(hexStr); err == nil {
  237. if user, err = GetUserByName(string(b)); user != nil {
  238. return user
  239. }
  240. log.Error(4, "user.getVerifyUser: %v", err)
  241. }
  242. return nil
  243. }
  244. // verify active code when active account
  245. func VerifyUserActiveCode(code string) (user *User) {
  246. minutes := setting.Service.ActiveCodeLives
  247. if user = getVerifyUser(code); user != nil {
  248. // time limit code
  249. prefix := code[:base.TimeLimitCodeLength]
  250. data := com.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  251. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  252. return user
  253. }
  254. }
  255. return nil
  256. }
  257. // ChangeUserName changes all corresponding setting from old user name to new one.
  258. func ChangeUserName(u *User, newUserName string) (err error) {
  259. if !IsLegalName(newUserName) {
  260. return ErrUserNameIllegal
  261. }
  262. newUserName = strings.ToLower(newUserName)
  263. // Update accesses of user.
  264. accesses := make([]Access, 0, 10)
  265. if err = x.Find(&accesses, &Access{UserName: u.LowerName}); err != nil {
  266. return err
  267. }
  268. sess := x.NewSession()
  269. defer sess.Close()
  270. if err = sess.Begin(); err != nil {
  271. return err
  272. }
  273. for i := range accesses {
  274. accesses[i].UserName = newUserName
  275. if strings.HasPrefix(accesses[i].RepoName, u.LowerName+"/") {
  276. accesses[i].RepoName = strings.Replace(accesses[i].RepoName, u.LowerName, newUserName, 1)
  277. }
  278. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  279. return err
  280. }
  281. }
  282. repos, err := GetRepositories(u.Id, true)
  283. if err != nil {
  284. return err
  285. }
  286. for i := range repos {
  287. accesses = make([]Access, 0, 10)
  288. // Update accesses of user repository.
  289. if err = x.Find(&accesses, &Access{RepoName: u.LowerName + "/" + repos[i].LowerName}); err != nil {
  290. return err
  291. }
  292. for j := range accesses {
  293. // if the access is not the user's access (already updated above)
  294. if accesses[j].UserName != u.LowerName {
  295. accesses[j].RepoName = newUserName + "/" + repos[i].LowerName
  296. if err = UpdateAccessWithSession(sess, &accesses[j]); err != nil {
  297. return err
  298. }
  299. }
  300. }
  301. }
  302. // Change user directory name.
  303. if err = os.Rename(UserPath(u.LowerName), UserPath(newUserName)); err != nil {
  304. sess.Rollback()
  305. return err
  306. }
  307. return sess.Commit()
  308. }
  309. // UpdateUser updates user's information.
  310. func UpdateUser(u *User) error {
  311. u.LowerName = strings.ToLower(u.Name)
  312. if len(u.Location) > 255 {
  313. u.Location = u.Location[:255]
  314. }
  315. if len(u.Website) > 255 {
  316. u.Website = u.Website[:255]
  317. }
  318. if len(u.Description) > 255 {
  319. u.Description = u.Description[:255]
  320. }
  321. _, err := x.Id(u.Id).AllCols().Update(u)
  322. return err
  323. }
  324. // TODO: need some kind of mechanism to record failure.
  325. // DeleteUser completely and permanently deletes everything of user.
  326. func DeleteUser(u *User) error {
  327. // Check ownership of repository.
  328. count, err := GetRepositoryCount(u)
  329. if err != nil {
  330. return errors.New("GetRepositoryCount: " + err.Error())
  331. } else if count > 0 {
  332. return ErrUserOwnRepos
  333. }
  334. // Check membership of organization.
  335. count, err = u.GetOrganizationCount()
  336. if err != nil {
  337. return errors.New("modesl.GetRepositories(GetOrganizationCount): " + err.Error())
  338. } else if count > 0 {
  339. return ErrUserHasOrgs
  340. }
  341. // TODO: check issues, other repos' commits
  342. // TODO: roll backable in some point.
  343. // Delete all followers.
  344. if _, err = x.Delete(&Follow{FollowId: u.Id}); err != nil {
  345. return err
  346. }
  347. // Delete oauth2.
  348. if _, err = x.Delete(&Oauth2{Uid: u.Id}); err != nil {
  349. return err
  350. }
  351. // Delete all feeds.
  352. if _, err = x.Delete(&Action{UserId: u.Id}); err != nil {
  353. return err
  354. }
  355. // Delete all watches.
  356. if _, err = x.Delete(&Watch{UserId: u.Id}); err != nil {
  357. return err
  358. }
  359. // Delete all accesses.
  360. if _, err = x.Delete(&Access{UserName: u.LowerName}); err != nil {
  361. return err
  362. }
  363. // Delete all SSH keys.
  364. keys := make([]*PublicKey, 0, 10)
  365. if err = x.Find(&keys, &PublicKey{OwnerId: u.Id}); err != nil {
  366. return err
  367. }
  368. for _, key := range keys {
  369. if err = DeletePublicKey(key); err != nil {
  370. return err
  371. }
  372. }
  373. // Delete user directory.
  374. if err = os.RemoveAll(UserPath(u.Name)); err != nil {
  375. return err
  376. }
  377. _, err = x.Delete(u)
  378. return err
  379. }
  380. // DeleteInactivateUsers deletes all inactivate users.
  381. func DeleteInactivateUsers() error {
  382. _, err := x.Where("is_active=?", false).Delete(new(User))
  383. return err
  384. }
  385. // UserPath returns the path absolute path of user repositories.
  386. func UserPath(userName string) string {
  387. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  388. }
  389. func GetUserByKeyId(keyId int64) (*User, error) {
  390. user := new(User)
  391. rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  392. has, err := x.Sql(rawSql, keyId).Get(user)
  393. if err != nil {
  394. return nil, err
  395. } else if !has {
  396. return nil, ErrUserNotKeyOwner
  397. }
  398. return user, nil
  399. }
  400. // GetUserById returns the user object by given ID if exists.
  401. func GetUserById(id int64) (*User, error) {
  402. u := new(User)
  403. has, err := x.Id(id).Get(u)
  404. if err != nil {
  405. return nil, err
  406. } else if !has {
  407. return nil, ErrUserNotExist
  408. }
  409. return u, nil
  410. }
  411. // GetUserByName returns the user object by given name if exists.
  412. func GetUserByName(name string) (*User, error) {
  413. if len(name) == 0 {
  414. return nil, ErrUserNotExist
  415. }
  416. user := &User{LowerName: strings.ToLower(name)}
  417. has, err := x.Get(user)
  418. if err != nil {
  419. return nil, err
  420. } else if !has {
  421. return nil, ErrUserNotExist
  422. }
  423. return user, nil
  424. }
  425. // GetUserEmailsByNames returns a slice of e-mails corresponds to names.
  426. func GetUserEmailsByNames(names []string) []string {
  427. mails := make([]string, 0, len(names))
  428. for _, name := range names {
  429. u, err := GetUserByName(name)
  430. if err != nil {
  431. continue
  432. }
  433. mails = append(mails, u.Email)
  434. }
  435. return mails
  436. }
  437. // GetUserIdsByNames returns a slice of ids corresponds to names.
  438. func GetUserIdsByNames(names []string) []int64 {
  439. ids := make([]int64, 0, len(names))
  440. for _, name := range names {
  441. u, err := GetUserByName(name)
  442. if err != nil {
  443. continue
  444. }
  445. ids = append(ids, u.Id)
  446. }
  447. return ids
  448. }
  449. // GetUserByEmail returns the user object by given e-mail if exists.
  450. func GetUserByEmail(email string) (*User, error) {
  451. if len(email) == 0 {
  452. return nil, ErrUserNotExist
  453. }
  454. user := &User{Email: strings.ToLower(email)}
  455. has, err := x.Get(user)
  456. if err != nil {
  457. return nil, err
  458. } else if !has {
  459. return nil, ErrUserNotExist
  460. }
  461. return user, nil
  462. }
  463. // SearchUserByName returns given number of users whose name contains keyword.
  464. func SearchUserByName(opt SearchOption) (us []*User, err error) {
  465. // Prevent SQL inject.
  466. opt.Keyword = strings.TrimSpace(opt.Keyword)
  467. if len(opt.Keyword) == 0 {
  468. return us, nil
  469. }
  470. opt.Keyword = strings.Split(opt.Keyword, " ")[0]
  471. if len(opt.Keyword) == 0 {
  472. return us, nil
  473. }
  474. opt.Keyword = strings.ToLower(opt.Keyword)
  475. us = make([]*User, 0, opt.Limit)
  476. err = x.Limit(opt.Limit).Where("type=0").And("lower_name like '%" + opt.Keyword + "%'").Find(&us)
  477. return us, err
  478. }
  479. // Follow is connection request for receiving user notifycation.
  480. type Follow struct {
  481. Id int64
  482. UserId int64 `xorm:"unique(follow)"`
  483. FollowId int64 `xorm:"unique(follow)"`
  484. }
  485. // FollowUser marks someone be another's follower.
  486. func FollowUser(userId int64, followId int64) (err error) {
  487. session := x.NewSession()
  488. defer session.Close()
  489. session.Begin()
  490. if _, err = session.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  491. session.Rollback()
  492. return err
  493. }
  494. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  495. if _, err = session.Exec(rawSql, followId); err != nil {
  496. session.Rollback()
  497. return err
  498. }
  499. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  500. if _, err = session.Exec(rawSql, userId); err != nil {
  501. session.Rollback()
  502. return err
  503. }
  504. return session.Commit()
  505. }
  506. // UnFollowUser unmarks someone be another's follower.
  507. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  508. session := x.NewSession()
  509. defer session.Close()
  510. session.Begin()
  511. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
  512. session.Rollback()
  513. return err
  514. }
  515. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  516. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  517. session.Rollback()
  518. return err
  519. }
  520. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  521. if _, err = session.Exec(rawSql, userId); err != nil {
  522. session.Rollback()
  523. return err
  524. }
  525. return session.Commit()
  526. }
  527. func UpdateMentions(userNames []string, issueId int64) error {
  528. users := make([]*User, 0, len(userNames))
  529. if err := x.Where("name IN (?)", strings.Join(userNames, "\",\"")).OrderBy("name ASC").Find(&users); err != nil {
  530. return err
  531. }
  532. ids := make([]int64, 0, len(userNames))
  533. for _, user := range users {
  534. ids = append(ids, user.Id)
  535. if user.Type == INDIVIDUAL {
  536. continue
  537. }
  538. if user.NumMembers == 0 {
  539. continue
  540. }
  541. tempIds := make([]int64, 0, user.NumMembers)
  542. orgUsers, err := GetOrgUsersByOrgId(user.Id)
  543. if err != nil {
  544. return err
  545. }
  546. for _, orgUser := range orgUsers {
  547. tempIds = append(tempIds, orgUser.Id)
  548. }
  549. ids = append(ids, tempIds...)
  550. }
  551. if err := UpdateIssueUserPairsByMentions(ids, issueId); err != nil {
  552. return err
  553. }
  554. return nil
  555. }