access_tokens.go 5.0 KB

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