access_tokens.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. "fmt"
  7. "time"
  8. gouuid "github.com/satori/go.uuid"
  9. "gorm.io/gorm"
  10. "gogs.io/gogs/internal/cryptoutil"
  11. "gogs.io/gogs/internal/errutil"
  12. )
  13. // AccessTokensStore is the persistent interface for access tokens.
  14. //
  15. // NOTE: All methods are sorted in alphabetical order.
  16. type AccessTokensStore interface {
  17. // Create creates a new access token and persist to database.
  18. // It returns ErrAccessTokenAlreadyExist when an access token
  19. // with same name already exists for the user.
  20. Create(userID int64, name string) (*AccessToken, error)
  21. // DeleteByID deletes the access token by given ID.
  22. // 🚨 SECURITY: The "userID" is required to prevent attacker
  23. // deletes arbitrary access token that belongs to another user.
  24. DeleteByID(userID, id int64) error
  25. // GetBySHA returns the access token with given SHA1.
  26. // It returns ErrAccessTokenNotExist when not found.
  27. GetBySHA(sha string) (*AccessToken, error)
  28. // List returns all access tokens belongs to given user.
  29. List(userID int64) ([]*AccessToken, error)
  30. // Save persists all values of given access token.
  31. // The Updated field is set to current time automatically.
  32. Save(t *AccessToken) error
  33. }
  34. var AccessTokens AccessTokensStore
  35. // AccessToken is a personal access token.
  36. type AccessToken struct {
  37. ID int64
  38. UserID int64 `xorm:"uid INDEX" gorm:"COLUMN:uid;INDEX"`
  39. Name string
  40. Sha1 string `xorm:"UNIQUE VARCHAR(40)" gorm:"TYPE:VARCHAR(40);UNIQUE"`
  41. Created time.Time `xorm:"-" gorm:"-" json:"-"`
  42. CreatedUnix int64
  43. Updated time.Time `xorm:"-" gorm:"-" json:"-"`
  44. UpdatedUnix int64
  45. HasRecentActivity bool `xorm:"-" gorm:"-" json:"-"`
  46. HasUsed bool `xorm:"-" gorm:"-" json:"-"`
  47. }
  48. // NOTE: This is a GORM create hook.
  49. func (t *AccessToken) BeforeCreate(tx *gorm.DB) error {
  50. if t.CreatedUnix == 0 {
  51. t.CreatedUnix = tx.NowFunc().Unix()
  52. }
  53. return nil
  54. }
  55. // NOTE: This is a GORM update hook.
  56. func (t *AccessToken) BeforeUpdate(tx *gorm.DB) error {
  57. t.UpdatedUnix = tx.NowFunc().Unix()
  58. return nil
  59. }
  60. // NOTE: This is a GORM query hook.
  61. func (t *AccessToken) AfterFind(tx *gorm.DB) error {
  62. t.Created = time.Unix(t.CreatedUnix, 0).Local()
  63. t.Updated = time.Unix(t.UpdatedUnix, 0).Local()
  64. t.HasUsed = t.Updated.After(t.Created)
  65. t.HasRecentActivity = t.Updated.Add(7 * 24 * time.Hour).After(tx.NowFunc())
  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(userID int64, name string) (*AccessToken, error) {
  83. err := db.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 := &AccessToken{
  90. UserID: userID,
  91. Name: name,
  92. Sha1: cryptoutil.SHA1(gouuid.NewV4().String()),
  93. }
  94. return token, db.DB.Create(token).Error
  95. }
  96. func (db *accessTokens) DeleteByID(userID, id int64) error {
  97. return db.Where("id = ? AND uid = ?", id, userID).Delete(new(AccessToken)).Error
  98. }
  99. var _ errutil.NotFound = (*ErrAccessTokenNotExist)(nil)
  100. type ErrAccessTokenNotExist struct {
  101. args errutil.Args
  102. }
  103. func IsErrAccessTokenNotExist(err error) bool {
  104. _, ok := err.(ErrAccessTokenNotExist)
  105. return ok
  106. }
  107. func (err ErrAccessTokenNotExist) Error() string {
  108. return fmt.Sprintf("access token does not exist: %v", err.args)
  109. }
  110. func (ErrAccessTokenNotExist) NotFound() bool {
  111. return true
  112. }
  113. func (db *accessTokens) GetBySHA(sha string) (*AccessToken, error) {
  114. token := new(AccessToken)
  115. err := db.Where("sha1 = ?", sha).First(token).Error
  116. if err != nil {
  117. if err == gorm.ErrRecordNotFound {
  118. return nil, ErrAccessTokenNotExist{args: errutil.Args{"sha": sha}}
  119. }
  120. return nil, err
  121. }
  122. return token, nil
  123. }
  124. func (db *accessTokens) List(userID int64) ([]*AccessToken, error) {
  125. var tokens []*AccessToken
  126. return tokens, db.Where("uid = ?", userID).Find(&tokens).Error
  127. }
  128. func (db *accessTokens) Save(t *AccessToken) error {
  129. return db.DB.Save(t).Error
  130. }