user.go 14 KB

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