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.

456 lines
11 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. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. "github.com/dchest/scrypt"
  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. Created time.Time `xorm:"created"`
  57. Updated time.Time `xorm:"updated"`
  58. }
  59. // HomeLink returns the user home page link.
  60. func (user *User) HomeLink() string {
  61. return "/user/" + user.Name
  62. }
  63. // AvatarLink returns the user gravatar link.
  64. func (user *User) AvatarLink() string {
  65. if base.Service.EnableCacheAvatar {
  66. return "/avatar/" + user.Avatar
  67. }
  68. return "http://1.gravatar.com/avatar/" + user.Avatar
  69. }
  70. // NewGitSig generates and returns the signature of given user.
  71. func (user *User) NewGitSig() *git.Signature {
  72. return &git.Signature{
  73. Name: user.Name,
  74. Email: user.Email,
  75. When: time.Now(),
  76. }
  77. }
  78. // EncodePasswd encodes password to safe format.
  79. func (user *User) EncodePasswd() error {
  80. newPasswd, err := scrypt.Key([]byte(user.Passwd), []byte(base.SecretKey), 16384, 8, 1, 64)
  81. user.Passwd = fmt.Sprintf("%x", newPasswd)
  82. return err
  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. if err = user.EncodePasswd(); err != nil {
  131. return nil, err
  132. } else 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 feeds.
  251. if _, err = orm.Delete(&Action{UserId: user.Id}); err != nil {
  252. return err
  253. }
  254. // Delete all accesses.
  255. if _, err = orm.Delete(&Access{UserName: user.LowerName}); err != nil {
  256. return err
  257. }
  258. // Delete all SSH keys.
  259. keys := make([]PublicKey, 0, 10)
  260. if err = orm.Find(&keys, &PublicKey{OwnerId: user.Id}); err != nil {
  261. return err
  262. }
  263. for _, key := range keys {
  264. if err = DeletePublicKey(&key); err != nil {
  265. return err
  266. }
  267. }
  268. // Delete user directory.
  269. if err = os.RemoveAll(UserPath(user.Name)); err != nil {
  270. return err
  271. }
  272. _, err = orm.Delete(user)
  273. // TODO: delete and update follower information.
  274. return err
  275. }
  276. // UserPath returns the path absolute path of user repositories.
  277. func UserPath(userName string) string {
  278. return filepath.Join(base.RepoRootPath, strings.ToLower(userName))
  279. }
  280. func GetUserByKeyId(keyId int64) (*User, error) {
  281. user := new(User)
  282. rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  283. has, err := orm.Sql(rawSql, keyId).Get(user)
  284. if err != nil {
  285. return nil, err
  286. } else if !has {
  287. err = errors.New("not exist key owner")
  288. return nil, err
  289. }
  290. return user, nil
  291. }
  292. // GetUserById returns the user object by given id if exists.
  293. func GetUserById(id int64) (*User, error) {
  294. user := new(User)
  295. has, err := orm.Id(id).Get(user)
  296. if err != nil {
  297. return nil, err
  298. }
  299. if !has {
  300. return nil, ErrUserNotExist
  301. }
  302. return user, nil
  303. }
  304. // GetUserByName returns the user object by given name if exists.
  305. func GetUserByName(name string) (*User, error) {
  306. if len(name) == 0 {
  307. return nil, ErrUserNotExist
  308. }
  309. user := &User{LowerName: strings.ToLower(name)}
  310. has, err := orm.Get(user)
  311. if err != nil {
  312. return nil, err
  313. } else if !has {
  314. return nil, ErrUserNotExist
  315. }
  316. return user, nil
  317. }
  318. // GetUserByEmail returns the user object by given e-mail if exists.
  319. func GetUserByEmail(email string) (*User, error) {
  320. if len(email) == 0 {
  321. return nil, ErrUserNotExist
  322. }
  323. user := &User{Email: strings.ToLower(email)}
  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. // LoginUserPlain validates user by raw user name and password.
  333. func LoginUserPlain(name, passwd string) (*User, error) {
  334. user := User{LowerName: strings.ToLower(name), Passwd: passwd}
  335. if err := user.EncodePasswd(); err != nil {
  336. return nil, err
  337. }
  338. has, err := orm.Get(&user)
  339. if err != nil {
  340. return nil, err
  341. } else if !has {
  342. err = ErrUserNotExist
  343. }
  344. return &user, err
  345. }
  346. // Follow is connection request for receiving user notifycation.
  347. type Follow struct {
  348. Id int64
  349. UserId int64 `xorm:"unique(follow)"`
  350. FollowId int64 `xorm:"unique(follow)"`
  351. }
  352. // FollowUser marks someone be another's follower.
  353. func FollowUser(userId int64, followId int64) (err error) {
  354. session := orm.NewSession()
  355. defer session.Close()
  356. session.Begin()
  357. if _, err = session.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  358. session.Rollback()
  359. return err
  360. }
  361. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  362. if _, err = session.Exec(rawSql, followId); err != nil {
  363. session.Rollback()
  364. return err
  365. }
  366. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  367. if _, err = session.Exec(rawSql, userId); err != nil {
  368. session.Rollback()
  369. return err
  370. }
  371. return session.Commit()
  372. }
  373. // UnFollowUser unmarks someone be another's follower.
  374. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  375. session := orm.NewSession()
  376. defer session.Close()
  377. session.Begin()
  378. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); 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, unFollowId); 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. }