user.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. "errors"
  7. "fmt"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. "github.com/dchest/scrypt"
  13. "github.com/gogits/gogs/modules/base"
  14. )
  15. var UserPasswdSalt string
  16. func init() {
  17. UserPasswdSalt = base.Cfg.MustValue("security", "USER_PASSWD_SALT")
  18. }
  19. // User types.
  20. const (
  21. UT_INDIVIDUAL = iota + 1
  22. UT_ORGANIZATION
  23. )
  24. // Login types.
  25. const (
  26. LT_PLAIN = iota + 1
  27. LT_LDAP
  28. )
  29. // A User represents the object of individual and member of organization.
  30. type User struct {
  31. Id int64
  32. LowerName string `xorm:"unique not null"`
  33. Name string `xorm:"unique not null"`
  34. Email string `xorm:"unique not null"`
  35. Passwd string `xorm:"not null"`
  36. LoginType int
  37. Type int
  38. NumFollowers int
  39. NumFollowings int
  40. NumStars int
  41. NumRepos int
  42. Avatar string `xorm:"varchar(2048) not null"`
  43. Created time.Time `xorm:"created"`
  44. Updated time.Time `xorm:"updated"`
  45. }
  46. // A Follow represents
  47. type Follow struct {
  48. Id int64
  49. UserId int64 `xorm:"unique(s)"`
  50. FollowId int64 `xorm:"unique(s)"`
  51. Created time.Time `xorm:"created"`
  52. }
  53. // Operation types of repository.
  54. const (
  55. OP_CREATE_REPO = iota + 1
  56. OP_DELETE_REPO
  57. OP_STAR_REPO
  58. OP_FOLLOW_REPO
  59. OP_COMMIT_REPO
  60. OP_PULL_REQUEST
  61. )
  62. // An Action represents
  63. type Action struct {
  64. Id int64
  65. UserId int64
  66. OpType int
  67. RepoId int64
  68. Content string
  69. Created time.Time `xorm:"created"`
  70. }
  71. var (
  72. ErrUserOwnRepos = errors.New("User still have ownership of repositories")
  73. ErrUserAlreadyExist = errors.New("User already exist")
  74. ErrUserNotExist = errors.New("User does not exist")
  75. ErrEmailAlreadyUsed = errors.New("E-mail already used")
  76. )
  77. // IsUserExist checks if given user name exist,
  78. // the user name should be noncased unique.
  79. func IsUserExist(name string) (bool, error) {
  80. return orm.Get(&User{LowerName: strings.ToLower(name)})
  81. }
  82. func IsEmailUsed(email string) (bool, error) {
  83. return orm.Get(&User{Email: email})
  84. }
  85. // RegisterUser creates record of a new user.
  86. func RegisterUser(user *User) (err error) {
  87. isExist, err := IsUserExist(user.Name)
  88. if err != nil {
  89. return err
  90. } else if isExist {
  91. return ErrUserAlreadyExist
  92. }
  93. isExist, err = IsEmailUsed(user.Email)
  94. if err != nil {
  95. return err
  96. } else if isExist {
  97. return ErrEmailAlreadyUsed
  98. }
  99. user.LowerName = strings.ToLower(user.Name)
  100. user.Avatar = base.EncodeMd5(user.Email)
  101. if err = user.EncodePasswd(); err != nil {
  102. return err
  103. }
  104. if _, err = orm.Insert(user); err != nil {
  105. return err
  106. }
  107. if err = os.MkdirAll(UserPath(user.Name), os.ModePerm); err != nil {
  108. if _, err := orm.Id(user.Id).Delete(&User{}); err != nil {
  109. return errors.New(fmt.Sprintf(
  110. "both create userpath %s and delete table record faild", user.Name))
  111. }
  112. return err
  113. }
  114. return nil
  115. }
  116. // UpdateUser updates user's information.
  117. func UpdateUser(user *User) (err error) {
  118. _, err = orm.Id(user.Id).Update(user)
  119. return err
  120. }
  121. // DeleteUser completely deletes everything of the user.
  122. func DeleteUser(user *User) error {
  123. cnt, err := GetRepositoryCount(user)
  124. if err != nil {
  125. return errors.New("modesl.GetRepositories: " + err.Error())
  126. } else if cnt > 0 {
  127. return ErrUserOwnRepos
  128. }
  129. // TODO: check issues, other repos' commits
  130. _, err = orm.Delete(user)
  131. // TODO: delete and update follower information.
  132. return err
  133. }
  134. // EncodePasswd encodes password to safe format.
  135. func (user *User) EncodePasswd() error {
  136. newPasswd, err := scrypt.Key([]byte(user.Passwd), []byte(UserPasswdSalt), 16384, 8, 1, 64)
  137. user.Passwd = fmt.Sprintf("%x", newPasswd)
  138. return err
  139. }
  140. func UserPath(userName string) string {
  141. return filepath.Join(RepoRootPath, userName)
  142. }
  143. func GetUserByKeyId(keyId int64) (*User, error) {
  144. user := new(User)
  145. has, err := orm.Sql("select a.* from user as a, public_key as b where a.id = b.owner_id and b.id=?", keyId).Get(user)
  146. if err != nil {
  147. return nil, err
  148. }
  149. if !has {
  150. err = errors.New("not exist key owner")
  151. return nil, err
  152. }
  153. return user, nil
  154. }
  155. func GetUserById(id int64) (*User, error) {
  156. user := new(User)
  157. has, err := orm.Id(id).Get(user)
  158. if err != nil {
  159. return nil, err
  160. }
  161. if !has {
  162. return nil, ErrUserNotExist
  163. }
  164. return user, nil
  165. }
  166. func GetUserByName(name string) (*User, error) {
  167. if len(name) == 0 {
  168. return nil, ErrUserNotExist
  169. }
  170. user := &User{
  171. LowerName: strings.ToLower(name),
  172. }
  173. has, err := orm.Get(user)
  174. if err != nil {
  175. return nil, err
  176. }
  177. if !has {
  178. return nil, ErrUserNotExist
  179. }
  180. return user, nil
  181. }
  182. // LoginUserPlain validates user by raw user name and password.
  183. func LoginUserPlain(name, passwd string) (*User, error) {
  184. user := User{LowerName: strings.ToLower(name), Passwd: passwd}
  185. if err := user.EncodePasswd(); err != nil {
  186. return nil, err
  187. }
  188. has, err := orm.Get(&user)
  189. if !has {
  190. err = ErrUserNotExist
  191. }
  192. if err != nil {
  193. return nil, err
  194. }
  195. return &user, nil
  196. }
  197. // FollowUser marks someone be another's follower.
  198. func FollowUser(userId int64, followId int64) error {
  199. session := orm.NewSession()
  200. defer session.Close()
  201. session.Begin()
  202. _, err := session.Insert(&Follow{UserId: userId, FollowId: followId})
  203. if err != nil {
  204. session.Rollback()
  205. return err
  206. }
  207. _, err = session.Exec("update user set num_followers = num_followers + 1 where id = ?", followId)
  208. if err != nil {
  209. session.Rollback()
  210. return err
  211. }
  212. _, err = session.Exec("update user set num_followings = num_followings + 1 where id = ?", userId)
  213. if err != nil {
  214. session.Rollback()
  215. return err
  216. }
  217. return session.Commit()
  218. }
  219. // UnFollowUser unmarks someone be another's follower.
  220. func UnFollowUser(userId int64, unFollowId int64) error {
  221. session := orm.NewSession()
  222. defer session.Close()
  223. session.Begin()
  224. _, err := session.Delete(&Follow{UserId: userId, FollowId: unFollowId})
  225. if err != nil {
  226. session.Rollback()
  227. return err
  228. }
  229. _, err = session.Exec("update user set num_followers = num_followers - 1 where id = ?", unFollowId)
  230. if err != nil {
  231. session.Rollback()
  232. return err
  233. }
  234. _, err = session.Exec("update user set num_followings = num_followings - 1 where id = ?", userId)
  235. if err != nil {
  236. session.Rollback()
  237. return err
  238. }
  239. return session.Commit()
  240. }