Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DE-1394 Remove deprecated v3 Validation #371

Merged
merged 2 commits into from
Dec 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 14 additions & 62 deletions email_validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,48 +84,32 @@ type EmailValidator interface {
}

type EmailValidatorImpl struct {
client *http.Client
isPublicKey bool
apiBase string
apiKey string
client *http.Client
apiBase string
apiKey string
}

// NewEmailValidator creates a new validation instance.
//
// * For ValidateEmail use private key
//
// * For ParseAddresses use public key
// Use private key.
func NewEmailValidator(apiKey string) *EmailValidatorImpl {
isPublicKey := false

// Did the user pass in a public key?
if strings.HasPrefix(apiKey, "pubkey-") {
isPublicKey = true
}

return &EmailValidatorImpl{
// TODO(vtopc): Don’t use http.DefaultClient - https://medium.com/@nate510/don-t-use-go-s-default-http-client-4804cb19f779
client: http.DefaultClient,
isPublicKey: isPublicKey,
apiBase: "https://api.mailgun.net/v4",
apiKey: apiKey,
client: http.DefaultClient,
apiBase: "https://api.mailgun.net/v4",
apiKey: apiKey,
}
}

// NewEmailValidatorFromEnv returns a new EmailValidator using environment variables
//
// * For ValidateEmail set MG_API_KEY
//
// * For ParseAddresses set MG_PUBLIC_API_KEY
// Set MG_API_KEY
func NewEmailValidatorFromEnv() (*EmailValidatorImpl, error) {
apiKey := os.Getenv("MG_PUBLIC_API_KEY")
apiKey := os.Getenv("MG_API_KEY")
if apiKey == "" {
apiKey = os.Getenv("MG_API_KEY")
if apiKey == "" {
return nil, errors.New(
"environment variable MG_PUBLIC_API_KEY or MG_API_KEY required for email validation")
}
return nil, errors.New(
"environment variable MG_API_KEY required for email validation")
}

v := NewEmailValidator(apiKey)
url := os.Getenv("MG_URL")
if url != "" {
Expand Down Expand Up @@ -159,20 +143,11 @@ func (m *EmailValidatorImpl) APIKey() string {
return m.apiKey
}

func (m *EmailValidatorImpl) getAddressURL(endpoint string) string {
if m.isPublicKey {
return fmt.Sprintf("%s/address/%s", m.APIBase(), endpoint)
}
return fmt.Sprintf("%s/address/private/%s", m.APIBase(), endpoint)
}

// ValidateEmail performs various checks on the email address provided to ensure it's correctly formatted.
// It may also be used to break an email address into its sub-components. If user has set the
// TODO(DE-1384): move to *MailgunImpl?
func (m *EmailValidatorImpl) ValidateEmail(ctx context.Context, email string, mailBoxVerify bool) (EmailVerification, error) {
if m.isPublicKey {
return EmailVerification{}, errors.New("ValidateEmail: public key is not supported anymore, use private key")
}

// TODO(DE-1383): remove check:
if strings.HasSuffix(m.APIBase(), "/v4") {
return m.validateV4(ctx, email, mailBoxVerify)
}
Expand Down Expand Up @@ -208,26 +183,3 @@ func (m *EmailValidatorImpl) validateV4(ctx context.Context, email string, mailB
Engagement: res.Engagement,
}, nil
}

// ParseAddresses takes a list of addresses and sorts them into valid and invalid address categories.
// NOTE: Use of this function requires a proper public API key. The private API key will not work.
//
// NOTE: Only for v3. To use the /v3 version of validations define MG_URL in the environment variable
// as `https://api.mailgun.net/v3` or set `v.SetAPIBase("https://api.mailgun.net/v3")`
//
// Deprecated: /v3/address/parse is deprecated use ValidateEmail instead.
// TODO(v5): remove
func (m *EmailValidatorImpl) ParseAddresses(ctx context.Context, addresses ...string) (parsed, unparseable []string, err error) {
r := newHTTPRequest(m.getAddressURL("parse"))
r.setClient(m.Client())
r.addParameter("addresses", strings.Join(addresses, ","))
r.setBasicAuth(basicAuthUser, m.APIKey())

var response addressParseResult
err = getResponseFromJSON(ctx, r, &response)
if err != nil {
return nil, nil, err
}

return response.Parsed, response.Unparseable, nil
}
20 changes: 0 additions & 20 deletions email_validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,26 +36,6 @@ func TestEmailValidationV4(t *testing.T) {
assert.False(t, ev.Engagement.IsBot)
}

func TestParseAddresses(t *testing.T) {
v := mailgun.NewEmailValidator(testKey)
v.SetAPIBase(server.URL())
ctx := context.Background()

addressesThatParsed, unparsableAddresses, err := v.ParseAddresses(ctx,
"Alice <[email protected]>",
"[email protected]",
"example.com")
require.NoError(t, err)
hittest := map[string]bool{
"Alice <[email protected]>": true,
"[email protected]": true,
}
for _, a := range addressesThatParsed {
require.True(t, hittest[a])
}
require.Len(t, unparsableAddresses, 1)
}

func TestUnmarshallResponse(t *testing.T) {
payload := []byte(`{
"address": "[email protected]",
Expand Down
13 changes: 0 additions & 13 deletions examples/examples.go
Original file line number Diff line number Diff line change
Expand Up @@ -545,19 +545,6 @@ func ListMailingLists(domain, apiKey string) ([]mailgun.MailingList, error) {
return result, nil
}

func ParseAddress(apiKey string) ([]string, []string, error) {
mv := mailgun.NewEmailValidator(apiKey)

ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()

return mv.ParseAddresses(ctx,
"Alice <[email protected]>",
"[email protected]",
// ...
)
}

func GetRoute(domain, apiKey string) (mailgun.Route, error) {
mg := mailgun.NewMailgun(domain, apiKey)

Expand Down
24 changes: 0 additions & 24 deletions examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,30 +35,6 @@ func ExampleEmailValidatorImpl_ValidateEmail() {
}
}

func ExampleEmailValidatorImpl_ParseAddresses() {
v := mailgun.NewEmailValidator("my_public_validation_api_key")

ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()

addressesThatParsed, unparsableAddresses, err := v.ParseAddresses(ctx, "Alice <[email protected]>", "[email protected]", "example.com")
if err != nil {
log.Fatal(err)
}
hittest := map[string]bool{
"Alice <[email protected]>": true,
"[email protected]": true,
}
for _, a := range addressesThatParsed {
if !hittest[a] {
log.Fatalf("Expected %s to be parsable", a)
}
}
if len(unparsableAddresses) != 1 {
log.Fatalf("Expected 1 address to be unparsable; got %d", len(unparsableAddresses))
}
}

func ExampleMailgunImpl_UpdateMailingList() {
mg := mailgun.NewMailgun("example.com", "my_api_key")

Expand Down
Loading