user.go 13 KB

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