access_tokens.go 5.3 KB

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