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