You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

373 lines
9.2 KiB

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