onasty/mailer/template.go (view raw)
Olexandr Smirnov
Olexandr Smirnov
ss2316544@gmail.com feat(api): change email (#191)..., 9 months ago
ss2316544@gmail.com feat(api): change email (#191)..., 9 months ago
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | ) |
| 7 | |
| 8 | var ErrInvalidTemplate = errors.New("failed to get template") |
| 9 | |
| 10 | type Template struct { |
| 11 | Subject string |
| 12 | Body string |
| 13 | } |
| 14 | |
| 15 | type TemplateFunc func(args map[string]string) Template |
| 16 | |
| 17 | func getTemplate(appURL, frontendURL string, templateName string) (TemplateFunc, error) { |
| 18 | switch templateName { |
| 19 | case "email_verification": |
| 20 | return emailVerificationTemplate(appURL), nil |
| 21 | case "reset_password": |
| 22 | return passwordResetTemplate(frontendURL), nil |
| 23 | case "confirm_email_change": |
| 24 | return confirmEmailChangeTemplate(appURL), nil |
| 25 | default: |
| 26 | return nil, ErrInvalidTemplate |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | func emailVerificationTemplate(appURL string) TemplateFunc { |
| 31 | return func(opts map[string]string) Template { |
| 32 | link := fmt.Sprintf("%[1]s/api/v1/auth/verify/%[2]s", appURL, opts["token"]) |
| 33 | |
| 34 | return Template{ |
| 35 | Subject: "Onasty: verify your email", |
| 36 | Body: fmt.Sprintf(`To verify your email, please follow this link: |
| 37 | <a href="%[1]s">%[1]s</a> |
| 38 | <br> |
| 39 | <br> |
| 40 | This link will expire after 24 hours.`, link), |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | func passwordResetTemplate(frontendURL string) TemplateFunc { |
| 46 | return func(opts map[string]string) Template { |
| 47 | link := fmt.Sprintf("%[1]s/auth?token=%[2]s", frontendURL, opts["token"]) |
| 48 | |
| 49 | return Template{ |
| 50 | Subject: "Onasty: reset your password", |
| 51 | Body: fmt.Sprintf(`To reset your password, use this api: |
| 52 | <a href="%[1]s">%[1]s</a> |
| 53 | <br> |
| 54 | <br> |
| 55 | This link will expire after an hour.`, link), |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | func confirmEmailChangeTemplate(appURL string) TemplateFunc { |
| 61 | return func(opts map[string]string) Template { |
| 62 | link := fmt.Sprintf("%[1]s/api/v1/auth/change-email/%[2]s", appURL, opts["token"]) |
| 63 | |
| 64 | return Template{ |
| 65 | Subject: "Onasty: confirm your email change", |
| 66 | Body: fmt.Sprintf(` |
| 67 | It seems like you have changed your email address to %[1]s. |
| 68 | <br> |
| 69 | To confirm this change, please follow this link: |
| 70 | <a href="%[2]s">%[2]s</a> |
| 71 | <br> |
| 72 | <br> |
| 73 | If you did not request email change, you can ignore this message. |
| 74 | <br> |
| 75 | This link will expire after 24 hours. |
| 76 | `, opts["email"], link), |
| 77 | } |
| 78 | } |
| 79 | } |