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

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