user.go 9.3 KB

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