user.go 8.2 KB

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