user.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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. // GetUsers returns given number of user objects with offset.
  186. func GetUsers(num, offset int) ([]User, error) {
  187. users := make([]User, 0, num)
  188. err := x.Limit(num, offset).Where("type=0").Asc("id").Find(&users)
  189. return users, err
  190. }
  191. // get user by erify code
  192. func getVerifyUser(code string) (user *User) {
  193. if len(code) <= base.TimeLimitCodeLength {
  194. return nil
  195. }
  196. // use tail hex username query user
  197. hexStr := code[base.TimeLimitCodeLength:]
  198. if b, err := hex.DecodeString(hexStr); err == nil {
  199. if user, err = GetUserByName(string(b)); user != nil {
  200. return user
  201. }
  202. log.Error("user.getVerifyUser: %v", err)
  203. }
  204. return nil
  205. }
  206. // verify active code when active account
  207. func VerifyUserActiveCode(code string) (user *User) {
  208. minutes := setting.Service.ActiveCodeLives
  209. if user = getVerifyUser(code); user != nil {
  210. // time limit code
  211. prefix := code[:base.TimeLimitCodeLength]
  212. data := base.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  213. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  214. return user
  215. }
  216. }
  217. return nil
  218. }
  219. // ChangeUserName changes all corresponding setting from old user name to new one.
  220. func ChangeUserName(user *User, newUserName string) (err error) {
  221. newUserName = strings.ToLower(newUserName)
  222. // Update accesses of user.
  223. accesses := make([]Access, 0, 10)
  224. if err = x.Find(&accesses, &Access{UserName: user.LowerName}); err != nil {
  225. return err
  226. }
  227. sess := x.NewSession()
  228. defer sess.Close()
  229. if err = sess.Begin(); err != nil {
  230. return err
  231. }
  232. for i := range accesses {
  233. accesses[i].UserName = newUserName
  234. if strings.HasPrefix(accesses[i].RepoName, user.LowerName+"/") {
  235. accesses[i].RepoName = strings.Replace(accesses[i].RepoName, user.LowerName, newUserName, 1)
  236. }
  237. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  238. return err
  239. }
  240. }
  241. repos, err := GetRepositories(user.Id, true)
  242. if err != nil {
  243. return err
  244. }
  245. for i := range repos {
  246. accesses = make([]Access, 0, 10)
  247. // Update accesses of user repository.
  248. if err = x.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repos[i].LowerName}); err != nil {
  249. return err
  250. }
  251. for j := range accesses {
  252. accesses[j].UserName = newUserName
  253. accesses[j].RepoName = newUserName + "/" + repos[i].LowerName
  254. if err = UpdateAccessWithSession(sess, &accesses[j]); err != nil {
  255. return err
  256. }
  257. }
  258. }
  259. // Change user directory name.
  260. if err = os.Rename(UserPath(user.LowerName), UserPath(newUserName)); err != nil {
  261. sess.Rollback()
  262. return err
  263. }
  264. return sess.Commit()
  265. }
  266. // UpdateUser updates user's information.
  267. func UpdateUser(u *User) (err error) {
  268. u.LowerName = strings.ToLower(u.Name)
  269. if len(u.Location) > 255 {
  270. u.Location = u.Location[:255]
  271. }
  272. if len(u.Website) > 255 {
  273. u.Website = u.Website[:255]
  274. }
  275. if len(u.Description) > 255 {
  276. u.Description = u.Description[:255]
  277. }
  278. _, err = x.Id(u.Id).AllCols().Update(u)
  279. return err
  280. }
  281. // TODO: need some kind of mechanism to record failure.
  282. // DeleteUser completely and permanently deletes everything of user.
  283. func DeleteUser(u *User) error {
  284. // Check ownership of repository.
  285. count, err := GetRepositoryCount(u)
  286. if err != nil {
  287. return errors.New("modesl.GetRepositories(GetRepositoryCount): " + err.Error())
  288. } else if count > 0 {
  289. return ErrUserOwnRepos
  290. }
  291. // Check membership of organization.
  292. count, err = u.GetOrganizationCount()
  293. if err != nil {
  294. return errors.New("modesl.GetRepositories(GetOrganizationCount): " + err.Error())
  295. } else if count > 0 {
  296. return ErrUserHasOrgs
  297. }
  298. // TODO: check issues, other repos' commits
  299. // TODO: roll backable in some point.
  300. // Delete all followers.
  301. if _, err = x.Delete(&Follow{FollowId: u.Id}); err != nil {
  302. return err
  303. }
  304. // Delete oauth2.
  305. if _, err = x.Delete(&Oauth2{Uid: u.Id}); err != nil {
  306. return err
  307. }
  308. // Delete all feeds.
  309. if _, err = x.Delete(&Action{UserId: u.Id}); err != nil {
  310. return err
  311. }
  312. // Delete all watches.
  313. if _, err = x.Delete(&Watch{UserId: u.Id}); err != nil {
  314. return err
  315. }
  316. // Delete all accesses.
  317. if _, err = x.Delete(&Access{UserName: u.LowerName}); err != nil {
  318. return err
  319. }
  320. // Delete all SSH keys.
  321. keys := make([]*PublicKey, 0, 10)
  322. if err = x.Find(&keys, &PublicKey{OwnerId: u.Id}); err != nil {
  323. return err
  324. }
  325. for _, key := range keys {
  326. if err = DeletePublicKey(key); err != nil {
  327. return err
  328. }
  329. }
  330. // Delete user directory.
  331. if err = os.RemoveAll(UserPath(u.Name)); err != nil {
  332. return err
  333. }
  334. _, err = x.Delete(u)
  335. return err
  336. }
  337. // DeleteInactivateUsers deletes all inactivate users.
  338. func DeleteInactivateUsers() error {
  339. _, err := x.Where("is_active=?", false).Delete(new(User))
  340. return err
  341. }
  342. // UserPath returns the path absolute path of user repositories.
  343. func UserPath(userName string) string {
  344. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  345. }
  346. func GetUserByKeyId(keyId int64) (*User, error) {
  347. user := new(User)
  348. rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  349. has, err := x.Sql(rawSql, keyId).Get(user)
  350. if err != nil {
  351. return nil, err
  352. } else if !has {
  353. return nil, ErrUserNotKeyOwner
  354. }
  355. return user, nil
  356. }
  357. // GetUserById returns the user object by given ID if exists.
  358. func GetUserById(id int64) (*User, error) {
  359. u := new(User)
  360. has, err := x.Id(id).Get(u)
  361. if err != nil {
  362. return nil, err
  363. } else if !has {
  364. return nil, ErrUserNotExist
  365. }
  366. return u, nil
  367. }
  368. // GetUserByName returns the user object by given name if exists.
  369. func GetUserByName(name string) (*User, error) {
  370. if len(name) == 0 {
  371. return nil, ErrUserNotExist
  372. }
  373. user := &User{LowerName: strings.ToLower(name)}
  374. has, err := x.Get(user)
  375. if err != nil {
  376. return nil, err
  377. } else if !has {
  378. return nil, ErrUserNotExist
  379. }
  380. return user, nil
  381. }
  382. // GetUserEmailsByNames returns a slice of e-mails corresponds to names.
  383. func GetUserEmailsByNames(names []string) []string {
  384. mails := make([]string, 0, len(names))
  385. for _, name := range names {
  386. u, err := GetUserByName(name)
  387. if err != nil {
  388. continue
  389. }
  390. mails = append(mails, u.Email)
  391. }
  392. return mails
  393. }
  394. // GetUserIdsByNames returns a slice of ids corresponds to names.
  395. func GetUserIdsByNames(names []string) []int64 {
  396. ids := make([]int64, 0, len(names))
  397. for _, name := range names {
  398. u, err := GetUserByName(name)
  399. if err != nil {
  400. continue
  401. }
  402. ids = append(ids, u.Id)
  403. }
  404. return ids
  405. }
  406. // GetUserByEmail returns the user object by given e-mail if exists.
  407. func GetUserByEmail(email string) (*User, error) {
  408. if len(email) == 0 {
  409. return nil, ErrUserNotExist
  410. }
  411. user := &User{Email: strings.ToLower(email)}
  412. has, err := x.Get(user)
  413. if err != nil {
  414. return nil, err
  415. } else if !has {
  416. return nil, ErrUserNotExist
  417. }
  418. return user, nil
  419. }
  420. // SearchUserByName returns given number of users whose name contains keyword.
  421. func SearchUserByName(key string, limit int) (us []*User, err error) {
  422. // Prevent SQL inject.
  423. key = strings.TrimSpace(key)
  424. if len(key) == 0 {
  425. return us, nil
  426. }
  427. key = strings.Split(key, " ")[0]
  428. if len(key) == 0 {
  429. return us, nil
  430. }
  431. key = strings.ToLower(key)
  432. us = make([]*User, 0, limit)
  433. err = x.Limit(limit).Where("lower_name like '%" + key + "%'").Find(&us)
  434. return us, err
  435. }
  436. // Follow is connection request for receiving user notifycation.
  437. type Follow struct {
  438. Id int64
  439. UserId int64 `xorm:"unique(follow)"`
  440. FollowId int64 `xorm:"unique(follow)"`
  441. }
  442. // FollowUser marks someone be another's follower.
  443. func FollowUser(userId int64, followId int64) (err error) {
  444. session := x.NewSession()
  445. defer session.Close()
  446. session.Begin()
  447. if _, err = session.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  448. session.Rollback()
  449. return err
  450. }
  451. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  452. if _, err = session.Exec(rawSql, followId); err != nil {
  453. session.Rollback()
  454. return err
  455. }
  456. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  457. if _, err = session.Exec(rawSql, userId); err != nil {
  458. session.Rollback()
  459. return err
  460. }
  461. return session.Commit()
  462. }
  463. // UnFollowUser unmarks someone be another's follower.
  464. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  465. session := x.NewSession()
  466. defer session.Close()
  467. session.Begin()
  468. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
  469. session.Rollback()
  470. return err
  471. }
  472. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  473. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  474. session.Rollback()
  475. return err
  476. }
  477. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  478. if _, err = session.Exec(rawSql, userId); err != nil {
  479. session.Rollback()
  480. return err
  481. }
  482. return session.Commit()
  483. }