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.2 kB

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