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. //
  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. 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. }