user.go 8.0 KB

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