You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 6.9 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. // Delete user directory.
  146. if err = os.RemoveAll(UserPath(user.Name)); err != nil {
  147. return err
  148. }
  149. _, err = orm.Delete(user)
  150. // TODO: delete and update follower information.
  151. return err
  152. }
  153. // EncodePasswd encodes password to safe format.
  154. func (user *User) EncodePasswd() error {
  155. newPasswd, err := scrypt.Key([]byte(user.Passwd), []byte(UserPasswdSalt), 16384, 8, 1, 64)
  156. user.Passwd = fmt.Sprintf("%x", newPasswd)
  157. return err
  158. }
  159. func UserPath(userName string) string {
  160. return filepath.Join(RepoRootPath, userName)
  161. }
  162. func GetUserByKeyId(keyId int64) (*User, error) {
  163. user := new(User)
  164. 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)
  165. if err != nil {
  166. return nil, err
  167. }
  168. if !has {
  169. err = errors.New("not exist key owner")
  170. return nil, err
  171. }
  172. return user, nil
  173. }
  174. func GetUserById(id int64) (*User, error) {
  175. user := new(User)
  176. has, err := orm.Id(id).Get(user)
  177. if err != nil {
  178. return nil, err
  179. }
  180. if !has {
  181. return nil, ErrUserNotExist
  182. }
  183. return user, nil
  184. }
  185. func GetUserByName(name string) (*User, error) {
  186. if len(name) == 0 {
  187. return nil, ErrUserNotExist
  188. }
  189. user := &User{
  190. LowerName: strings.ToLower(name),
  191. }
  192. has, err := orm.Get(user)
  193. if err != nil {
  194. return nil, err
  195. }
  196. if !has {
  197. return nil, ErrUserNotExist
  198. }
  199. return user, nil
  200. }
  201. // LoginUserPlain validates user by raw user name and password.
  202. func LoginUserPlain(name, passwd string) (*User, error) {
  203. user := User{LowerName: strings.ToLower(name), Passwd: passwd}
  204. if err := user.EncodePasswd(); err != nil {
  205. return nil, err
  206. }
  207. has, err := orm.Get(&user)
  208. if !has {
  209. err = ErrUserNotExist
  210. }
  211. if err != nil {
  212. return nil, err
  213. }
  214. return &user, nil
  215. }
  216. // FollowUser marks someone be another's follower.
  217. func FollowUser(userId int64, followId int64) error {
  218. session := orm.NewSession()
  219. defer session.Close()
  220. session.Begin()
  221. _, err := session.Insert(&Follow{UserId: userId, FollowId: followId})
  222. if err != nil {
  223. session.Rollback()
  224. return err
  225. }
  226. _, err = session.Exec("update user set num_followers = num_followers + 1 where id = ?", followId)
  227. if err != nil {
  228. session.Rollback()
  229. return err
  230. }
  231. _, err = session.Exec("update user set num_followings = num_followings + 1 where id = ?", userId)
  232. if err != nil {
  233. session.Rollback()
  234. return err
  235. }
  236. return session.Commit()
  237. }
  238. // UnFollowUser unmarks someone be another's follower.
  239. func UnFollowUser(userId int64, unFollowId int64) error {
  240. session := orm.NewSession()
  241. defer session.Close()
  242. session.Begin()
  243. _, err := session.Delete(&Follow{UserId: userId, FollowId: unFollowId})
  244. if err != nil {
  245. session.Rollback()
  246. return err
  247. }
  248. _, err = session.Exec("update user set num_followers = num_followers - 1 where id = ?", unFollowId)
  249. if err != nil {
  250. session.Rollback()
  251. return err
  252. }
  253. _, err = session.Exec("update user set num_followings = num_followings - 1 where id = ?", userId)
  254. if err != nil {
  255. session.Rollback()
  256. return err
  257. }
  258. return session.Commit()
  259. }