user.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. git "github.com/libgit2/git2go"
  15. )
  16. var UserPasswdSalt string
  17. func init() {
  18. UserPasswdSalt = base.Cfg.MustValue("security", "USER_PASSWD_SALT")
  19. }
  20. // User types.
  21. const (
  22. UT_INDIVIDUAL = iota + 1
  23. UT_ORGANIZATION
  24. )
  25. // Login types.
  26. const (
  27. LT_PLAIN = iota + 1
  28. LT_LDAP
  29. )
  30. // A User represents the object of individual and member of organization.
  31. type User struct {
  32. Id int64
  33. LowerName string `xorm:"unique not null"`
  34. Name string `xorm:"unique not null"`
  35. Email string `xorm:"unique not null"`
  36. Passwd string `xorm:"not null"`
  37. LoginType int
  38. Type int
  39. NumFollowers int
  40. NumFollowings int
  41. NumStars int
  42. NumRepos int
  43. Avatar string `xorm:"varchar(2048) not null"`
  44. AvatarEmail string `xorm:"not null"`
  45. Location string
  46. Website string
  47. Created time.Time `xorm:"created"`
  48. Updated time.Time `xorm:"updated"`
  49. }
  50. func (user *User) HomeLink() string {
  51. return "/user/" + user.LowerName
  52. }
  53. func (user *User) AvatarLink() string {
  54. return "http://1.gravatar.com/avatar/" + user.Avatar
  55. }
  56. // A Follow represents
  57. type Follow struct {
  58. Id int64
  59. UserId int64 `xorm:"unique(s)"`
  60. FollowId int64 `xorm:"unique(s)"`
  61. Created time.Time `xorm:"created"`
  62. }
  63. var (
  64. ErrUserOwnRepos = errors.New("User still have ownership of repositories")
  65. ErrUserAlreadyExist = errors.New("User already exist")
  66. ErrUserNotExist = errors.New("User does not exist")
  67. ErrEmailAlreadyUsed = errors.New("E-mail already used")
  68. )
  69. // IsUserExist checks if given user name exist,
  70. // the user name should be noncased unique.
  71. func IsUserExist(name string) (bool, error) {
  72. return orm.Get(&User{LowerName: strings.ToLower(name)})
  73. }
  74. func IsEmailUsed(email string) (bool, error) {
  75. return orm.Get(&User{Email: email})
  76. }
  77. func (user *User) NewGitSig() *git.Signature {
  78. return &git.Signature{
  79. Name: user.Name,
  80. Email: user.Email,
  81. When: time.Now(),
  82. }
  83. }
  84. // RegisterUser creates record of a new user.
  85. func RegisterUser(user *User) (err error) {
  86. isExist, err := IsUserExist(user.Name)
  87. if err != nil {
  88. return err
  89. } else if isExist {
  90. return ErrUserAlreadyExist
  91. }
  92. isExist, err = IsEmailUsed(user.Email)
  93. if err != nil {
  94. return err
  95. } else if isExist {
  96. return ErrEmailAlreadyUsed
  97. }
  98. user.LowerName = strings.ToLower(user.Name)
  99. user.Avatar = base.EncodeMd5(user.Email)
  100. user.AvatarEmail = 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. // Check ownership of repository.
  124. count, err := GetRepositoryCount(user)
  125. if err != nil {
  126. return errors.New("modesl.GetRepositories: " + err.Error())
  127. } else if count > 0 {
  128. return ErrUserOwnRepos
  129. }
  130. // TODO: check issues, other repos' commits
  131. // Delete all feeds.
  132. if _, err = orm.Delete(&Action{UserId: user.Id}); err != nil {
  133. return err
  134. }
  135. // Delete all SSH keys.
  136. keys := make([]PublicKey, 0, 10)
  137. if err = orm.Find(&keys, &PublicKey{OwnerId: user.Id}); err != nil {
  138. return err
  139. }
  140. for _, key := range keys {
  141. if err = DeletePublicKey(&key); err != nil {
  142. return err
  143. }
  144. }
  145. _, err = orm.Delete(user)
  146. // TODO: delete and update follower information.
  147. return err
  148. }
  149. // EncodePasswd encodes password to safe format.
  150. func (user *User) EncodePasswd() error {
  151. var err error
  152. user.Passwd, err = EncodePasswd(user.Passwd)
  153. return err
  154. }
  155. func UserPath(userName string) string {
  156. return filepath.Join(RepoRootPath, userName)
  157. }
  158. func EncodePasswd(rawPasswd string) (string, error) {
  159. newPasswd, err := scrypt.Key([]byte(rawPasswd), []byte(UserPasswdSalt), 16384, 8, 1, 64)
  160. if err != nil {
  161. return "", err
  162. }
  163. return fmt.Sprintf("%x", newPasswd), nil
  164. }
  165. func GetUserByKeyId(keyId int64) (*User, error) {
  166. user := new(User)
  167. 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)
  168. if err != nil {
  169. return nil, err
  170. }
  171. if !has {
  172. err = errors.New("not exist key owner")
  173. return nil, err
  174. }
  175. return user, nil
  176. }
  177. func GetUserById(id int64) (*User, error) {
  178. user := new(User)
  179. has, err := orm.Id(id).Get(user)
  180. if err != nil {
  181. return nil, err
  182. }
  183. if !has {
  184. return nil, ErrUserNotExist
  185. }
  186. return user, nil
  187. }
  188. func GetUserByName(name string) (*User, error) {
  189. if len(name) == 0 {
  190. return nil, ErrUserNotExist
  191. }
  192. user := &User{
  193. LowerName: strings.ToLower(name),
  194. }
  195. has, err := orm.Get(user)
  196. if err != nil {
  197. return nil, err
  198. }
  199. if !has {
  200. return nil, ErrUserNotExist
  201. }
  202. return user, nil
  203. }
  204. // LoginUserPlain validates user by raw user name and password.
  205. func LoginUserPlain(name, passwd string) (*User, error) {
  206. user := User{LowerName: strings.ToLower(name), Passwd: passwd}
  207. if err := user.EncodePasswd(); err != nil {
  208. return nil, err
  209. }
  210. has, err := orm.Get(&user)
  211. if !has {
  212. err = ErrUserNotExist
  213. }
  214. if err != nil {
  215. return nil, err
  216. }
  217. return &user, nil
  218. }
  219. // FollowUser marks someone be another's follower.
  220. func FollowUser(userId int64, followId int64) error {
  221. session := orm.NewSession()
  222. defer session.Close()
  223. session.Begin()
  224. _, err := session.Insert(&Follow{UserId: userId, FollowId: followId})
  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 = ?", followId)
  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. }
  241. // UnFollowUser unmarks someone be another's follower.
  242. func UnFollowUser(userId int64, unFollowId int64) error {
  243. session := orm.NewSession()
  244. defer session.Close()
  245. session.Begin()
  246. _, err := session.Delete(&Follow{UserId: userId, FollowId: unFollowId})
  247. if err != nil {
  248. session.Rollback()
  249. return err
  250. }
  251. _, err = session.Exec("update user set num_followers = num_followers - 1 where id = ?", unFollowId)
  252. if err != nil {
  253. session.Rollback()
  254. return err
  255. }
  256. _, err = session.Exec("update user set num_followings = num_followings - 1 where id = ?", userId)
  257. if err != nil {
  258. session.Rollback()
  259. return err
  260. }
  261. return session.Commit()
  262. }