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.

429 lines
11 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
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. 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. if len(name) == 0 {
  94. return false, nil
  95. }
  96. return orm.Get(&User{LowerName: strings.ToLower(name)})
  97. }
  98. // IsEmailUsed returns true if the e-mail has been used.
  99. func IsEmailUsed(email string) (bool, error) {
  100. if len(email) == 0 {
  101. return false, nil
  102. }
  103. return orm.Get(&User{Email: email})
  104. }
  105. // return a user salt token
  106. func GetUserSalt() string {
  107. return base.GetRandomString(10)
  108. }
  109. // RegisterUser creates record of a new user.
  110. func RegisterUser(user *User) (*User, error) {
  111. if !IsLegalName(user.Name) {
  112. return nil, ErrUserNameIllegal
  113. }
  114. isExist, err := IsUserExist(user.Name)
  115. if err != nil {
  116. return nil, err
  117. } else if isExist {
  118. return nil, ErrUserAlreadyExist
  119. }
  120. isExist, err = IsEmailUsed(user.Email)
  121. if err != nil {
  122. return nil, err
  123. } else if isExist {
  124. return nil, ErrEmailAlreadyUsed
  125. }
  126. user.LowerName = strings.ToLower(user.Name)
  127. user.Avatar = base.EncodeMd5(user.Email)
  128. user.AvatarEmail = user.Email
  129. user.Rands = GetUserSalt()
  130. if err = user.EncodePasswd(); err != nil {
  131. return nil, err
  132. } else if _, err = orm.Insert(user); err != nil {
  133. return nil, err
  134. } else if err = os.MkdirAll(UserPath(user.Name), os.ModePerm); err != nil {
  135. if _, err := orm.Id(user.Id).Delete(&User{}); err != nil {
  136. return nil, errors.New(fmt.Sprintf(
  137. "both create userpath %s and delete table record faild: %v", user.Name, err))
  138. }
  139. return nil, err
  140. }
  141. if user.Id == 1 {
  142. user.IsAdmin = true
  143. user.IsActive = true
  144. _, err = orm.Id(user.Id).UseBool().Update(user)
  145. }
  146. return user, err
  147. }
  148. // GetUsers returns given number of user objects with offset.
  149. func GetUsers(num, offset int) ([]User, error) {
  150. users := make([]User, 0, num)
  151. err := orm.Limit(num, offset).Asc("id").Find(&users)
  152. return users, err
  153. }
  154. // get user by erify code
  155. func getVerifyUser(code string) (user *User) {
  156. if len(code) <= base.TimeLimitCodeLength {
  157. return nil
  158. }
  159. // use tail hex username query user
  160. hexStr := code[base.TimeLimitCodeLength:]
  161. if b, err := hex.DecodeString(hexStr); err == nil {
  162. if user, err = GetUserByName(string(b)); user != nil {
  163. return user
  164. }
  165. log.Error("user.getVerifyUser: %v", err)
  166. }
  167. return nil
  168. }
  169. // verify active code when active account
  170. func VerifyUserActiveCode(code string) (user *User) {
  171. minutes := base.Service.ActiveCodeLives
  172. if user = getVerifyUser(code); user != nil {
  173. // time limit code
  174. prefix := code[:base.TimeLimitCodeLength]
  175. data := base.ToStr(user.Id) + user.Email + user.LowerName + user.Passwd + user.Rands
  176. if base.VerifyTimeLimitCode(data, minutes, prefix) {
  177. return user
  178. }
  179. }
  180. return nil
  181. }
  182. // ChangeUserName changes all corresponding setting from old user name to new one.
  183. func ChangeUserName(user *User, newUserName string) (err error) {
  184. newUserName = strings.ToLower(newUserName)
  185. // Update accesses of user.
  186. accesses := make([]Access, 0, 10)
  187. if err = orm.Find(&accesses, &Access{UserName: user.LowerName}); err != nil {
  188. return err
  189. }
  190. for i := range accesses {
  191. accesses[i].UserName = newUserName
  192. if strings.HasPrefix(accesses[i].RepoName, user.LowerName+"/") {
  193. accesses[i].RepoName = strings.Replace(accesses[i].RepoName, user.LowerName, newUserName, 1)
  194. if err = UpdateAccess(&accesses[i]); err != nil {
  195. return err
  196. }
  197. }
  198. }
  199. repos, err := GetRepositories(user)
  200. if err != nil {
  201. return err
  202. }
  203. for i := range repos {
  204. accesses = make([]Access, 0, 10)
  205. // Update accesses of user repository.
  206. if err = orm.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repos[i].LowerName}); err != nil {
  207. return err
  208. }
  209. for j := range accesses {
  210. accesses[j].RepoName = newUserName + "/" + repos[i].LowerName
  211. if err = UpdateAccess(&accesses[j]); err != nil {
  212. return err
  213. }
  214. }
  215. }
  216. // Change user directory name.
  217. return os.Rename(UserPath(user.LowerName), UserPath(newUserName))
  218. }
  219. // UpdateUser updates user's information.
  220. func UpdateUser(user *User) (err error) {
  221. user.LowerName = strings.ToLower(user.Name)
  222. if len(user.Location) > 255 {
  223. user.Location = user.Location[:255]
  224. }
  225. if len(user.Website) > 255 {
  226. user.Website = user.Website[:255]
  227. }
  228. _, err = orm.Id(user.Id).AllCols().Update(user)
  229. return err
  230. }
  231. // DeleteUser completely deletes everything of the user.
  232. func DeleteUser(user *User) error {
  233. // Check ownership of repository.
  234. count, err := GetRepositoryCount(user)
  235. if err != nil {
  236. return errors.New("modesl.GetRepositories: " + err.Error())
  237. } else if count > 0 {
  238. return ErrUserOwnRepos
  239. }
  240. // TODO: check issues, other repos' commits
  241. // Delete all feeds.
  242. if _, err = orm.Delete(&Action{UserId: user.Id}); err != nil {
  243. return err
  244. }
  245. // Delete all accesses.
  246. if _, err = orm.Delete(&Access{UserName: user.LowerName}); err != nil {
  247. return err
  248. }
  249. // Delete all SSH keys.
  250. keys := make([]PublicKey, 0, 10)
  251. if err = orm.Find(&keys, &PublicKey{OwnerId: user.Id}); err != nil {
  252. return err
  253. }
  254. for _, key := range keys {
  255. if err = DeletePublicKey(&key); err != nil {
  256. return err
  257. }
  258. }
  259. // Delete user directory.
  260. if err = os.RemoveAll(UserPath(user.Name)); err != nil {
  261. return err
  262. }
  263. _, err = orm.Delete(user)
  264. // TODO: delete and update follower information.
  265. return err
  266. }
  267. // UserPath returns the path absolute path of user repositories.
  268. func UserPath(userName string) string {
  269. return filepath.Join(base.RepoRootPath, strings.ToLower(userName))
  270. }
  271. func GetUserByKeyId(keyId int64) (*User, error) {
  272. user := new(User)
  273. rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?"
  274. has, err := orm.Sql(rawSql, keyId).Get(user)
  275. if err != nil {
  276. return nil, err
  277. } else if !has {
  278. err = errors.New("not exist key owner")
  279. return nil, err
  280. }
  281. return user, nil
  282. }
  283. // GetUserById returns the user object by given id if exists.
  284. func GetUserById(id int64) (*User, error) {
  285. user := new(User)
  286. has, err := orm.Id(id).Get(user)
  287. if err != nil {
  288. return nil, err
  289. }
  290. if !has {
  291. return nil, ErrUserNotExist
  292. }
  293. return user, nil
  294. }
  295. // GetUserByName returns the user object by given name if exists.
  296. func GetUserByName(name string) (*User, error) {
  297. if len(name) == 0 {
  298. return nil, ErrUserNotExist
  299. }
  300. user := &User{LowerName: strings.ToLower(name)}
  301. has, err := orm.Get(user)
  302. if err != nil {
  303. return nil, err
  304. } else if !has {
  305. return nil, ErrUserNotExist
  306. }
  307. return user, nil
  308. }
  309. // LoginUserPlain validates user by raw user name and password.
  310. func LoginUserPlain(name, passwd string) (*User, error) {
  311. user := User{LowerName: strings.ToLower(name), Passwd: passwd}
  312. if err := user.EncodePasswd(); err != nil {
  313. return nil, err
  314. }
  315. has, err := orm.Get(&user)
  316. if err != nil {
  317. return nil, err
  318. } else if !has {
  319. err = ErrUserNotExist
  320. }
  321. return &user, err
  322. }
  323. // Follow is connection request for receiving user notifycation.
  324. type Follow struct {
  325. Id int64
  326. UserId int64 `xorm:"unique(follow)"`
  327. FollowId int64 `xorm:"unique(follow)"`
  328. }
  329. // FollowUser marks someone be another's follower.
  330. func FollowUser(userId int64, followId int64) (err error) {
  331. session := orm.NewSession()
  332. defer session.Close()
  333. session.Begin()
  334. if _, err = session.Insert(&Follow{UserId: userId, FollowId: followId}); err != nil {
  335. session.Rollback()
  336. return err
  337. }
  338. rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?"
  339. if _, err = session.Exec(rawSql, followId); err != nil {
  340. session.Rollback()
  341. return err
  342. }
  343. rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?"
  344. if _, err = session.Exec(rawSql, userId); err != nil {
  345. session.Rollback()
  346. return err
  347. }
  348. return session.Commit()
  349. }
  350. // UnFollowUser unmarks someone be another's follower.
  351. func UnFollowUser(userId int64, unFollowId int64) (err error) {
  352. session := orm.NewSession()
  353. defer session.Close()
  354. session.Begin()
  355. if _, err = session.Delete(&Follow{UserId: userId, FollowId: unFollowId}); err != nil {
  356. session.Rollback()
  357. return err
  358. }
  359. rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?"
  360. if _, err = session.Exec(rawSql, unFollowId); err != nil {
  361. session.Rollback()
  362. return err
  363. }
  364. rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?"
  365. if _, err = session.Exec(rawSql, userId); err != nil {
  366. session.Rollback()
  367. return err
  368. }
  369. return session.Commit()
  370. }