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 15KB

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