user.go 12 KB

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