access_tokens.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. // Save persists all values of given access token. The Updated field is set to
  33. // current time automatically.
  34. Save(ctx context.Context, t *AccessToken) error
  35. }
  36. var AccessTokens AccessTokensStore
  37. // AccessToken is a personal access token.
  38. type AccessToken struct {
  39. ID int64
  40. UserID int64 `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. // BeforeUpdate implements the GORM update hook.
  59. func (t *AccessToken) BeforeUpdate(tx *gorm.DB) error {
  60. t.UpdatedUnix = tx.NowFunc().Unix()
  61. return nil
  62. }
  63. // AfterFind implements the GORM query hook.
  64. func (t *AccessToken) AfterFind(tx *gorm.DB) error {
  65. t.Created = time.Unix(t.CreatedUnix, 0).Local()
  66. t.Updated = time.Unix(t.UpdatedUnix, 0).Local()
  67. t.HasUsed = t.Updated.After(t.Created)
  68. t.HasRecentActivity = t.Updated.Add(7 * 24 * time.Hour).After(tx.NowFunc())
  69. return nil
  70. }
  71. var _ AccessTokensStore = (*accessTokens)(nil)
  72. type accessTokens struct {
  73. *gorm.DB
  74. }
  75. type ErrAccessTokenAlreadyExist struct {
  76. args errutil.Args
  77. }
  78. func IsErrAccessTokenAlreadyExist(err error) bool {
  79. _, ok := err.(ErrAccessTokenAlreadyExist)
  80. return ok
  81. }
  82. func (err ErrAccessTokenAlreadyExist) Error() string {
  83. return fmt.Sprintf("access token already exists: %v", err.args)
  84. }
  85. func (db *accessTokens) Create(ctx context.Context, userID int64, name string) (*AccessToken, error) {
  86. err := db.WithContext(ctx).Where("uid = ? AND name = ?", userID, name).First(new(AccessToken)).Error
  87. if err == nil {
  88. return nil, ErrAccessTokenAlreadyExist{args: errutil.Args{"userID": userID, "name": name}}
  89. } else if err != gorm.ErrRecordNotFound {
  90. return nil, err
  91. }
  92. token := cryptoutil.SHA1(gouuid.NewV4().String())
  93. sha256 := cryptoutil.SHA256(token)
  94. accessToken := &AccessToken{
  95. UserID: userID,
  96. Name: name,
  97. Sha1: sha256[:40], // To pass the column unique constraint, keep the length of SHA1.
  98. SHA256: sha256,
  99. }
  100. if err = db.DB.WithContext(ctx).Create(accessToken).Error; err != nil {
  101. return nil, err
  102. }
  103. // Set back the raw access token value, for the sake of the caller.
  104. accessToken.Sha1 = token
  105. return accessToken, nil
  106. }
  107. func (db *accessTokens) DeleteByID(ctx context.Context, userID, id int64) error {
  108. return db.WithContext(ctx).Where("id = ? AND uid = ?", id, userID).Delete(new(AccessToken)).Error
  109. }
  110. var _ errutil.NotFound = (*ErrAccessTokenNotExist)(nil)
  111. type ErrAccessTokenNotExist struct {
  112. args errutil.Args
  113. }
  114. func IsErrAccessTokenNotExist(err error) bool {
  115. _, ok := err.(ErrAccessTokenNotExist)
  116. return ok
  117. }
  118. func (err ErrAccessTokenNotExist) Error() string {
  119. return fmt.Sprintf("access token does not exist: %v", err.args)
  120. }
  121. func (ErrAccessTokenNotExist) NotFound() bool {
  122. return true
  123. }
  124. func (db *accessTokens) GetBySHA1(ctx context.Context, sha1 string) (*AccessToken, error) {
  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) Save(ctx context.Context, t *AccessToken) error {
  141. return db.DB.WithContext(ctx).Save(t).Error
  142. }