access_tokens.go 5.0 KB

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