user.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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.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. err = errors.New("not exist key owner")
  303. return nil, err
  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. user := new(User)
  310. has, err := orm.Id(id).Get(user)
  311. if err != nil {
  312. return nil, err
  313. }
  314. if !has {
  315. return nil, ErrUserNotExist
  316. }
  317. return user, nil
  318. }
  319. // GetUserByName returns the user object by given name if exists.
  320. func GetUserByName(name string) (*User, error) {
  321. if len(name) == 0 {
  322. return nil, ErrUserNotExist
  323. }
  324. user := &User{LowerName: strings.ToLower(name)}
  325. has, err := orm.Get(user)
  326. if err != nil {
  327. return nil, err
  328. } else if !has {
  329. return nil, ErrUserNotExist
  330. }
  331. return user, nil
  332. }
  333. // GetUserEmailsByNames returns a slice of e-mails corresponds to names.
  334. func GetUserEmailsByNames(names []string) []string {
  335. mails := make([]string, 0, len(names))
  336. for _, name := range names {
  337. u, err := GetUserByName(name)
  338. if err != nil {
  339. continue
  340. }
  341. mails = append(mails, u.Email)
  342. }
  343. return mails
  344. }
  345. // GetUserByEmail returns the user object by given e-mail if exists.
  346. func GetUserByEmail(email string) (*User, error) {
  347. if len(email) == 0 {
  348. return nil, ErrUserNotExist
  349. }
  350. user := &User{Email: strings.ToLower(email)}
  351. has, err := orm.Get(user)
  352. if err != nil {
  353. return nil, err
  354. } else if !has {
  355. return nil, ErrUserNotExist
  356. }
  357. return user, nil
  358. }
  359. // SearchUserByName returns given number of users whose name contains keyword.
  360. func SearchUserByName(key string, limit int) (us []*User, err error) {
  361. // Prevent SQL inject.
  362. key = strings.TrimSpace(key)
  363. if len(key) == 0 {
  364. return us, nil
  365. }
  366. key = strings.Split(key, " ")[0]
  367. if len(key) == 0 {
  368. return us, nil
  369. }
  370. key = strings.ToLower(key)
  371. us = make([]*User, 0, limit)
  372. err = orm.Limit(limit).Where("lower_name like '%" + key + "%'").Find(&us)
  373. return us, err
  374. }
  375. // LoginUserPlain validates user by raw user name and password.
  376. func LoginUserPlain(uname, passwd string) (*User, error) {
  377. var u *User
  378. if strings.Contains(uname, "@") {
  379. u = &User{Email: uname}
  380. } else {
  381. u = &User{LowerName: strings.ToLower(uname)}
  382. }
  383. has, err := orm.Get(u)
  384. if err != nil {
  385. return nil, err
  386. } else if !has {
  387. return nil, ErrUserNotExist
  388. }
  389. newUser := &User{Passwd: passwd, Salt: u.Salt}
  390. newUser.EncodePasswd()
  391. if u.Passwd != newUser.Passwd {
  392. return nil, ErrUserNotExist
  393. }
  394. return u, nil
  395. }
  396. // Follow is connection request for receiving user notifycation.
  397. type Follow struct {
  398. Id int64
  399. UserId int64 `xorm:"unique(follow)"`
  400. FollowId int64 `xorm:"unique(follow)"`
  401. }
  402. // FollowUser marks someone be another's follower.
  403. func FollowUser(userId int64, followId int64) (err error) {
  404. session := orm.NewSession()
  405. defer session.Close()
  406. session.Begin()
  407. if _, err = session.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  408. session.Rollback()
  409. return err
  410. }
  411. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  412. if _, err = session.Exec(rawSql, followId); err != nil {
  413. session.Rollback()
  414. return err
  415. }
  416. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  417. if _, err = session.Exec(rawSql, userId); err != nil {
  418. session.Rollback()
  419. return err
  420. }
  421. return session.Commit()
  422. }
  423. // UnFollowUser unmarks someone be another's follower.
  424. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  425. session := orm.NewSession()
  426. defer session.Close()
  427. session.Begin()
  428. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
  429. session.Rollback()
  430. return err
  431. }
  432. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  433. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  434. session.Rollback()
  435. return err
  436. }
  437. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  438. if _, err = session.Exec(rawSql, userId); err != nil {
  439. session.Rollback()
  440. return err
  441. }
  442. return session.Commit()
  443. }