user.go 16 KB

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