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.

83 lines
2.1 KiB

8 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. "time"
  7. gouuid "github.com/satori/go.uuid"
  8. "code.gitea.io/gitea/modules/base"
  9. "code.gitea.io/gitea/modules/util"
  10. )
  11. // AccessToken represents a personal access token.
  12. type AccessToken struct {
  13. ID int64 `xorm:"pk autoincr"`
  14. UID int64 `xorm:"INDEX"`
  15. Name string
  16. Sha1 string `xorm:"UNIQUE VARCHAR(40)"`
  17. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  18. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  19. HasRecentActivity bool `xorm:"-"`
  20. HasUsed bool `xorm:"-"`
  21. }
  22. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  23. func (t *AccessToken) AfterLoad() {
  24. t.HasUsed = t.UpdatedUnix > t.CreatedUnix
  25. t.HasRecentActivity = t.UpdatedUnix.AddDuration(7*24*time.Hour) > util.TimeStampNow()
  26. }
  27. // NewAccessToken creates new access token.
  28. func NewAccessToken(t *AccessToken) error {
  29. t.Sha1 = base.EncodeSha1(gouuid.NewV4().String())
  30. _, err := x.Insert(t)
  31. return err
  32. }
  33. // GetAccessTokenBySHA returns access token by given sha1.
  34. func GetAccessTokenBySHA(sha string) (*AccessToken, error) {
  35. if sha == "" {
  36. return nil, ErrAccessTokenEmpty{}
  37. }
  38. t := &AccessToken{Sha1: sha}
  39. has, err := x.Get(t)
  40. if err != nil {
  41. return nil, err
  42. } else if !has {
  43. return nil, ErrAccessTokenNotExist{sha}
  44. }
  45. return t, nil
  46. }
  47. // ListAccessTokens returns a list of access tokens belongs to given user.
  48. func ListAccessTokens(uid int64) ([]*AccessToken, error) {
  49. tokens := make([]*AccessToken, 0, 5)
  50. return tokens, x.
  51. Where("uid=?", uid).
  52. Desc("id").
  53. Find(&tokens)
  54. }
  55. // UpdateAccessToken updates information of access token.
  56. func UpdateAccessToken(t *AccessToken) error {
  57. _, err := x.ID(t.ID).AllCols().Update(t)
  58. return err
  59. }
  60. // DeleteAccessTokenByID deletes access token by given ID.
  61. func DeleteAccessTokenByID(id, userID int64) error {
  62. cnt, err := x.ID(id).Delete(&AccessToken{
  63. UID: userID,
  64. })
  65. if err != nil {
  66. return err
  67. } else if cnt != 1 {
  68. return ErrAccessTokenNotExist{}
  69. }
  70. return nil
  71. }