You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

485 lines
12 KiB

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