more cart
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
package customerauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/mail"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mailersend/mailersend-go"
|
||||
)
|
||||
|
||||
// MailerSendNotifier delivers transactional auth messages (email verification
|
||||
// and password reset) through the MailerSend API. It implements the Notifier
|
||||
// interface and is a drop-in replacement for LogNotifier in production.
|
||||
type MailerSendNotifier struct {
|
||||
client *mailersend.Mailersend
|
||||
from mail.Address
|
||||
}
|
||||
|
||||
// NewMailerSendNotifier creates a new MailerSend-backed notifier. The apiKey
|
||||
// is the MailerSend API token (MAILERSEND_API_KEY env var). The from address
|
||||
// must include at least an email; the name portion is optional.
|
||||
func NewMailerSendNotifier(apiKey string, from mail.Address) (*MailerSendNotifier, error) {
|
||||
if strings.TrimSpace(apiKey) == "" {
|
||||
return nil, fmt.Errorf("mailersend notifier: missing API key")
|
||||
}
|
||||
if strings.TrimSpace(from.Address) == "" {
|
||||
return nil, fmt.Errorf("mailersend notifier: missing from address")
|
||||
}
|
||||
return &MailerSendNotifier{
|
||||
client: mailersend.NewMailersend(apiKey),
|
||||
from: from,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SendEmailVerification sends the verification link to the customer's email
|
||||
// address. Errors are logged but not returned (best-effort delivery matches the
|
||||
// signature of the Notifier interface).
|
||||
func (n *MailerSendNotifier) SendEmailVerification(email, link string) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
if err := n.send(ctx, email,
|
||||
"Verify your email address",
|
||||
fmt.Sprintf("Click the link to verify your email address:\n\n%s", link),
|
||||
fmt.Sprintf(`<p>Click <a href="%s">here</a> to verify your email address.</p>`, link),
|
||||
); err != nil {
|
||||
log.Printf("customerauth: send verification to %s: %v", email, err)
|
||||
}
|
||||
}
|
||||
|
||||
// SendPasswordReset sends the password-reset link to the customer's email.
|
||||
// Errors are logged but not returned.
|
||||
func (n *MailerSendNotifier) SendPasswordReset(email, link string) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
if err := n.send(ctx, email,
|
||||
"Reset your password",
|
||||
fmt.Sprintf("Click the link to reset your password:\n\n%s\n\nIf you didn't request this, ignore this email.", link),
|
||||
fmt.Sprintf(`<p>Click <a href="%s">here</a> to reset your password.</p><p>If you didn't request this, ignore this email.</p>`, link),
|
||||
); err != nil {
|
||||
log.Printf("customerauth: send password reset to %s: %v", email, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (n *MailerSendNotifier) send(ctx context.Context, to, subject, textBody, htmlBody string) error {
|
||||
message := n.client.Email.NewMessage()
|
||||
message.SetFrom(mailersend.From{
|
||||
Name: n.from.Name,
|
||||
Email: n.from.Address,
|
||||
})
|
||||
message.SetRecipients([]mailersend.Recipient{
|
||||
{Email: to},
|
||||
})
|
||||
message.SetSubject(subject)
|
||||
message.SetText(textBody)
|
||||
if htmlBody != "" {
|
||||
message.SetHTML(htmlBody)
|
||||
}
|
||||
_, err := n.client.Email.Send(ctx, message)
|
||||
if err != nil {
|
||||
return fmt.Errorf("mailersend: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -19,6 +19,7 @@ type CustomerServer struct {
|
||||
applier ProfileApplier
|
||||
deleter CredentialDeleter
|
||||
auditLogPath string
|
||||
emailIndex *profile.ProfileEmailIndex // optional, maintained by mutations
|
||||
}
|
||||
|
||||
// NewCustomerServer builds a UCP REST adapter over a profile grain pool.
|
||||
@@ -30,6 +31,33 @@ func NewCustomerServer(applier ProfileApplier, auditLogPath string, deleter ...C
|
||||
return &CustomerServer{applier: applier, deleter: del, auditLogPath: auditLogPath}
|
||||
}
|
||||
|
||||
// SetEmailIndex attaches a ProfileEmailIndex that is updated by every
|
||||
// customer mutation (create, update, delete).
|
||||
func (s *CustomerServer) SetEmailIndex(ix *profile.ProfileEmailIndex) {
|
||||
s.emailIndex = ix
|
||||
}
|
||||
|
||||
// indexProfileAfterMutation reads the grain and updates the email index.
|
||||
func (s *CustomerServer) indexProfileAfterMutation(ctx context.Context, id uint64) {
|
||||
if s.emailIndex == nil {
|
||||
return
|
||||
}
|
||||
g, err := s.applier.Get(ctx, id)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
prefs := g.EmailPreferences
|
||||
// Copy so the index holds its own snapshot (the grain is pooled).
|
||||
if prefs != nil {
|
||||
cp := &profile.EmailPreferences{
|
||||
OrderEmails: prefs.OrderEmails,
|
||||
MarketingEmails: prefs.MarketingEmails,
|
||||
}
|
||||
prefs = cp
|
||||
}
|
||||
s.emailIndex.Set(id, g.Email, prefs)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// UCP Customer endpoints
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -61,6 +89,11 @@ func (s *CustomerServer) handleCreateCustomer(w http.ResponseWriter, r *http.Req
|
||||
AvatarUrl: req.AvatarUrl,
|
||||
}
|
||||
|
||||
if req.EmailPreferences != nil {
|
||||
msg.OrderEmails = req.EmailPreferences.OrderEmails
|
||||
msg.MarketingEmails = req.EmailPreferences.MarketingEmails
|
||||
}
|
||||
|
||||
if _, err := s.applier.Apply(r.Context(), id, msg); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to create customer: "+err.Error())
|
||||
return
|
||||
@@ -72,6 +105,8 @@ func (s *CustomerServer) handleCreateCustomer(w http.ResponseWriter, r *http.Req
|
||||
return
|
||||
}
|
||||
|
||||
s.indexProfileAfterMutation(r.Context(), id)
|
||||
|
||||
writeJSON(w, http.StatusCreated, customerGrainToResponse(rawId.String(), g))
|
||||
}
|
||||
|
||||
@@ -132,6 +167,11 @@ func (s *CustomerServer) handleUpdateCustomer(w http.ResponseWriter, r *http.Req
|
||||
AvatarUrl: req.AvatarUrl,
|
||||
}
|
||||
|
||||
if req.EmailPreferences != nil {
|
||||
msg.OrderEmails = req.EmailPreferences.OrderEmails
|
||||
msg.MarketingEmails = req.EmailPreferences.MarketingEmails
|
||||
}
|
||||
|
||||
if _, err := s.applier.Apply(r.Context(), id, msg); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to update customer: "+err.Error())
|
||||
return
|
||||
@@ -143,9 +183,36 @@ func (s *CustomerServer) handleUpdateCustomer(w http.ResponseWriter, r *http.Req
|
||||
return
|
||||
}
|
||||
|
||||
s.indexProfileAfterMutation(r.Context(), id)
|
||||
|
||||
writeJSON(w, http.StatusOK, customerGrainToResponse(r.PathValue("id"), g))
|
||||
}
|
||||
|
||||
// handleGetCustomerByEmail handles GET /customers/by-email/{email} — looks up
|
||||
// the customer profile from the email index and returns the customer response.
|
||||
// Returns 404 when the email is not found.
|
||||
func (s *CustomerServer) handleGetCustomerByEmail(w http.ResponseWriter, r *http.Request) {
|
||||
email := r.PathValue("email")
|
||||
if email == "" || s.emailIndex == nil {
|
||||
writeError(w, http.StatusNotFound, "customer not found")
|
||||
return
|
||||
}
|
||||
|
||||
entry, ok := s.emailIndex.Lookup(email)
|
||||
if !ok {
|
||||
writeError(w, http.StatusNotFound, "customer not found")
|
||||
return
|
||||
}
|
||||
|
||||
g, err := s.applier.Get(r.Context(), entry.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "customer not found")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, customerGrainToResponse(profile.ProfileId(entry.ID).String(), g))
|
||||
}
|
||||
|
||||
// handleAddAddress handles POST /customers/{id}/addresses.
|
||||
func (s *CustomerServer) handleAddAddress(w http.ResponseWriter, r *http.Request) {
|
||||
id, ok := parseCustomerID(r)
|
||||
@@ -477,5 +544,13 @@ func customerGrainToResponse(id string, g *profile.ProfileGrain) CustomerRespons
|
||||
})
|
||||
}
|
||||
|
||||
if g.EmailPreferences != nil {
|
||||
prefs := &EmailPreferencesResponse{
|
||||
OrderEmails: g.EmailPreferences.OrderEmails,
|
||||
MarketingEmails: g.EmailPreferences.MarketingEmails,
|
||||
}
|
||||
resp.EmailPreferences = prefs
|
||||
}
|
||||
|
||||
return resp
|
||||
}
|
||||
|
||||
@@ -519,7 +519,7 @@ func TestDeleteCustomer(t *testing.T) {
|
||||
id := testProfileID(t, applier)
|
||||
deleter := &testCredentialDeleter{}
|
||||
auditPath := filepath.Join(t.TempDir(), "audit.log")
|
||||
handler := CustomerHandler(applier, auditPath, deleter)
|
||||
handler := CustomerHandler(applier, auditPath, WithCredentialDeleter(deleter))
|
||||
|
||||
// Set up some profile data
|
||||
pid, _ := profile.ParseProfileId(id)
|
||||
|
||||
+30
-3
@@ -1,6 +1,10 @@
|
||||
package ucp
|
||||
|
||||
import "net/http"
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.k6n.net/mats/go-cart-actor/pkg/profile"
|
||||
)
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Order HTTP handler mounting
|
||||
@@ -86,11 +90,33 @@ func CheckoutHandler(applier CheckoutApplier, orderSvc ...OrderApplier) http.Han
|
||||
// To sign responses with RFC 9421 HTTP Message Signatures, wrap with WithSigning:
|
||||
//
|
||||
// mux.Handle("/ucp/v1/customers", ucp.WithSigning(ucp.CustomerHandler(pool), signer))
|
||||
func CustomerHandler(applier ProfileApplier, auditLogPath string, deleter ...CredentialDeleter) http.Handler {
|
||||
s := NewCustomerServer(applier, auditLogPath, deleter...)
|
||||
// CustomerHandlerOption configures a CustomerHandler with optional dependencies.
|
||||
type CustomerHandlerOption func(s *CustomerServer)
|
||||
|
||||
// WithEmailIndex attaches a ProfileEmailIndex that the customer handler
|
||||
// updates on every mutation and uses for the GET /by-email/{email} route.
|
||||
func WithEmailIndex(ix *profile.ProfileEmailIndex) CustomerHandlerOption {
|
||||
return func(s *CustomerServer) {
|
||||
s.SetEmailIndex(ix)
|
||||
}
|
||||
}
|
||||
|
||||
// WithCredentialDeleter attaches a credential deleter for GDPR erasure.
|
||||
func WithCredentialDeleter(deleter CredentialDeleter) CustomerHandlerOption {
|
||||
return func(s *CustomerServer) {
|
||||
s.deleter = deleter
|
||||
}
|
||||
}
|
||||
|
||||
func CustomerHandler(applier ProfileApplier, auditLogPath string, opts ...CustomerHandlerOption) http.Handler {
|
||||
s := NewCustomerServer(applier, auditLogPath)
|
||||
for _, opt := range opts {
|
||||
opt(s)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /", s.handleCreateCustomer)
|
||||
mux.HandleFunc("GET /{id}", s.handleGetCustomer)
|
||||
mux.HandleFunc("GET /by-email/{email}", s.handleGetCustomerByEmail)
|
||||
mux.HandleFunc("PUT /{id}", s.handleUpdateCustomer)
|
||||
mux.HandleFunc("DELETE /{id}", s.handleDeleteCustomer)
|
||||
mux.HandleFunc("POST /{id}/addresses", s.handleAddAddress)
|
||||
@@ -154,6 +180,7 @@ func Handler(cartApplier CartApplier, opts Options) http.Handler {
|
||||
customerSrv := NewCustomerServer(opts.ProfileApplier, opts.ProfileAuditLog, opts.CredentialDeleter)
|
||||
mux.HandleFunc("POST /customers", customerSrv.handleCreateCustomer)
|
||||
mux.HandleFunc("GET /customers/{id}", customerSrv.handleGetCustomer)
|
||||
mux.HandleFunc("GET /customers/by-email/{email}", customerSrv.handleGetCustomerByEmail)
|
||||
mux.HandleFunc("PUT /customers/{id}", customerSrv.handleUpdateCustomer)
|
||||
mux.HandleFunc("DELETE /customers/{id}", customerSrv.handleDeleteCustomer)
|
||||
mux.HandleFunc("POST /customers/{id}/addresses", customerSrv.handleAddAddress)
|
||||
|
||||
+28
-14
@@ -335,16 +335,23 @@ type OrderLineEntry struct {
|
||||
// UCP Customer types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// EmailPreferencesResponse is the UCP wire format for email preference toggles.
|
||||
type EmailPreferencesResponse struct {
|
||||
OrderEmails *bool `json:"orderEmails,omitempty"`
|
||||
MarketingEmails *bool `json:"marketingEmails,omitempty"`
|
||||
}
|
||||
|
||||
// CustomerResponse is the UCP customer profile response body.
|
||||
type CustomerResponse struct {
|
||||
Id string `json:"id"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Language string `json:"language,omitempty"`
|
||||
Currency string `json:"currency,omitempty"`
|
||||
AvatarUrl string `json:"avatarUrl,omitempty"`
|
||||
Addresses []AddressResponse `json:"addresses,omitempty"`
|
||||
Id string `json:"id"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Phone string `json:"phone,omitempty"`
|
||||
Language string `json:"language,omitempty"`
|
||||
Currency string `json:"currency,omitempty"`
|
||||
AvatarUrl string `json:"avatarUrl,omitempty"`
|
||||
Addresses []AddressResponse `json:"addresses,omitempty"`
|
||||
EmailPreferences *EmailPreferencesResponse `json:"emailPreferences,omitempty"`
|
||||
}
|
||||
|
||||
// AddressResponse is the UCP wire format for an address.
|
||||
@@ -363,14 +370,21 @@ type AddressResponse struct {
|
||||
IsDefaultBilling bool `json:"isDefaultBilling"`
|
||||
}
|
||||
|
||||
// EmailPreferencesInput is the body for updating a customer's email preferences.
|
||||
type EmailPreferencesInput struct {
|
||||
OrderEmails *bool `json:"orderEmails,omitempty"`
|
||||
MarketingEmails *bool `json:"marketingEmails,omitempty"`
|
||||
}
|
||||
|
||||
// CustomerUpdateRequest is the body for PUT /customers/{id}.
|
||||
type CustomerUpdateRequest struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
Email *string `json:"email,omitempty"`
|
||||
Phone *string `json:"phone,omitempty"`
|
||||
Language *string `json:"language,omitempty"`
|
||||
Currency *string `json:"currency,omitempty"`
|
||||
AvatarUrl *string `json:"avatarUrl,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
Email *string `json:"email,omitempty"`
|
||||
Phone *string `json:"phone,omitempty"`
|
||||
Language *string `json:"language,omitempty"`
|
||||
Currency *string `json:"currency,omitempty"`
|
||||
AvatarUrl *string `json:"avatarUrl,omitempty"`
|
||||
EmailPreferences *EmailPreferencesInput `json:"emailPreferences,omitempty"`
|
||||
}
|
||||
|
||||
// AddAddressRequest is the body for POST /customers/{id}/addresses.
|
||||
|
||||
Reference in New Issue
Block a user