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.

370 lines
9.1 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
  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. )
  35. // User represents the object of individual and member of organization.
  36. type User struct {
  37. Id int64
  38. LowerName string `xorm:"unique not null"`
  39. Name string `xorm:"unique not null"`
  40. Email string `xorm:"unique not null"`
  41. Passwd string `xorm:"not null"`
  42. LoginType int
  43. Type int
  44. NumFollowers int
  45. NumFollowings int
  46. NumStars int
  47. NumRepos int
  48. Avatar string `xorm:"varchar(2048) not null"`
  49. AvatarEmail string `xorm:"not null"`
  50. Location string
  51. Website string
  52. IsActive bool
  53. IsAdmin bool
  54. Rands string `xorm:"VARCHAR(10)"`
  55. Created time.Time `xorm:"created"`
  56. Updated time.Time `xorm:"updated"`
  57. }
  58. // HomeLink returns the user home page link.
  59. func (user *User) HomeLink() string {
  60. return "/user/" + user.LowerName
  61. }
  62. // AvatarLink returns the user gravatar link.
  63. func (user *User) AvatarLink() string {
  64. return "http://1.gravatar.com/avatar/" + user.Avatar
  65. }
  66. // NewGitSig generates and returns the signature of given user.
  67. func (user *User) NewGitSig() *git.Signature {
  68. return &git.Signature{
  69. Name: user.Name,
  70. Email: user.Email,
  71. When: time.Now(),
  72. }
  73. }
  74. // EncodePasswd encodes password to safe format.
  75. func (user *User) EncodePasswd() error {
  76. newPasswd, err := scrypt.Key([]byte(user.Passwd), []byte(base.SecretKey), 16384, 8, 1, 64)
  77. user.Passwd = fmt.Sprintf("%x", newPasswd)
  78. return err
  79. }
  80. // Member represents user is member of organization.
  81. type Member struct {
  82. Id int64
  83. OrgId int64 `xorm:"unique(member) index"`
  84. UserId int64 `xorm:"unique(member)"`
  85. }
  86. // IsUserExist checks if given user name exist,
  87. // the user name should be noncased unique.
  88. func IsUserExist(name string) (bool, error) {
  89. return orm.Get(&User{LowerName: strings.ToLower(name)})
  90. }
  91. // IsEmailUsed returns true if the e-mail has been used.
  92. func IsEmailUsed(email string) (bool, error) {
  93. return orm.Get(&User{Email: email})
  94. }
  95. // return a user salt token
  96. func GetUserSalt() string {
  97. return base.GetRandomString(10)
  98. }
  99. // RegisterUser creates record of a new user.
  100. func RegisterUser(user *User) (*User, error) {
  101. if !IsLegalName(user.Name) {
  102. return nil, ErrUserNameIllegal
  103. }
  104. isExist, err := IsUserExist(user.Name)
  105. if err != nil {
  106. return nil, err
  107. } else if isExist {
  108. return nil, ErrUserAlreadyExist
  109. }
  110. isExist, err = IsEmailUsed(user.Email)
  111. if err != nil {
  112. return nil, err
  113. } else if isExist {
  114. return nil, ErrEmailAlreadyUsed
  115. }
  116. user.LowerName = strings.ToLower(user.Name)
  117. user.Avatar = base.EncodeMd5(user.Email)
  118. user.AvatarEmail = user.Email
  119. user.Rands = GetUserSalt()
  120. if err = user.EncodePasswd(); err != nil {
  121. return nil, err
  122. } else if _, err = orm.Insert(user); err != nil {
  123. return nil, err
  124. } else if err = os.MkdirAll(UserPath(user.Name), os.ModePerm); err != nil {
  125. if _, err := orm.Id(user.Id).Delete(&User{}); err != nil {
  126. return nil, errors.New(fmt.Sprintf(
  127. "both create userpath %s and delete table record faild: %v", user.Name, err))
  128. }
  129. return nil, err
  130. }
  131. if user.Id == 1 {
  132. user.IsAdmin = true
  133. user.IsActive = true
  134. _, err = orm.Id(user.Id).UseBool().Update(user)
  135. }
  136. return user, err
  137. }
  138. // GetUsers returns given number of user objects with offset.
  139. func GetUsers(num, offset int) ([]User, error) {
  140. users := make([]User, 0, num)
  141. err := orm.Limit(num, offset).Asc("id").Find(&users)
  142. return users, err
  143. }
  144. // get user by erify code
  145. func getVerifyUser(code string) (user *User) {
  146. if len(code) <= base.TimeLimitCodeLength {
  147. return nil
  148. }
  149. // use tail hex username query user
  150. hexStr := code[base.TimeLimitCodeLength:]
  151. if b, err := hex.DecodeString(hexStr); err == nil {
  152. if user, err = GetUserByName(string(b)); user != nil {
  153. return user
  154. }
  155. log.Error("user.getVerifyUser: %v", err)
  156. }
  157. return nil
  158. }
  159. // verify active code when active account
  160. func VerifyUserActiveCode(code string) (user *User) {
  161. minutes := base.Service.ActiveCodeLives
  162. if user = getVerifyUser(code); user != nil {
  163. // time limit code
  164. prefix := code[:base.TimeLimitCodeLength]
  165. data := base.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  166. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  167. return user
  168. }
  169. }
  170. return nil
  171. }
  172. // UpdateUser updates user's information.
  173. func UpdateUser(user *User) (err error) {
  174. if len(user.Location) > 255 {
  175. user.Location = user.Location[:255]
  176. }
  177. if len(user.Website) > 255 {
  178. user.Website = user.Website[:255]
  179. }
  180. _, err = orm.Id(user.Id).UseBool().Cols("website", "location").Update(user)
  181. return err
  182. }
  183. // DeleteUser completely deletes everything of the user.
  184. func DeleteUser(user *User) error {
  185. // Check ownership of repository.
  186. count, err := GetRepositoryCount(user)
  187. if err != nil {
  188. return errors.New("modesl.GetRepositories: " + err.Error())
  189. } else if count > 0 {
  190. return ErrUserOwnRepos
  191. }
  192. // TODO: check issues, other repos' commits
  193. // Delete all feeds.
  194. if _, err = orm.Delete(&Action{UserId: user.Id}); err != nil {
  195. return err
  196. }
  197. // Delete all SSH keys.
  198. keys := make([]PublicKey, 0, 10)
  199. if err = orm.Find(&keys, &PublicKey{OwnerId: user.Id}); err != nil {
  200. return err
  201. }
  202. for _, key := range keys {
  203. if err = DeletePublicKey(&key); err != nil {
  204. return err
  205. }
  206. }
  207. // Delete user directory.
  208. if err = os.RemoveAll(UserPath(user.Name)); err != nil {
  209. return err
  210. }
  211. _, err = orm.Delete(user)
  212. // TODO: delete and update follower information.
  213. return err
  214. }
  215. // UserPath returns the path absolute path of user repositories.
  216. func UserPath(userName string) string {
  217. return filepath.Join(base.RepoRootPath, strings.ToLower(userName))
  218. }
  219. func GetUserByKeyId(keyId int64) (*User, error) {
  220. user := new(User)
  221. rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  222. has, err := orm.Sql(rawSql, keyId).Get(user)
  223. if err != nil {
  224. return nil, err
  225. } else if !has {
  226. err = errors.New("not exist key owner")
  227. return nil, err
  228. }
  229. return user, nil
  230. }
  231. // GetUserById returns the user object by given id if exists.
  232. func GetUserById(id int64) (*User, error) {
  233. user := new(User)
  234. has, err := orm.Id(id).Get(user)
  235. if err != nil {
  236. return nil, err
  237. }
  238. if !has {
  239. return nil, ErrUserNotExist
  240. }
  241. return user, nil
  242. }
  243. // GetUserByName returns the user object by given name if exists.
  244. func GetUserByName(name string) (*User, error) {
  245. if len(name) == 0 {
  246. return nil, ErrUserNotExist
  247. }
  248. user := &User{LowerName: strings.ToLower(name)}
  249. has, err := orm.Get(user)
  250. if err != nil {
  251. return nil, err
  252. } else if !has {
  253. return nil, ErrUserNotExist
  254. }
  255. return user, nil
  256. }
  257. // LoginUserPlain validates user by raw user name and password.
  258. func LoginUserPlain(name, passwd string) (*User, error) {
  259. user := User{LowerName: strings.ToLower(name), Passwd: passwd}
  260. if err := user.EncodePasswd(); err != nil {
  261. return nil, err
  262. }
  263. has, err := orm.Get(&user)
  264. if err != nil {
  265. return nil, err
  266. } else if !has {
  267. err = ErrUserNotExist
  268. }
  269. return &user, err
  270. }
  271. // Follow is connection request for receiving user notifycation.
  272. type Follow struct {
  273. Id int64
  274. UserId int64 `xorm:"unique(follow)"`
  275. FollowId int64 `xorm:"unique(follow)"`
  276. }
  277. // FollowUser marks someone be another's follower.
  278. func FollowUser(userId int64, followId int64) (err error) {
  279. session := orm.NewSession()
  280. defer session.Close()
  281. session.Begin()
  282. if _, err = session.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  283. session.Rollback()
  284. return err
  285. }
  286. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  287. if _, err = session.Exec(rawSql, followId); err != nil {
  288. session.Rollback()
  289. return err
  290. }
  291. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  292. if _, err = session.Exec(rawSql, userId); err != nil {
  293. session.Rollback()
  294. return err
  295. }
  296. return session.Commit()
  297. }
  298. // UnFollowUser unmarks someone be another's follower.
  299. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  300. session := orm.NewSession()
  301. defer session.Close()
  302. session.Begin()
  303. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
  304. session.Rollback()
  305. return err
  306. }
  307. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  308. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  309. session.Rollback()
  310. return err
  311. }
  312. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  313. if _, err = session.Exec(rawSql, userId); err != nil {
  314. session.Rollback()
  315. return err
  316. }
  317. return session.Commit()
  318. }