access_tokens.go 4.3 KB

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