access_tokens.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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 `gorm:"primarykey"`
  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. if t.UpdatedUnix > 0 {
  61. t.Updated = time.Unix(t.UpdatedUnix, 0).Local()
  62. t.HasUsed = t.Updated.After(t.Created)
  63. t.HasRecentActivity = t.Updated.Add(7 * 24 * time.Hour).After(tx.NowFunc())
  64. }
  65. return nil
  66. }
  67. var _ AccessTokensStore = (*accessTokens)(nil)
  68. type accessTokens struct {
  69. *gorm.DB
  70. }
  71. type ErrAccessTokenAlreadyExist struct {
  72. args errutil.Args
  73. }
  74. func IsErrAccessTokenAlreadyExist(err error) bool {
  75. _, ok := err.(ErrAccessTokenAlreadyExist)
  76. return ok
  77. }
  78. func (err ErrAccessTokenAlreadyExist) Error() string {
  79. return fmt.Sprintf("access token already exists: %v", err.args)
  80. }
  81. func (db *accessTokens) Create(ctx context.Context, userID int64, name string) (*AccessToken, error) {
  82. err := db.WithContext(ctx).Where("uid = ? AND name = ?", userID, name).First(new(AccessToken)).Error
  83. if err == nil {
  84. return nil, ErrAccessTokenAlreadyExist{args: errutil.Args{"userID": userID, "name": name}}
  85. } else if err != gorm.ErrRecordNotFound {
  86. return nil, err
  87. }
  88. token := cryptoutil.SHA1(gouuid.NewV4().String())
  89. sha256 := cryptoutil.SHA256(token)
  90. accessToken := &AccessToken{
  91. UserID: userID,
  92. Name: name,
  93. Sha1: sha256[:40], // To pass the column unique constraint, keep the length of SHA1.
  94. SHA256: sha256,
  95. }
  96. if err = db.WithContext(ctx).Create(accessToken).Error; err != nil {
  97. return nil, err
  98. }
  99. // Set back the raw access token value, for the sake of the caller.
  100. accessToken.Sha1 = token
  101. return accessToken, nil
  102. }
  103. func (db *accessTokens) DeleteByID(ctx context.Context, userID, id int64) error {
  104. return db.WithContext(ctx).Where("id = ? AND uid = ?", id, userID).Delete(new(AccessToken)).Error
  105. }
  106. var _ errutil.NotFound = (*ErrAccessTokenNotExist)(nil)
  107. type ErrAccessTokenNotExist struct {
  108. args errutil.Args
  109. }
  110. func IsErrAccessTokenNotExist(err error) bool {
  111. _, ok := err.(ErrAccessTokenNotExist)
  112. return ok
  113. }
  114. func (err ErrAccessTokenNotExist) Error() string {
  115. return fmt.Sprintf("access token does not exist: %v", err.args)
  116. }
  117. func (ErrAccessTokenNotExist) NotFound() bool {
  118. return true
  119. }
  120. func (db *accessTokens) GetBySHA1(ctx context.Context, sha1 string) (*AccessToken, error) {
  121. // No need to waste a query for an empty SHA1.
  122. if sha1 == "" {
  123. return nil, ErrAccessTokenNotExist{args: errutil.Args{"sha": sha1}}
  124. }
  125. sha256 := cryptoutil.SHA256(sha1)
  126. token := new(AccessToken)
  127. err := db.WithContext(ctx).Where("sha256 = ?", sha256).First(token).Error
  128. if err != nil {
  129. if err == gorm.ErrRecordNotFound {
  130. return nil, ErrAccessTokenNotExist{args: errutil.Args{"sha": sha1}}
  131. }
  132. return nil, err
  133. }
  134. return token, nil
  135. }
  136. func (db *accessTokens) List(ctx context.Context, userID int64) ([]*AccessToken, error) {
  137. var tokens []*AccessToken
  138. return tokens, db.WithContext(ctx).Where("uid = ?", userID).Order("id ASC").Find(&tokens).Error
  139. }
  140. func (db *accessTokens) Touch(ctx context.Context, id int64) error {
  141. return db.WithContext(ctx).
  142. Model(new(AccessToken)).
  143. Where("id = ?", id).
  144. UpdateColumn("updated_unix", db.NowFunc().Unix()).
  145. Error
  146. }