email_addresses.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. "gorm.io/gorm"
  9. "gogs.io/gogs/internal/errutil"
  10. )
  11. // EmailAddressesStore is the persistent interface for email addresses.
  12. //
  13. // NOTE: All methods are sorted in alphabetical order.
  14. type EmailAddressesStore interface {
  15. // GetByEmail returns the email address with given email. It may return
  16. // unverified email addresses and returns ErrEmailNotExist when not found.
  17. GetByEmail(ctx context.Context, email string) (*EmailAddress, error)
  18. }
  19. var EmailAddresses EmailAddressesStore
  20. var _ EmailAddressesStore = (*emailAddresses)(nil)
  21. type emailAddresses struct {
  22. *gorm.DB
  23. }
  24. // NewEmailAddressesStore returns a persistent interface for email addresses
  25. // with given database connection.
  26. func NewEmailAddressesStore(db *gorm.DB) EmailAddressesStore {
  27. return &emailAddresses{DB: db}
  28. }
  29. var _ errutil.NotFound = (*ErrEmailNotExist)(nil)
  30. type ErrEmailNotExist struct {
  31. args errutil.Args
  32. }
  33. func IsErrEmailAddressNotExist(err error) bool {
  34. _, ok := err.(ErrEmailNotExist)
  35. return ok
  36. }
  37. func (err ErrEmailNotExist) Error() string {
  38. return fmt.Sprintf("email address does not exist: %v", err.args)
  39. }
  40. func (ErrEmailNotExist) NotFound() bool {
  41. return true
  42. }
  43. func (db *emailAddresses) GetByEmail(ctx context.Context, email string) (*EmailAddress, error) {
  44. emailAddress := new(EmailAddress)
  45. err := db.WithContext(ctx).Where("email = ?", email).First(emailAddress).Error
  46. if err != nil {
  47. if err == gorm.ErrRecordNotFound {
  48. return nil, ErrEmailNotExist{
  49. args: errutil.Args{
  50. "email": email,
  51. },
  52. }
  53. }
  54. return nil, err
  55. }
  56. return emailAddress, nil
  57. }