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
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. IsAdmin bool
  47. Rands string `xorm:"VARCHAR(10)"`
  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.Rands = GetUserSalt()
  110. if err = user.EncodePasswd(); err != nil {
  111. return nil, err
  112. } else if _, err = orm.Insert(user); err != nil {
  113. return nil, err
  114. } else if err = os.MkdirAll(UserPath(user.Name), os.ModePerm); err != nil {
  115. if _, err := orm.Id(user.Id).Delete(&User{}); err != nil {
  116. return nil, errors.New(fmt.Sprintf(
  117. "both create userpath %s and delete table record faild: %v", user.Name, err))
  118. }
  119. return nil, err
  120. }
  121. if user.Id == 1 {
  122. user.IsAdmin = true
  123. user.IsActive = true
  124. _, err = orm.Id(user.Id).UseBool().Update(user)
  125. }
  126. return user, err
  127. }
  128. // get user by erify code
  129. func getVerifyUser(code string) (user *User) {
  130. if len(code) <= base.TimeLimitCodeLength {
  131. return nil
  132. }
  133. // use tail hex username query user
  134. hexStr := code[base.TimeLimitCodeLength:]
  135. if b, err := hex.DecodeString(hexStr); err == nil {
  136. if user, err = GetUserByName(string(b)); user != nil {
  137. return user
  138. }
  139. log.Error("user.getVerifyUser: %v", err)
  140. }
  141. return nil
  142. }
  143. // verify active code when active account
  144. func VerifyUserActiveCode(code string) (user *User) {
  145. minutes := base.Service.ActiveCodeLives
  146. if user = getVerifyUser(code); user != nil {
  147. // time limit code
  148. prefix := code[:base.TimeLimitCodeLength]
  149. data := base.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  150. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  151. return user
  152. }
  153. }
  154. return nil
  155. }
  156. // UpdateUser updates user's information.
  157. func UpdateUser(user *User) (err error) {
  158. _, err = orm.Id(user.Id).UseBool().Update(user)
  159. return err
  160. }
  161. // DeleteUser completely deletes everything of the user.
  162. func DeleteUser(user *User) error {
  163. // Check ownership of repository.
  164. count, err := GetRepositoryCount(user)
  165. if err != nil {
  166. return errors.New("modesl.GetRepositories: " + err.Error())
  167. } else if count > 0 {
  168. return ErrUserOwnRepos
  169. }
  170. // TODO: check issues, other repos' commits
  171. // Delete all feeds.
  172. if _, err = orm.Delete(&Action{UserId: user.Id}); err != nil {
  173. return err
  174. }
  175. // Delete all SSH keys.
  176. keys := make([]PublicKey, 0, 10)
  177. if err = orm.Find(&keys, &PublicKey{OwnerId: user.Id}); err != nil {
  178. return err
  179. }
  180. for _, key := range keys {
  181. if err = DeletePublicKey(&key); err != nil {
  182. return err
  183. }
  184. }
  185. // Delete user directory.
  186. if err = os.RemoveAll(UserPath(user.Name)); err != nil {
  187. return err
  188. }
  189. _, err = orm.Delete(user)
  190. // TODO: delete and update follower information.
  191. return err
  192. }
  193. // EncodePasswd encodes password to safe format.
  194. func (user *User) EncodePasswd() error {
  195. newPasswd, err := scrypt.Key([]byte(user.Passwd), []byte(base.SecretKey), 16384, 8, 1, 64)
  196. user.Passwd = fmt.Sprintf("%x", newPasswd)
  197. return err
  198. }
  199. // UserPath returns the path absolute path of user repositories.
  200. func UserPath(userName string) string {
  201. return filepath.Join(RepoRootPath, strings.ToLower(userName))
  202. }
  203. func GetUserByKeyId(keyId int64) (*User, error) {
  204. user := new(User)
  205. rawSql := "SELECT a.* FROM user AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  206. if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
  207. rawSql = "SELECT a.* FROM \"user\" AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  208. }
  209. has, err := orm.Sql(rawSql, keyId).Get(user)
  210. if err != nil {
  211. return nil, err
  212. } else if !has {
  213. err = errors.New("not exist key owner")
  214. return nil, err
  215. }
  216. return user, nil
  217. }
  218. // GetUserById returns the user object by given id if exists.
  219. func GetUserById(id int64) (*User, error) {
  220. user := new(User)
  221. has, err := orm.Id(id).Get(user)
  222. if err != nil {
  223. return nil, err
  224. }
  225. if !has {
  226. return nil, ErrUserNotExist
  227. }
  228. return user, nil
  229. }
  230. // GetUserByName returns the user object by given name if exists.
  231. func GetUserByName(name string) (*User, error) {
  232. if len(name) == 0 {
  233. return nil, ErrUserNotExist
  234. }
  235. user := &User{
  236. LowerName: strings.ToLower(name),
  237. }
  238. has, err := orm.Get(user)
  239. if err != nil {
  240. return nil, err
  241. } else if !has {
  242. return nil, ErrUserNotExist
  243. }
  244. return user, nil
  245. }
  246. // LoginUserPlain validates user by raw user name and password.
  247. func LoginUserPlain(name, passwd string) (*User, error) {
  248. user := User{LowerName: strings.ToLower(name), Passwd: passwd}
  249. if err := user.EncodePasswd(); err != nil {
  250. return nil, err
  251. }
  252. has, err := orm.Get(&user)
  253. if err != nil {
  254. return nil, err
  255. } else if !has {
  256. err = ErrUserNotExist
  257. }
  258. return &user, err
  259. }
  260. // FollowUser marks someone be another's follower.
  261. func FollowUser(userId int64, followId int64) (err error) {
  262. session := orm.NewSession()
  263. defer session.Close()
  264. session.Begin()
  265. if _, err = session.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  266. session.Rollback()
  267. return err
  268. }
  269. rawSql := "UPDATE user SET num_followers = num_followers + 1 WHERE id = ?"
  270. if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
  271. rawSql = "UPDATE \"user\" SET num_followers = num_followers + 1 WHERE id = ?"
  272. }
  273. if _, err = session.Exec(rawSql, followId); err != nil {
  274. session.Rollback()
  275. return err
  276. }
  277. rawSql = "UPDATE user SET num_followings = num_followings + 1 WHERE id = ?"
  278. if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
  279. rawSql = "UPDATE \"user\" SET num_followings = num_followings + 1 WHERE id = ?"
  280. }
  281. if _, err = session.Exec(rawSql, userId); err != nil {
  282. session.Rollback()
  283. return err
  284. }
  285. return session.Commit()
  286. }
  287. // UnFollowUser unmarks someone be another's follower.
  288. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  289. session := orm.NewSession()
  290. defer session.Close()
  291. session.Begin()
  292. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
  293. session.Rollback()
  294. return err
  295. }
  296. rawSql := "UPDATE user SET num_followers = num_followers - 1 WHERE id = ?"
  297. if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
  298. rawSql = "UPDATE \"user\" SET num_followers = num_followers - 1 WHERE id = ?"
  299. }
  300. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  301. session.Rollback()
  302. return err
  303. }
  304. rawSql = "UPDATE user SET num_followings = num_followings - 1 WHERE id = ?"
  305. if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" {
  306. rawSql = "UPDATE \"user\" SET num_followings = num_followings - 1 WHERE id = ?"
  307. }
  308. if _, err = session.Exec(rawSql, userId); err != nil {
  309. session.Rollback()
  310. return err
  311. }
  312. return session.Commit()
  313. }