zrok/controller/resetPasswordEmail.go

83 lines
2.2 KiB
Go
Raw Normal View History

2023-01-18 20:05:10 +01:00
package controller
import (
"bytes"
"fmt"
2023-01-20 18:25:14 +01:00
"github.com/openziti/zrok/build"
2023-01-18 20:05:10 +01:00
"html/template"
"github.com/openziti/zrok/controller/emailUi"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/wneessen/go-mail"
)
type resetPasswordEmail struct {
EmailAddress string
Url string
2023-01-20 18:25:14 +01:00
Version string
2023-01-18 20:05:10 +01:00
}
func sendResetPasswordEmail(emailAddress, token string) error {
emailData := &resetPasswordEmail{
EmailAddress: emailAddress,
Url: fmt.Sprintf("%s/%s", cfg.ResetPassword.ResetUrlTemplate, token),
2023-01-20 18:25:14 +01:00
Version: build.String(),
2023-01-18 20:05:10 +01:00
}
plainBody, err := emailData.mergeTemplate("resetPassword.gotext")
2023-01-18 20:05:10 +01:00
if err != nil {
return err
}
htmlBody, err := emailData.mergeTemplate("resetPassword.gohtml")
2023-01-18 20:05:10 +01:00
if err != nil {
return err
}
msg := mail.NewMsg()
if err := msg.From(cfg.Registration.EmailFrom); err != nil {
return errors.Wrap(err, "failed to set from address in reset password email")
2023-01-18 20:05:10 +01:00
}
if err := msg.To(emailAddress); err != nil {
return errors.Wrap(err, "failed to set to address in reset password email")
2023-01-18 20:05:10 +01:00
}
msg.Subject("Password Reset Request")
2023-01-18 20:05:10 +01:00
msg.SetDate()
msg.SetMessageID()
msg.SetBulk()
msg.SetImportance(mail.ImportanceHigh)
msg.SetBodyString(mail.TypeTextPlain, plainBody)
msg.SetBodyString(mail.TypeTextHTML, htmlBody)
client, err := mail.NewClient(cfg.Email.Host,
mail.WithPort(cfg.Email.Port),
mail.WithSMTPAuth(mail.SMTPAuthPlain),
mail.WithUsername(cfg.Email.Username),
mail.WithPassword(cfg.Email.Password),
mail.WithTLSPolicy(mail.TLSMandatory),
)
if err != nil {
return errors.Wrap(err, "error creating reset password email client")
2023-01-18 20:05:10 +01:00
}
if err := client.DialAndSend(msg); err != nil {
return errors.Wrap(err, "error sending reset password email")
2023-01-18 20:05:10 +01:00
}
logrus.Infof("reset password email sent to '%v'", emailAddress)
2023-01-18 20:05:10 +01:00
return nil
}
func (fpe resetPasswordEmail) mergeTemplate(filename string) (string, error) {
2023-01-18 20:05:10 +01:00
t, err := template.ParseFS(emailUi.FS, filename)
if err != nil {
return "", errors.Wrapf(err, "error parsing verification email template '%v'", filename)
}
buf := new(bytes.Buffer)
if err := t.Execute(buf, fpe); err != nil {
return "", errors.Wrapf(err, "error executing verification email template '%v'", filename)
}
return buf.String(), nil
}