access_tokens.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. "github.com/jinzhu/gorm"
  9. gouuid "github.com/satori/go.uuid"
  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() {
  50. if t.CreatedUnix > 0 {
  51. return
  52. }
  53. t.CreatedUnix = gorm.NowFunc().Unix()
  54. }
  55. // NOTE: This is a GORM update hook.
  56. func (t *AccessToken) BeforeUpdate() {
  57. t.UpdatedUnix = gorm.NowFunc().Unix()
  58. }
  59. // NOTE: This is a GORM query hook.
  60. func (t *AccessToken) AfterFind() {
  61. t.Created = time.Unix(t.CreatedUnix, 0).Local()
  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(gorm.NowFunc())
  65. }
  66. var _ AccessTokensStore = (*accessTokens)(nil)
  67. type accessTokens struct {
  68. *gorm.DB
  69. }
  70. type ErrAccessTokenAlreadyExist struct {
  71. args errutil.Args
  72. }
  73. func IsErrAccessTokenAlreadyExist(err error) bool {
  74. _, ok := err.(ErrAccessTokenAlreadyExist)
  75. return ok
  76. }
  77. func (err ErrAccessTokenAlreadyExist) Error() string {
  78. return fmt.Sprintf("access token already exists: %v", err.args)
  79. }
  80. func (db *accessTokens) Create(userID int64, name string) (*AccessToken, error) {
  81. err := db.Where("uid = ? AND name = ?", userID, name).First(new(AccessToken)).Error
  82. if err == nil {
  83. return nil, ErrAccessTokenAlreadyExist{args: errutil.Args{"userID": userID, "name": name}}
  84. } else if !gorm.IsRecordNotFoundError(err) {
  85. return nil, err
  86. }
  87. token := &AccessToken{
  88. UserID: userID,
  89. Name: name,
  90. Sha1: cryptoutil.SHA1(gouuid.NewV4().String()),
  91. }
  92. return token, db.DB.Create(token).Error
  93. }
  94. func (db *accessTokens) DeleteByID(userID, id int64) error {
  95. return db.Where("id = ? AND uid = ?", id, userID).Delete(new(AccessToken)).Error
  96. }
  97. var _ errutil.NotFound = (*ErrAccessTokenNotExist)(nil)
  98. type ErrAccessTokenNotExist struct {
  99. args errutil.Args
  100. }
  101. func IsErrAccessTokenNotExist(err error) bool {
  102. _, ok := err.(ErrAccessTokenNotExist)
  103. return ok
  104. }
  105. func (err ErrAccessTokenNotExist) Error() string {
  106. return fmt.Sprintf("access token does not exist: %v", err.args)
  107. }
  108. func (ErrAccessTokenNotExist) NotFound() bool {
  109. return true
  110. }
  111. func (db *accessTokens) GetBySHA(sha string) (*AccessToken, error) {
  112. token := new(AccessToken)
  113. err := db.Where("sha1 = ?", sha).First(token).Error
  114. if err != nil {
  115. if gorm.IsRecordNotFoundError(err) {
  116. return nil, ErrAccessTokenNotExist{args: errutil.Args{"sha": sha}}
  117. }
  118. return nil, err
  119. }
  120. return token, nil
  121. }
  122. func (db *accessTokens) List(userID int64) ([]*AccessToken, error) {
  123. var tokens []*AccessToken
  124. return tokens, db.Where("uid = ?", userID).Find(&tokens).Error
  125. }
  126. func (db *accessTokens) Save(t *AccessToken) error {
  127. return db.DB.Save(t).Error
  128. }