email_addresses.go 2.0 KB

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