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.

479 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
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
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 "http://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)
  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 all feeds.
  255. if _, err = orm.Delete(&Action{UserId: user.Id}); err != nil {
  256. return err
  257. }
  258. // Delete all watches.
  259. if _, err = orm.Delete(&Watch{UserId: user.Id}); err != nil {
  260. return err
  261. }
  262. // Delete all accesses.
  263. if _, err = orm.Delete(&Access{UserName: user.LowerName}); err != nil {
  264. return err
  265. }
  266. // Delete all SSH keys.
  267. keys := make([]PublicKey, 0, 10)
  268. if err = orm.Find(&keys, &PublicKey{OwnerId: user.Id}); err != nil {
  269. return err
  270. }
  271. for _, key := range keys {
  272. if err = DeletePublicKey(&key); err != nil {
  273. return err
  274. }
  275. }
  276. // Delete user directory.
  277. if err = os.RemoveAll(UserPath(user.Name)); err != nil {
  278. return err
  279. }
  280. _, err = orm.Delete(user)
  281. return err
  282. }
  283. // UserPath returns the path absolute path of user repositories.
  284. func UserPath(userName string) string {
  285. return filepath.Join(base.RepoRootPath, strings.ToLower(userName))
  286. }
  287. func GetUserByKeyId(keyId int64) (*User, error) {
  288. user := new(User)
  289. rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  290. has, err := orm.Sql(rawSql, keyId).Get(user)
  291. if err != nil {
  292. return nil, err
  293. } else if !has {
  294. err = errors.New("not exist key owner")
  295. return nil, err
  296. }
  297. return user, nil
  298. }
  299. // GetUserById returns the user object by given id if exists.
  300. func GetUserById(id int64) (*User, error) {
  301. user := new(User)
  302. has, err := orm.Id(id).Get(user)
  303. if err != nil {
  304. return nil, err
  305. }
  306. if !has {
  307. return nil, ErrUserNotExist
  308. }
  309. return user, nil
  310. }
  311. // GetUserByName returns the user object by given name if exists.
  312. func GetUserByName(name string) (*User, error) {
  313. if len(name) == 0 {
  314. return nil, ErrUserNotExist
  315. }
  316. user := &User{LowerName: strings.ToLower(name)}
  317. has, err := orm.Get(user)
  318. if err != nil {
  319. return nil, err
  320. } else if !has {
  321. return nil, ErrUserNotExist
  322. }
  323. return user, nil
  324. }
  325. // GetUserEmailsByNames returns a slice of e-mails corresponds to names.
  326. func GetUserEmailsByNames(names []string) []string {
  327. mails := make([]string, 0, len(names))
  328. for _, name := range names {
  329. u, err := GetUserByName(name)
  330. if err != nil {
  331. continue
  332. }
  333. mails = append(mails, u.Email)
  334. }
  335. return mails
  336. }
  337. // GetUserByEmail returns the user object by given e-mail if exists.
  338. func GetUserByEmail(email string) (*User, error) {
  339. if len(email) == 0 {
  340. return nil, ErrUserNotExist
  341. }
  342. user := &User{Email: strings.ToLower(email)}
  343. has, err := orm.Get(user)
  344. if err != nil {
  345. return nil, err
  346. } else if !has {
  347. return nil, ErrUserNotExist
  348. }
  349. return user, nil
  350. }
  351. // LoginUserPlain validates user by raw user name and password.
  352. func LoginUserPlain(name, passwd string) (*User, error) {
  353. user := User{LowerName: strings.ToLower(name)}
  354. has, err := orm.Get(&user)
  355. if err != nil {
  356. return nil, err
  357. } else if !has {
  358. return nil, ErrUserNotExist
  359. }
  360. newUser := &User{Passwd: passwd, Salt: user.Salt}
  361. newUser.EncodePasswd()
  362. if user.Passwd != newUser.Passwd {
  363. return nil, ErrUserNotExist
  364. }
  365. return &user, nil
  366. }
  367. // Follow is connection request for receiving user notifycation.
  368. type Follow struct {
  369. Id int64
  370. UserId int64 `xorm:"unique(follow)"`
  371. FollowId int64 `xorm:"unique(follow)"`
  372. }
  373. // FollowUser marks someone be another's follower.
  374. func FollowUser(userId int64, followId int64) (err error) {
  375. session := orm.NewSession()
  376. defer session.Close()
  377. session.Begin()
  378. if _, err = session.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  379. session.Rollback()
  380. return err
  381. }
  382. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  383. if _, err = session.Exec(rawSql, followId); err != nil {
  384. session.Rollback()
  385. return err
  386. }
  387. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  388. if _, err = session.Exec(rawSql, userId); err != nil {
  389. session.Rollback()
  390. return err
  391. }
  392. return session.Commit()
  393. }
  394. // UnFollowUser unmarks someone be another's follower.
  395. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  396. session := orm.NewSession()
  397. defer session.Close()
  398. session.Begin()
  399. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
  400. session.Rollback()
  401. return err
  402. }
  403. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  404. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  405. session.Rollback()
  406. return err
  407. }
  408. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  409. if _, err = session.Exec(rawSql, userId); err != nil {
  410. session.Rollback()
  411. return err
  412. }
  413. return session.Commit()
  414. }