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