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. )
  18. // User types.
  19. const (
  20. UT_INDIVIDUAL = iota + 1
  21. UT_ORGANIZATION
  22. )
  23. var (
  24. ErrUserOwnRepos = errors.New("User still have ownership of repositories")
  25. ErrUserAlreadyExist = errors.New("User already exist")
  26. ErrUserNotExist = errors.New("User does not exist")
  27. ErrUserNotKeyOwner = errors.New("User does not the owner of public key")
  28. ErrEmailAlreadyUsed = errors.New("E-mail already used")
  29. ErrUserNameIllegal = errors.New("User name contains illegal characters")
  30. ErrLoginSourceNotExist = errors.New("Login source does not exist")
  31. ErrLoginSourceNotActived = errors.New("Login source is not actived")
  32. ErrUnsupportedLoginType = errors.New("Login source is unknown")
  33. )
  34. // User represents the object of individual and member of organization.
  35. type User struct {
  36. Id int64
  37. LowerName string `xorm:"unique not null"`
  38. Name string `xorm:"unique not null"`
  39. FullName string
  40. Email string `xorm:"unique not null"`
  41. Passwd string `xorm:"not null"`
  42. LoginType int
  43. LoginSource int64 `xorm:"not null default 0"`
  44. LoginName string
  45. Type int
  46. NumFollowers int
  47. NumFollowings int
  48. NumStars int
  49. NumRepos int
  50. Avatar string `xorm:"varchar(2048) not null"`
  51. AvatarEmail string `xorm:"not null"`
  52. Location string
  53. Website string
  54. IsActive bool
  55. IsAdmin bool
  56. Rands string `xorm:"VARCHAR(10)"`
  57. Salt string `xorm:"VARCHAR(10)"`
  58. Created time.Time `xorm:"created"`
  59. Updated time.Time `xorm:"updated"`
  60. }
  61. // HomeLink returns the user home page link.
  62. func (user *User) HomeLink() string {
  63. return "/user/" + user.Name
  64. }
  65. // AvatarLink returns the user gravatar link.
  66. func (user *User) AvatarLink() string {
  67. if base.DisableGravatar {
  68. return "/img/avatar_default.jpg"
  69. } else if base.Service.EnableCacheAvatar {
  70. return "/avatar/" + user.Avatar
  71. }
  72. return "//1.gravatar.com/avatar/" + user.Avatar
  73. }
  74. // NewGitSig generates and returns the signature of given user.
  75. func (user *User) NewGitSig() *git.Signature {
  76. return &git.Signature{
  77. Name: user.Name,
  78. Email: user.Email,
  79. When: time.Now(),
  80. }
  81. }
  82. // EncodePasswd encodes password to safe format.
  83. func (user *User) EncodePasswd() {
  84. newPasswd := base.PBKDF2([]byte(user.Passwd), []byte(user.Salt), 10000, 50, sha256.New)
  85. user.Passwd = fmt.Sprintf("%x", newPasswd)
  86. }
  87. // Member represents user is member of organization.
  88. type Member struct {
  89. Id int64
  90. OrgId int64 `xorm:"unique(member) index"`
  91. UserId int64 `xorm:"unique(member)"`
  92. }
  93. // IsUserExist checks if given user name exist,
  94. // the user name should be noncased unique.
  95. func IsUserExist(name string) (bool, error) {
  96. if len(name) == 0 {
  97. return false, nil
  98. }
  99. return orm.Get(&User{LowerName: strings.ToLower(name)})
  100. }
  101. // IsEmailUsed returns true if the e-mail has been used.
  102. func IsEmailUsed(email string) (bool, error) {
  103. if len(email) == 0 {
  104. return false, nil
  105. }
  106. return orm.Get(&User{Email: email})
  107. }
  108. // return a user salt token
  109. func GetUserSalt() string {
  110. return base.GetRandomString(10)
  111. }
  112. // RegisterUser creates record of a new user.
  113. func RegisterUser(user *User) (*User, error) {
  114. if !IsLegalName(user.Name) {
  115. return nil, ErrUserNameIllegal
  116. }
  117. isExist, err := IsUserExist(user.Name)
  118. if err != nil {
  119. return nil, err
  120. } else if isExist {
  121. return nil, ErrUserAlreadyExist
  122. }
  123. isExist, err = IsEmailUsed(user.Email)
  124. if err != nil {
  125. return nil, err
  126. } else if isExist {
  127. return nil, ErrEmailAlreadyUsed
  128. }
  129. user.LowerName = strings.ToLower(user.Name)
  130. user.Avatar = base.EncodeMd5(user.Email)
  131. user.AvatarEmail = user.Email
  132. user.Rands = GetUserSalt()
  133. user.Salt = GetUserSalt()
  134. user.EncodePasswd()
  135. if _, err = orm.Insert(user); err != nil {
  136. return nil, err
  137. } else if err = os.MkdirAll(UserPath(user.Name), os.ModePerm); err != nil {
  138. if _, err := orm.Id(user.Id).Delete(&User{}); err != nil {
  139. return nil, errors.New(fmt.Sprintf(
  140. "both create userpath %s and delete table record faild: %v", user.Name, err))
  141. }
  142. return nil, err
  143. }
  144. if user.Id == 1 {
  145. user.IsAdmin = true
  146. user.IsActive = true
  147. _, err = orm.Id(user.Id).UseBool().Update(user)
  148. }
  149. return user, err
  150. }
  151. // GetUsers returns given number of user objects with offset.
  152. func GetUsers(num, offset int) ([]User, error) {
  153. users := make([]User, 0, num)
  154. err := orm.Limit(num, offset).Asc("id").Find(&users)
  155. return users, err
  156. }
  157. // get user by erify code
  158. func getVerifyUser(code string) (user *User) {
  159. if len(code) <= base.TimeLimitCodeLength {
  160. return nil
  161. }
  162. // use tail hex username query user
  163. hexStr := code[base.TimeLimitCodeLength:]
  164. if b, err := hex.DecodeString(hexStr); err == nil {
  165. if user, err = GetUserByName(string(b)); user != nil {
  166. return user
  167. }
  168. log.Error("user.getVerifyUser: %v", err)
  169. }
  170. return nil
  171. }
  172. // verify active code when active account
  173. func VerifyUserActiveCode(code string) (user *User) {
  174. minutes := base.Service.ActiveCodeLives
  175. if user = getVerifyUser(code); user != nil {
  176. // time limit code
  177. prefix := code[:base.TimeLimitCodeLength]
  178. data := base.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  179. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  180. return user
  181. }
  182. }
  183. return nil
  184. }
  185. // ChangeUserName changes all corresponding setting from old user name to new one.
  186. func ChangeUserName(user *User, newUserName string) (err error) {
  187. newUserName = strings.ToLower(newUserName)
  188. // Update accesses of user.
  189. accesses := make([]Access, 0, 10)
  190. if err = orm.Find(&accesses, &Access{UserName: user.LowerName}); err != nil {
  191. return err
  192. }
  193. sess := orm.NewSession()
  194. defer sess.Close()
  195. if err = sess.Begin(); err != nil {
  196. return err
  197. }
  198. for i := range accesses {
  199. accesses[i].UserName = newUserName
  200. if strings.HasPrefix(accesses[i].RepoName, user.LowerName+"/") {
  201. accesses[i].RepoName = strings.Replace(accesses[i].RepoName, user.LowerName, newUserName, 1)
  202. }
  203. if err = UpdateAccessWithSession(sess, &accesses[i]); err != nil {
  204. return err
  205. }
  206. }
  207. repos, err := GetRepositories(user, true)
  208. if err != nil {
  209. return err
  210. }
  211. for i := range repos {
  212. accesses = make([]Access, 0, 10)
  213. // Update accesses of user repository.
  214. if err = orm.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repos[i].LowerName}); err != nil {
  215. return err
  216. }
  217. for j := range accesses {
  218. accesses[j].UserName = newUserName
  219. accesses[j].RepoName = newUserName + "/" + repos[i].LowerName
  220. if err = UpdateAccessWithSession(sess, &accesses[j]); err != nil {
  221. return err
  222. }
  223. }
  224. }
  225. // Change user directory name.
  226. if err = os.Rename(UserPath(user.LowerName), UserPath(newUserName)); err != nil {
  227. sess.Rollback()
  228. return err
  229. }
  230. return sess.Commit()
  231. }
  232. // UpdateUser updates user's information.
  233. func UpdateUser(user *User) (err error) {
  234. user.LowerName = strings.ToLower(user.Name)
  235. if len(user.Location) > 255 {
  236. user.Location = user.Location[:255]
  237. }
  238. if len(user.Website) > 255 {
  239. user.Website = user.Website[:255]
  240. }
  241. _, err = orm.Id(user.Id).AllCols().Update(user)
  242. return err
  243. }
  244. // DeleteUser completely deletes everything of the user.
  245. func DeleteUser(user *User) error {
  246. // Check ownership of repository.
  247. count, err := GetRepositoryCount(user)
  248. if err != nil {
  249. return errors.New("modesl.GetRepositories: " + err.Error())
  250. } else if count > 0 {
  251. return ErrUserOwnRepos
  252. }
  253. // TODO: check issues, other repos' commits
  254. // Delete all followers.
  255. if _, err = orm.Delete(&Follow{FollowId: user.Id}); err != nil {
  256. return err
  257. }
  258. // Delete oauth2.
  259. if _, err = orm.Delete(&Oauth2{Uid: user.Id}); err != nil {
  260. return err
  261. }
  262. // Delete all feeds.
  263. if _, err = orm.Delete(&Action{UserId: user.Id}); err != nil {
  264. return err
  265. }
  266. // Delete all watches.
  267. if _, err = orm.Delete(&Watch{UserId: user.Id}); err != nil {
  268. return err
  269. }
  270. // Delete all accesses.
  271. if _, err = orm.Delete(&Access{UserName: user.LowerName}); err != nil {
  272. return err
  273. }
  274. // Delete all SSH keys.
  275. keys := make([]*PublicKey, 0, 10)
  276. if err = orm.Find(&keys, &PublicKey{OwnerId: user.Id}); err != nil {
  277. return err
  278. }
  279. for _, key := range keys {
  280. if err = DeletePublicKey(key); err != nil {
  281. return err
  282. }
  283. }
  284. // Delete user directory.
  285. if err = os.RemoveAll(UserPath(user.Name)); err != nil {
  286. return err
  287. }
  288. _, err = orm.Delete(user)
  289. return err
  290. }
  291. // UserPath returns the path absolute path of user repositories.
  292. func UserPath(userName string) string {
  293. return filepath.Join(base.RepoRootPath, strings.ToLower(userName))
  294. }
  295. func GetUserByKeyId(keyId int64) (*User, error) {
  296. user := new(User)
  297. rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  298. has, err := orm.Sql(rawSql, keyId).Get(user)
  299. if err != nil {
  300. return nil, err
  301. } else if !has {
  302. return nil, ErrUserNotKeyOwner
  303. }
  304. return user, nil
  305. }
  306. // GetUserById returns the user object by given id if exists.
  307. func GetUserById(id int64) (*User, error) {
  308. user := new(User)
  309. has, err := orm.Id(id).Get(user)
  310. if err != nil {
  311. return nil, err
  312. }
  313. if !has {
  314. return nil, ErrUserNotExist
  315. }
  316. return user, 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. }