From e3ff957c67c1aaa0056ee437b62b81cc1c10b8ef Mon Sep 17 00:00:00 2001 From: Aditya Thebe Date: Tue, 22 Oct 2024 20:13:54 +0545 Subject: [PATCH] chore: use gotemplate for invitation email --- auth/controllers.go | 21 +++++++++++++++------ auth/templates.go | 21 ++++++++++++++++++--- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/auth/controllers.go b/auth/controllers.go index 67bb2be3..167a091f 100644 --- a/auth/controllers.go +++ b/auth/controllers.go @@ -1,6 +1,7 @@ package auth import ( + "bytes" "fmt" "net/http" "os" @@ -69,8 +70,18 @@ func (k *KratosHandler) InviteUser(c echo.Context) error { return c.JSON(http.StatusInternalServerError, dutyAPI.HTTPError{Err: err.Error(), Message: "error creating recovery link"}) } - body := fmt.Sprintf(inviteUserTemplate, reqData.FirstName, recoveryLink, recoveryCode) - inviteMail := mail.New(reqData.Email, "User Invite", body, "text/html") + data := map[string]string{ + "firstName": reqData.FirstName, + "link": recoveryLink, + "code": recoveryCode, + } + + var body bytes.Buffer + if err := inviteUserTemplate.Execute(&body, data); err != nil { + return err + } + + inviteMail := mail.New(reqData.Email, "User Invite", body.String(), "text/html") if err = inviteMail.Send(); err != nil { return c.JSON(http.StatusInternalServerError, dutyAPI.HTTPError{ Err: err.Error(), @@ -78,10 +89,8 @@ func (k *KratosHandler) InviteUser(c echo.Context) error { }) } - return c.JSON(http.StatusOK, map[string]string{ - "link": recoveryLink, - "code": recoveryCode, - }) + delete(data, "firstName") + return c.JSON(http.StatusOK, data) } func UpdateAccountState(c echo.Context) error { diff --git a/auth/templates.go b/auth/templates.go index 2dbcb20b..08be0c29 100644 --- a/auth/templates.go +++ b/auth/templates.go @@ -1,8 +1,23 @@ package auth -const inviteUserTemplate = ` +import ( + "fmt" + "html/template" + + "github.com/flanksource/duty/shutdown" +) + +var inviteUserTemplate *template.Template + +func init() { + parsed, err := template.New("email").Parse(` Welcome to Mission Control

-Hello %s, +Hello {{.firstName}},
+Please visit {{.link}} to complete registration and use the code: {{.code}}`) + if err != nil { + shutdown.ShutdownAndExit(1, fmt.Sprintf("failed to parse invitation email template: %v", err)) + } -please visit this link to complete registration and use the code: %s` + inviteUserTemplate = parsed +}