access_tokens.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. package database
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "github.com/pkg/errors"
  7. gouuid "github.com/satori/go.uuid"
  8. "gorm.io/gorm"
  9. "gogs.io/gogs/internal/cryptoutil"
  10. "gogs.io/gogs/internal/errutil"
  11. )
  12. // AccessToken is a personal access token.
  13. type AccessToken struct {
  14. ID int64 `gorm:"primarykey"`
  15. UserID int64 `xorm:"uid" gorm:"column:uid;index"`
  16. Name string
  17. Sha1 string `gorm:"type:VARCHAR(40);unique"`
  18. SHA256 string `gorm:"type:VARCHAR(64);unique;not null"`
  19. Created time.Time `gorm:"-" json:"-"`
  20. CreatedUnix int64
  21. Updated time.Time `gorm:"-" json:"-"`
  22. UpdatedUnix int64
  23. HasRecentActivity bool `gorm:"-" json:"-"`
  24. HasUsed bool `gorm:"-" json:"-"`
  25. }
  26. // BeforeCreate implements the GORM create hook.
  27. func (t *AccessToken) BeforeCreate(tx *gorm.DB) error {
  28. if t.CreatedUnix == 0 {
  29. t.CreatedUnix = tx.NowFunc().Unix()
  30. }
  31. return nil
  32. }
  33. // AfterFind implements the GORM query hook.
  34. func (t *AccessToken) AfterFind(tx *gorm.DB) error {
  35. t.Created = time.Unix(t.CreatedUnix, 0).Local()
  36. if t.UpdatedUnix > 0 {
  37. t.Updated = time.Unix(t.UpdatedUnix, 0).Local()
  38. t.HasUsed = t.Updated.After(t.Created)
  39. t.HasRecentActivity = t.Updated.Add(7 * 24 * time.Hour).After(tx.NowFunc())
  40. }
  41. return nil
  42. }
  43. // AccessTokensStore is the storage layer for access tokens.
  44. type AccessTokensStore struct {
  45. db *gorm.DB
  46. }
  47. func newAccessTokensStore(db *gorm.DB) *AccessTokensStore {
  48. return &AccessTokensStore{db: db}
  49. }
  50. type ErrAccessTokenAlreadyExist struct {
  51. args errutil.Args
  52. }
  53. func IsErrAccessTokenAlreadyExist(err error) bool {
  54. return errors.As(err, &ErrAccessTokenAlreadyExist{})
  55. }
  56. func (err ErrAccessTokenAlreadyExist) Error() string {
  57. return fmt.Sprintf("access token already exists: %v", err.args)
  58. }
  59. // Create creates a new access token and persist to database. It returns
  60. // ErrAccessTokenAlreadyExist when an access token with same name already exists
  61. // for the user.
  62. func (s *AccessTokensStore) Create(ctx context.Context, userID int64, name string) (*AccessToken, error) {
  63. err := s.db.WithContext(ctx).Where("uid = ? AND name = ?", userID, name).First(new(AccessToken)).Error
  64. if err == nil {
  65. return nil, ErrAccessTokenAlreadyExist{args: errutil.Args{"userID": userID, "name": name}}
  66. } else if !errors.Is(err, gorm.ErrRecordNotFound) {
  67. return nil, err
  68. }
  69. token := cryptoutil.SHA1(gouuid.NewV4().String())
  70. sha256 := cryptoutil.SHA256(token)
  71. accessToken := &AccessToken{
  72. UserID: userID,
  73. Name: name,
  74. Sha1: sha256[:40], // To pass the column unique constraint, keep the length of SHA1.
  75. SHA256: sha256,
  76. }
  77. if err = s.db.WithContext(ctx).Create(accessToken).Error; err != nil {
  78. return nil, err
  79. }
  80. // Set back the raw access token value, for the sake of the caller.
  81. accessToken.Sha1 = token
  82. return accessToken, nil
  83. }
  84. // DeleteByID deletes the access token by given ID.
  85. //
  86. // 🚨 SECURITY: The "userID" is required to prevent attacker deletes arbitrary
  87. // access token that belongs to another user.
  88. func (s *AccessTokensStore) DeleteByID(ctx context.Context, userID, id int64) error {
  89. return s.db.WithContext(ctx).Where("id = ? AND uid = ?", id, userID).Delete(new(AccessToken)).Error
  90. }
  91. var _ errutil.NotFound = (*ErrAccessTokenNotExist)(nil)
  92. type ErrAccessTokenNotExist struct {
  93. args errutil.Args
  94. }
  95. // IsErrAccessTokenNotExist returns true if the underlying error has the type
  96. // ErrAccessTokenNotExist.
  97. func IsErrAccessTokenNotExist(err error) bool {
  98. return errors.As(errors.Cause(err), &ErrAccessTokenNotExist{})
  99. }
  100. func (err ErrAccessTokenNotExist) Error() string {
  101. return fmt.Sprintf("access token does not exist: %v", err.args)
  102. }
  103. func (ErrAccessTokenNotExist) NotFound() bool {
  104. return true
  105. }
  106. // GetBySHA1 returns the access token with given SHA1. It returns
  107. // ErrAccessTokenNotExist when not found.
  108. func (s *AccessTokensStore) GetBySHA1(ctx context.Context, sha1 string) (*AccessToken, error) {
  109. // No need to waste a query for an empty SHA1.
  110. if sha1 == "" {
  111. return nil, ErrAccessTokenNotExist{args: errutil.Args{"sha": sha1}}
  112. }
  113. sha256 := cryptoutil.SHA256(sha1)
  114. token := new(AccessToken)
  115. err := s.db.WithContext(ctx).Where("sha256 = ?", sha256).First(token).Error
  116. if errors.Is(err, gorm.ErrRecordNotFound) {
  117. return nil, ErrAccessTokenNotExist{args: errutil.Args{"sha": sha1}}
  118. } else if err != nil {
  119. return nil, err
  120. }
  121. return token, nil
  122. }
  123. // List returns all access tokens belongs to given user.
  124. func (s *AccessTokensStore) List(ctx context.Context, userID int64) ([]*AccessToken, error) {
  125. var tokens []*AccessToken
  126. return tokens, s.db.WithContext(ctx).Where("uid = ?", userID).Order("id ASC").Find(&tokens).Error
  127. }
  128. // Touch updates the updated time of the given access token to the current time.
  129. func (s *AccessTokensStore) Touch(ctx context.Context, id int64) error {
  130. return s.db.WithContext(ctx).
  131. Model(new(AccessToken)).
  132. Where("id = ?", id).
  133. UpdateColumn("updated_unix", s.db.NowFunc().Unix()).
  134. Error
  135. }