access_tokens.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. "github.com/jinzhu/gorm"
  8. "gogs.io/gogs/internal/errutil"
  9. )
  10. // AccessTokensStore is the persistent interface for access tokens.
  11. //
  12. // NOTE: All methods are sorted in alphabetical order.
  13. type AccessTokensStore interface {
  14. // GetBySHA returns the access token with given SHA1.
  15. // It returns ErrAccessTokenNotExist when not found.
  16. GetBySHA(sha string) (*AccessToken, error)
  17. // Save persists all values of given access token.
  18. Save(t *AccessToken) error
  19. }
  20. var AccessTokens AccessTokensStore
  21. type accessTokens struct {
  22. *gorm.DB
  23. }
  24. var _ errutil.NotFound = (*ErrAccessTokenNotExist)(nil)
  25. type ErrAccessTokenNotExist struct {
  26. args errutil.Args
  27. }
  28. func IsErrAccessTokenNotExist(err error) bool {
  29. _, ok := err.(ErrAccessTokenNotExist)
  30. return ok
  31. }
  32. func (err ErrAccessTokenNotExist) Error() string {
  33. return fmt.Sprintf("access token does not exist: %v", err.args)
  34. }
  35. func (ErrAccessTokenNotExist) NotFound() bool {
  36. return true
  37. }
  38. func (db *accessTokens) GetBySHA(sha string) (*AccessToken, error) {
  39. token := new(AccessToken)
  40. err := db.Where("sha1 = ?", sha).First(token).Error
  41. if err != nil {
  42. if gorm.IsRecordNotFoundError(err) {
  43. return nil, ErrAccessTokenNotExist{args: errutil.Args{"sha": sha}}
  44. }
  45. return nil, err
  46. }
  47. return token, nil
  48. }
  49. func (db *accessTokens) Save(t *AccessToken) error {
  50. return db.DB.Save(t).Error
  51. }