email_addresses.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2022 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. "context"
  7. "fmt"
  8. "github.com/pkg/errors"
  9. "gorm.io/gorm"
  10. "gogs.io/gogs/internal/errutil"
  11. )
  12. // EmailAddressesStore is the persistent interface for email addresses.
  13. //
  14. // NOTE: All methods are sorted in alphabetical order.
  15. type EmailAddressesStore interface {
  16. // GetByEmail returns the email address with given email. If `needsActivated` is
  17. // true, only activated email will be returned, otherwise, it may return
  18. // inactivated email addresses. It returns ErrEmailNotExist when no qualified
  19. // email is not found.
  20. GetByEmail(ctx context.Context, email string, needsActivated bool) (*EmailAddress, error)
  21. }
  22. var EmailAddresses EmailAddressesStore
  23. var _ EmailAddressesStore = (*emailAddresses)(nil)
  24. type emailAddresses struct {
  25. *gorm.DB
  26. }
  27. // NewEmailAddressesStore returns a persistent interface for email addresses
  28. // with given database connection.
  29. func NewEmailAddressesStore(db *gorm.DB) EmailAddressesStore {
  30. return &emailAddresses{DB: db}
  31. }
  32. var _ errutil.NotFound = (*ErrEmailNotExist)(nil)
  33. type ErrEmailNotExist struct {
  34. args errutil.Args
  35. }
  36. // IsErrEmailAddressNotExist returns true if the underlying error has the type
  37. // ErrEmailNotExist.
  38. func IsErrEmailAddressNotExist(err error) bool {
  39. _, ok := errors.Cause(err).(ErrEmailNotExist)
  40. return ok
  41. }
  42. func (err ErrEmailNotExist) Error() string {
  43. return fmt.Sprintf("email address does not exist: %v", err.args)
  44. }
  45. func (ErrEmailNotExist) NotFound() bool {
  46. return true
  47. }
  48. func (db *emailAddresses) GetByEmail(ctx context.Context, email string, needsActivated bool) (*EmailAddress, error) {
  49. tx := db.WithContext(ctx).Where("email = ?", email)
  50. if needsActivated {
  51. tx = tx.Where("is_activated = ?", true)
  52. }
  53. emailAddress := new(EmailAddress)
  54. err := tx.First(emailAddress).Error
  55. if err != nil {
  56. if err == gorm.ErrRecordNotFound {
  57. return nil, ErrEmailNotExist{
  58. args: errutil.Args{
  59. "email": email,
  60. },
  61. }
  62. }
  63. return nil, err
  64. }
  65. return emailAddress, nil
  66. }