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