From 6f61f09ba433d3d290ea44385b8ba03b8fd39d66 Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Tue, 13 Feb 2024 19:41:00 -0500 Subject: [PATCH] refactor: move email validation to gorm --- api/s5/http.go | 15 --------------- db/models/user.go | 23 +++++++++++++++++++++++ 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/api/s5/http.go b/api/s5/http.go index 3e8ad60..2840db3 100644 --- a/api/s5/http.go +++ b/api/s5/http.go @@ -106,16 +106,8 @@ type HttpHandlerResult struct { } func NewHttpHandler(params HttpHandlerParams) (HttpHandlerResult, error) { - verifier := emailverifier.NewVerifier() - - verifier.DisableSMTPCheck() - verifier.DisableGravatarCheck() - verifier.DisableDomainSuggest() - verifier.DisableAutoUpdateDisposable() - return HttpHandlerResult{ HttpHandler: HttpHandler{ - verifier: verifier, config: params.Config, logger: params.Logger, storage: params.Storage, @@ -398,13 +390,6 @@ func (h *HttpHandler) accountRegister(jc jape.Context) { request.Email = fmt.Sprintf("%s@%s", hex.EncodeToString(decodedKey[1:]), "example.com") } - verify, _ := h.verifier.Verify(request.Email) - - if !verify.Syntax.Valid { - errored(errInvalidEmail) - return - } - accountExists, _, _ := h.accounts.EmailExists(request.Email) if accountExists { diff --git a/db/models/user.go b/db/models/user.go index 3b733c5..8e06cf5 100644 --- a/db/models/user.go +++ b/db/models/user.go @@ -2,6 +2,7 @@ package models import ( "errors" + emailverifier "github.com/AfterShip/email-verifier" "gorm.io/gorm" "time" ) @@ -28,5 +29,27 @@ func (u *User) BeforeUpdate(tx *gorm.DB) error { if len(u.LastName) == 0 { return errors.New("last name is empty") } + + verify, err := getEmailVerfier().Verify(u.Email) + + if err != nil { + return err + } + + if !verify.Syntax.Valid { + return errors.New("email is invalid") + } + return nil } + +func getEmailVerfier() *emailverifier.Verifier { + verifier := emailverifier.NewVerifier() + + verifier.DisableSMTPCheck() + verifier.DisableGravatarCheck() + verifier.DisableDomainSuggest() + verifier.DisableAutoUpdateDisposable() + + return verifier +}