Files
lincodex/backend/internal/usecase/notification/service_mail.go
T

155 lines
6.4 KiB
Go

package notification
import (
"context"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification/mailtemplate"
)
// TokenMailRequest asks for one service mail that carries a one-time token.
//
// The token record must be stored already, in the same transaction, because
// the delivery is bound to it. RawToken is the secret that goes into the link
// of the message; it exists only in memory and is stored nowhere except in
// the rendered body, which the delivery keeps until the mail is sent or
// cancelled.
type TokenMailRequest struct {
// Recipient is the address of the account now; the delivery keeps it as
// the address to send to, and the worker compares it with the account
// again before it sends.
Recipient domain.EmailAddress
Token domain.EmailToken
RawToken domain.SecretToken
// Lifetime is the validity of the token that the message states, in
// whole hours.
Lifetime domain.Hours
// Code is the six-digit code of an email verification message, and
// CodeLifetime its validity as the message states it. Both are required
// for email verification and unused by the other kinds.
Code domain.VerificationCode
CodeLifetime time.Duration
}
// ServiceMailer stores service mail of the account flows (email verification
// and password reset) as deliveries, in the transaction that issues the
// token. No event or request row carries the token: the rendered body goes
// straight into the delivery, which the account's deletion removes by
// cascade.
//
// Service mail needs no consent of any purpose. It is part of the account
// flow, not a product notification, so nothing here reads the consent
// ledger; the worker checks the token and the account instead (see
// ServiceMailSender).
type ServiceMailer struct {
renderer ServiceMailRenderer
account domain.MailProviderAccount
clock func() time.Time
}
// NewServiceMailer pins new deliveries to account, the transport and account
// configured when the mail is requested. clock is the application clock for
// the creation time.
func NewServiceMailer(renderer ServiceMailRenderer, account domain.MailProviderAccount, clock func() time.Time) *ServiceMailer {
return &ServiceMailer{renderer: renderer, account: account, clock: clock}
}
// EnqueueVerification stores the email verification message for request.Token
// through unit, which must be the caller's transaction, and returns the
// delivery ID. The delivery ID is the token ID, so repeating the call for
// the same token stores nothing new. The mail is sent only if the
// transaction commits and the token is still current when the worker gets
// to it.
func (mailer *ServiceMailer) EnqueueVerification(ctx context.Context, unit outbound.UnitOfWork, request TokenMailRequest) (uuid.UUID, error) {
const location = "ServiceMailer.EnqueueVerification"
if err := checkTokenMailRequest(location, request, domain.EmailTokenPurposeEmailVerification); err != nil {
return uuid.Nil, err
}
if request.Code.IsZero() {
return uuid.Nil, fmt.Errorf("%s - verification code must be set: %w", location, domain.ErrInvalidEmailToken)
}
content, err := mailer.renderer.RenderVerification(mailtemplate.VerificationData{
Token: request.RawToken,
TokenLifetime: request.Lifetime,
Code: request.Code,
CodeLifetime: request.CodeLifetime,
})
if err != nil {
return uuid.Nil, fmt.Errorf("%s - render message: %w", location, err)
}
return mailer.store(ctx, unit, location, request, content)
}
// EnqueuePasswordReset stores the password reset message for request.Token;
// see EnqueueVerification.
func (mailer *ServiceMailer) EnqueuePasswordReset(ctx context.Context, unit outbound.UnitOfWork, request TokenMailRequest) (uuid.UUID, error) {
const location = "ServiceMailer.EnqueuePasswordReset"
if err := checkTokenMailRequest(location, request, domain.EmailTokenPurposePasswordReset); err != nil {
return uuid.Nil, err
}
content, err := mailer.renderer.RenderPasswordReset(mailtemplate.PasswordResetData{Token: request.RawToken, TokenLifetime: request.Lifetime})
if err != nil {
return uuid.Nil, fmt.Errorf("%s - render message: %w", location, err)
}
return mailer.store(ctx, unit, location, request, content)
}
func (mailer *ServiceMailer) store(
ctx context.Context,
unit outbound.UnitOfWork,
location string,
request TokenMailRequest,
content domain.MailContent,
) (uuid.UUID, error) {
delivery, err := domain.NewDelivery(domain.NewDeliveryInput{
ID: request.Token.ID,
RecipientUserID: request.Token.UserID,
Recipient: request.Recipient,
Content: content,
ProviderAccount: mailer.account,
EmailTokenID: request.Token.ID,
CreatedAt: mailer.clock(),
})
if err != nil {
return uuid.Nil, fmt.Errorf("%s - build delivery: %w", location, err)
}
created, err := unit.Deliveries().Create(ctx, delivery)
if err != nil {
return uuid.Nil, fmt.Errorf("%s - store delivery: %w", location, err)
}
if !created {
// The same token was enqueued before; the stored message stays as it
// is, because a retry under the same idempotency key must repeat the
// same body.
existing, err := unit.Deliveries().Get(ctx, request.Token.ID)
if err != nil {
return uuid.Nil, fmt.Errorf("%s - read existing delivery: %w", location, err)
}
if existing.RecipientUserID() != request.Token.UserID || existing.Kind() != content.Kind() {
return uuid.Nil, fmt.Errorf("%s - a delivery for another recipient or kind has the token ID: %w", location, domain.ErrInvalidDelivery)
}
}
return request.Token.ID, nil
}
// checkTokenMailRequest refuses a request whose token is not of the purpose
// the message needs or has no ID, before anything is rendered.
func checkTokenMailRequest(location string, request TokenMailRequest, purpose domain.EmailTokenPurpose) error {
switch {
case request.Token.ID == uuid.Nil || request.Token.UserID == uuid.Nil:
return fmt.Errorf("%s - token must be built by domain.NewEmailToken: %w", location, domain.ErrInvalidEmailToken)
case request.Token.Purpose != purpose:
return fmt.Errorf("%s - token purpose does not match the message: %w", location, domain.ErrInvalidEmailToken)
case request.RawToken.IsZero():
return fmt.Errorf("%s - raw token must be set: %w", location, domain.ErrInvalidEmailToken)
case request.Recipient.IsZero():
return fmt.Errorf("%s - recipient must be set: %w", location, domain.ErrInvalidDelivery)
}
return nil
}