2022-07-06 23:19:05 +02:00
|
|
|
package mails
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/mail"
|
|
|
|
|
|
|
|
"github.com/pocketbase/pocketbase/core"
|
|
|
|
"github.com/pocketbase/pocketbase/mails/templates"
|
|
|
|
"github.com/pocketbase/pocketbase/models"
|
|
|
|
"github.com/pocketbase/pocketbase/tokens"
|
2022-11-21 14:53:05 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tools/mailer"
|
2022-08-14 18:30:45 +02:00
|
|
|
"github.com/pocketbase/pocketbase/tools/rest"
|
2022-07-06 23:19:05 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// SendAdminPasswordReset sends a password reset request email to the specified admin.
|
|
|
|
func SendAdminPasswordReset(app core.App, admin *models.Admin) error {
|
|
|
|
token, tokenErr := tokens.NewAdminResetPasswordToken(app, admin)
|
|
|
|
if tokenErr != nil {
|
|
|
|
return tokenErr
|
|
|
|
}
|
|
|
|
|
2022-08-14 18:30:45 +02:00
|
|
|
actionUrl, urlErr := rest.NormalizeUrl(fmt.Sprintf(
|
2022-08-12 16:08:36 +02:00
|
|
|
"%s/_/#/confirm-password-reset/%s",
|
2022-08-14 18:30:45 +02:00
|
|
|
app.Settings().Meta.AppUrl,
|
2022-07-06 23:19:05 +02:00
|
|
|
token,
|
|
|
|
))
|
|
|
|
if urlErr != nil {
|
|
|
|
return urlErr
|
|
|
|
}
|
|
|
|
|
|
|
|
params := struct {
|
|
|
|
AppName string
|
|
|
|
AppUrl string
|
|
|
|
Admin *models.Admin
|
|
|
|
Token string
|
|
|
|
ActionUrl string
|
|
|
|
}{
|
|
|
|
AppName: app.Settings().Meta.AppName,
|
|
|
|
AppUrl: app.Settings().Meta.AppUrl,
|
|
|
|
Admin: admin,
|
|
|
|
Token: token,
|
|
|
|
ActionUrl: actionUrl,
|
|
|
|
}
|
|
|
|
|
|
|
|
mailClient := app.NewMailClient()
|
|
|
|
|
2022-11-21 14:53:05 +02:00
|
|
|
// resolve body template
|
|
|
|
body, renderErr := resolveTemplateContent(params, templates.Layout, templates.AdminPasswordResetBody)
|
|
|
|
if renderErr != nil {
|
|
|
|
return renderErr
|
|
|
|
}
|
|
|
|
|
|
|
|
message := &mailer.Message{
|
|
|
|
From: mail.Address{
|
|
|
|
Name: app.Settings().Meta.SenderName,
|
|
|
|
Address: app.Settings().Meta.SenderAddress,
|
|
|
|
},
|
|
|
|
To: mail.Address{Address: admin.Email},
|
|
|
|
Subject: "Reset admin password",
|
|
|
|
HTML: body,
|
|
|
|
}
|
|
|
|
|
2022-07-06 23:19:05 +02:00
|
|
|
event := &core.MailerAdminEvent{
|
|
|
|
MailClient: mailClient,
|
2022-11-21 14:53:05 +02:00
|
|
|
Message: message,
|
2022-07-06 23:19:05 +02:00
|
|
|
Admin: admin,
|
|
|
|
Meta: map[string]any{"token": token},
|
|
|
|
}
|
|
|
|
|
|
|
|
sendErr := app.OnMailerBeforeAdminResetPasswordSend().Trigger(event, func(e *core.MailerAdminEvent) error {
|
2022-11-21 14:53:05 +02:00
|
|
|
return e.MailClient.Send(e.Message)
|
2022-07-06 23:19:05 +02:00
|
|
|
})
|
|
|
|
|
|
|
|
if sendErr == nil {
|
|
|
|
app.OnMailerAfterAdminResetPasswordSend().Trigger(event)
|
|
|
|
}
|
|
|
|
|
|
|
|
return sendErr
|
|
|
|
}
|