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