access_tokens.go 5.3 KB

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