feat(tier2): event branding + UX polish — Block D

Backend
- Migration 0010 adds event_branding (one row per event; all fields
  nullable so a brand-new event renders with defaults)
- BrandingRepo with COALESCE/NULLIF upsert semantics: nil pointer
  preserves the existing value, "" clears the field to NULL
- internal/uploads package: ImageStore interface + LocalFSStore (dev),
  pure-stdlib decode + re-encode that strips EXIF and rejects anything
  that isn't valid JPEG/PNG. Size cap 2 MB, random 16-byte filenames
- GET /events/{id}/branding (viewer+) returns the row plus the
  AllowedFonts list so the frontend picker stays in sync
- PUT /events/{id}/branding (editor+) validates hex colours, font
  allowlist, and refuses image URLs whose path doesn't start with
  /uploads/ (blocks arbitrary-origin <img> smuggling on guest pages)
- POST /uploads/image (authed) → fresh CDN URL; GET /uploads/{file}
  serves with year-long cache (immutable random names)
- GET /access/{token} now embeds the host's branding so the RSVP page
  can render in their colours/font with their logo + cover
- docker-compose mounts a named volume for uploads
- Custom-domain sub-block deferred to Tier 3 per the plan

Frontend
- BrandingCard.vue: colour pickers, font dropdown, logo + cover upload
  with progressive disclosure, live preview pane that re-renders on
  every keystroke
- RSVP page applies branding via CSS vars at the section root, so
  primary colour theme + font cascade through every child card. Cover
  image renders as a banner above the form; logo lands in the header
- Submit button background switches to var(--brand-primary) when set
- Mounted on the event detail page below the guests block

Plus the small UX fixes from the e2e walkthrough:
- Nav: dropped the top-level "Events" link; the logo doubles as the
  home affordance (→ /dashboard when signed in, → / otherwise). Account
  + Billing + Sign out live under a profile dropdown (avatar with
  initials, opens on click, closes on outside-click / Esc / route nav)
- Renamed "Back to dashboard" → "Back to events" across event detail,
  billing, account, and new-event pages

Tests
- TestBrandingGetReturnsDefaults / TestBrandingPutPersists /
  TestBrandingPutRejectsBadInputs / TestUploadAndServeImage /
  TestUploadRejectsNonImage — all pass
- Domain tests for IsValidHexColor + IsAllowedFont
- Full integration suite green (176s)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Kwaku Danso
2026-05-18 12:04:09 +01:00
parent 9842bd4f45
commit e5b187c575
30 changed files with 2310 additions and 199 deletions
+246
View File
@@ -0,0 +1,246 @@
package api
import (
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"strings"
"github.com/alchemistkay/guestguard/internal/domain"
"github.com/alchemistkay/guestguard/internal/storage"
"github.com/alchemistkay/guestguard/internal/uploads"
)
// brandingHandler owns the per-event customisation row plus image uploads.
// Tier 2 Block D. Reads are viewer+; writes (PUT + image upload) are
// editor+. The role check uses the standard requireRole helper.
type brandingHandler struct {
logger *slog.Logger
events *storage.EventRepo
collabs *storage.CollaboratorRepo
repo *storage.BrandingRepo
store uploads.ImageStore
}
type brandingResponse struct {
*domain.Branding
// AllowedFonts is echoed back on every GET so the frontend's picker
// stays in sync with the server's allowlist without a separate
// /branding/fonts endpoint.
AllowedFonts []string `json:"allowed_fonts"`
}
// GET /events/{id}/branding — viewer+. Missing row is rendered as
// "defaults" (200 with nulls) rather than 404 so the frontend doesn't
// need a special-case loader.
func (h *brandingHandler) get(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
eventID, ok := parseIDParam(w, r, "id")
if !ok {
return
}
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleViewer); !ok {
return
}
b, err := h.repo.Get(r.Context(), eventID)
if err != nil && !errors.Is(err, domain.ErrBrandingNotFound) {
writeError(w, http.StatusInternalServerError, "failed to load branding")
return
}
if b == nil {
b = &domain.Branding{EventID: eventID}
}
writeJSON(w, http.StatusOK, brandingResponse{Branding: b, AllowedFonts: domain.AllowedFonts})
}
type updateBrandingRequest struct {
// Pointer-typed so omitted JSON keys map to nil = "leave unchanged",
// while empty-string maps to "clear the field". The repo's Upsert
// honours this distinction.
PrimaryColor *string `json:"primary_color"`
AccentColor *string `json:"accent_color"`
LogoURL *string `json:"logo_url"`
CoverImageURL *string `json:"cover_image_url"`
FontFamily *string `json:"font_family"`
GreetingMessage *string `json:"greeting_message"`
}
// PUT /events/{id}/branding — editor+. Validates each field server-side
// (the allowlist for fonts, hex shape for colours, our-CDN-only for image
// URLs to prevent the host smuggling an `<img>` from an arbitrary origin
// into the guest-facing page).
func (h *brandingHandler) put(w http.ResponseWriter, r *http.Request) {
hostID, ok := hostFromContext(w, r)
if !ok {
return
}
eventID, ok := parseIDParam(w, r, "id")
if !ok {
return
}
if _, _, ok := requireRole(w, r, h.events, h.collabs, eventID, hostID, domain.RoleEditor); !ok {
return
}
var req updateBrandingRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid json")
return
}
if req.PrimaryColor != nil && !domain.IsValidHexColor(*req.PrimaryColor) {
writeError(w, http.StatusBadRequest, "primary_color: "+domain.ErrInvalidColor.Error())
return
}
if req.AccentColor != nil && !domain.IsValidHexColor(*req.AccentColor) {
writeError(w, http.StatusBadRequest, "accent_color: "+domain.ErrInvalidColor.Error())
return
}
if req.FontFamily != nil && !domain.IsAllowedFont(*req.FontFamily) {
writeError(w, http.StatusBadRequest, domain.ErrUnknownFont.Error())
return
}
if !validImageURL(req.LogoURL) {
writeError(w, http.StatusBadRequest, "logo_url must be a previously-uploaded image URL")
return
}
if !validImageURL(req.CoverImageURL) {
writeError(w, http.StatusBadRequest, "cover_image_url must be a previously-uploaded image URL")
return
}
b, err := h.repo.Upsert(r.Context(), storage.UpsertBrandingParams{
EventID: eventID,
PrimaryColor: req.PrimaryColor,
AccentColor: req.AccentColor,
LogoURL: req.LogoURL,
CoverImageURL: req.CoverImageURL,
FontFamily: req.FontFamily,
GreetingMessage: req.GreetingMessage,
})
if err != nil {
h.logger.Error("upsert branding", "err", err)
writeError(w, http.StatusInternalServerError, "failed to save branding")
return
}
writeJSON(w, http.StatusOK, brandingResponse{Branding: b, AllowedFonts: domain.AllowedFonts})
}
// validImageURL accepts nil / "" / any URL whose path begins with
// /uploads/ — i.e. the host must have run the bytes through our own
// /uploads/image endpoint. This prevents `logo_url=https://evil/x.png`
// from rendering attacker-controlled content on every RSVP page.
func validImageURL(p *string) bool {
if p == nil || *p == "" {
return true
}
u, err := url.Parse(*p)
if err != nil {
return false
}
return strings.HasPrefix(u.Path, "/uploads/")
}
// uploadHandler is split out so the route can sit at /uploads/image without
// being tied to an event id (a single host may upload before deciding
// which of their events to attach the image to).
type uploadHandler struct {
logger *slog.Logger
store uploads.ImageStore
}
type uploadResponse struct {
URL string `json:"url"`
}
// POST /uploads/image — authed. multipart "file" or raw body. Validates
// size + format, re-encodes to strip EXIF, stores under a random name.
// The response URL is what the host pastes into the branding PUT body.
func (h *uploadHandler) post(w http.ResponseWriter, r *http.Request) {
if _, ok := hostFromContext(w, r); !ok {
return
}
// Cap the read so a hostile client can't OOM the API even on a slow
// connection. The +1 lets DecodeAndReencode report "exceeds limit"
// distinctly from "exactly the limit".
r.Body = http.MaxBytesReader(w, r.Body, uploads.MaxUploadBytes+1024)
body, err := readImageUpload(r)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
out, format, err := uploads.DecodeAndReencode(body)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
publicURL, err := h.store.Save(r.Context(), out, format)
if err != nil {
h.logger.Error("save upload", "err", err)
writeError(w, http.StatusInternalServerError, "failed to save upload")
return
}
writeJSON(w, http.StatusCreated, uploadResponse{URL: publicURL})
}
// readImageUpload accepts either a multipart upload (the drag-drop UI's
// shape) or a raw body (curl-friendly).
func readImageUpload(r *http.Request) ([]byte, error) {
if err := r.ParseMultipartForm(uploads.MaxUploadBytes + 1024); err == nil && r.MultipartForm != nil {
files := r.MultipartForm.File["file"]
if len(files) > 0 {
f, err := files[0].Open()
if err != nil {
return nil, err
}
defer f.Close()
return uploads.PeekReader(f)
}
}
defer r.Body.Close()
return uploads.PeekReader(r.Body)
}
// GET /uploads/{filename} — serves the bytes the LocalFSStore wrote. In
// production a CDN would handle this; in dev the API streams them.
func (h *uploadHandler) serve(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("filename")
if name == "" {
writeError(w, http.StatusBadRequest, "missing filename")
return
}
local, ok := h.store.(*uploads.LocalFSStore)
if !ok {
writeError(w, http.StatusNotFound, "upload not found")
return
}
path, err := local.FilePath(name)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid filename")
return
}
f, err := os.Open(path)
if err != nil {
writeError(w, http.StatusNotFound, "upload not found")
return
}
defer f.Close()
if strings.HasSuffix(name, ".png") {
w.Header().Set("Content-Type", "image/png")
} else {
w.Header().Set("Content-Type", "image/jpeg")
}
// Branding images don't change once uploaded (host gets a new URL on
// re-upload), so long cache lifetime is safe.
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
if _, err := io.Copy(w, f); err != nil {
h.logger.Warn("serve upload", "err", err, "name", name)
}
}
+57
View File
@@ -309,6 +309,63 @@ func (h *collaboratorHandler) cancelInvite(w http.ResponseWriter, r *http.Reques
w.WriteHeader(http.StatusNoContent)
}
// --- "your pending invites" (self-service inbox) ---
// GET /me/invites — authed. Lists invites addressed to the caller's email
// so the dashboard can show a one-click Accept banner without requiring
// the user to re-click the email link. Crucial for the signup → verify-
// email → login flow where the email click opens a new tab and the
// original invite tab is forgotten.
func (h *collaboratorHandler) myInvites(w http.ResponseWriter, r *http.Request) {
userID, ok := hostFromContext(w, r)
if !ok {
return
}
user, err := h.users.GetByID(r.Context(), userID)
if err != nil || user == nil {
writeError(w, http.StatusUnauthorized, "unauthenticated")
return
}
pending, err := h.invites.ListPendingForEmail(r.Context(), user.Email)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list invites")
return
}
writeJSON(w, http.StatusOK, map[string]any{"invites": pending})
}
// POST /me/invites/{event_id}/accept — authed. Accepts the latest pending
// invite for (caller.email, event_id). Same effect as POST /invites/{token}/
// accept but doesn't require the raw token; the caller's verified email is
// the identity signal instead.
func (h *collaboratorHandler) acceptForEvent(w http.ResponseWriter, r *http.Request) {
userID, ok := hostFromContext(w, r)
if !ok {
return
}
user, err := h.users.GetByID(r.Context(), userID)
if err != nil || user == nil {
writeError(w, http.StatusUnauthorized, "unauthenticated")
return
}
eventID, ok := parseIDParam(w, r, "event_id")
if !ok {
return
}
role, err := h.collabs.AcceptByEventAndEmail(r.Context(), eventID, user.Email, userID)
if err != nil {
switch {
case errors.Is(err, domain.ErrInviteNotFound):
writeError(w, http.StatusNotFound, "no pending invitation for this event")
default:
h.logger.Error("accept by email", "err", err)
writeError(w, http.StatusInternalServerError, "failed to accept invitation")
}
return
}
writeJSON(w, http.StatusOK, acceptResponse{EventID: eventID, Role: role})
}
// --- public invite-accept flow ---
type inviteSummary struct {
+19 -6
View File
@@ -125,23 +125,36 @@ func (h *eventHandler) list(w http.ResponseWriter, r *http.Request) {
offset := atoiOr(q.Get("offset"), 0)
// Block C: the dashboard shows every event the user has any role on,
// not just events they own. The collaborators repo gives us the id set;
// the events repo paginates the merged list.
collabIDs, err := h.collabs.ListEventIDsForUser(r.Context(), hostID)
// not just events they own. Pull the role map up front so we can
// annotate each card with `your_role` — the frontend uses that to
// split "your events" from "shared with you" without a follow-up call.
roles, err := h.collabs.RolesForUser(r.Context(), hostID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to resolve memberships")
return
}
collabIDs := make([]uuid.UUID, 0, len(roles))
for id := range roles {
collabIDs = append(collabIDs, id)
}
events, err := h.repo.ListForUser(r.Context(), hostID, collabIDs, limit, offset)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list events")
return
}
if events == nil {
events = []*domain.Event{}
views := make([]eventView, 0, len(events))
for _, ev := range events {
role := roles[ev.ID]
if role == "" && ev.HostID == hostID {
// Defensive: legacy events created before Block C's seed-on-
// create may not have a collaborator row. Fall back to the
// host_id check so they still show as owned.
role = domain.RoleOwner
}
views = append(views, eventView{Event: ev, YourRole: role})
}
writeJSON(w, http.StatusOK, map[string]any{
"events": events,
"events": views,
"limit": limit,
"offset": offset,
})
+55
View File
@@ -12,6 +12,7 @@ import (
"github.com/alchemistkay/guestguard/internal/notification"
"github.com/alchemistkay/guestguard/internal/ratelimit"
"github.com/alchemistkay/guestguard/internal/storage"
"github.com/alchemistkay/guestguard/internal/uploads"
)
type Server struct {
@@ -38,6 +39,8 @@ type Server struct {
privacy *privacyHandler
collabs *collaboratorHandler
analytics *analyticsHandler
branding *brandingHandler
uploads *uploadHandler
}
type ServerDeps struct {
@@ -77,6 +80,13 @@ type ServerDeps struct {
// system still boots and runs, all users sit on the free tier with
// its limits enforced; /billing/* returns 503.
StripeClient *billing.Client
// Uploads (Tier 2 Block D). UploadsDir is where the LocalFSStore
// writes images; UploadsPublicURL is the base prefix the API will
// serve them under. Both empty means uploads are disabled (POST
// /uploads/image returns 503).
UploadsDir string
UploadsPublicURL string
}
func NewServer(deps ServerDeps) (*Server, error) {
@@ -89,6 +99,18 @@ func NewServer(deps ServerDeps) (*Server, error) {
collabRepo := storage.NewCollaboratorRepo(deps.DB)
inviteRepo := storage.NewInviteRepo(deps.DB)
analyticsRepo := storage.NewAnalyticsRepo(deps.DB)
brandingRepo := storage.NewBrandingRepo(deps.DB)
// Branding image store. Empty UploadsDir leaves it nil and the upload
// + serve handlers report 503, so the rest of the service keeps
// working in stripped-down environments.
var imageStore uploads.ImageStore
if deps.UploadsDir != "" {
imageStore = &uploads.LocalFSStore{
Dir: deps.UploadsDir,
PublicBase: deps.UploadsPublicURL,
}
}
verifRepo := storage.NewEmailVerificationRepo(deps.DB)
resetRepo := storage.NewPasswordResetRepo(deps.DB)
refreshRepo := storage.NewRefreshTokenRepo(deps.DB)
@@ -168,6 +190,7 @@ func NewServer(deps ServerDeps) (*Server, error) {
accessLogs: accessRepo,
rsvps: rsvpRepo,
collabs: collabRepo,
branding: brandingRepo,
gen: auth.NewGenerator(),
ttl: deps.TokenTTL,
pub: deps.AccessPublisher,
@@ -225,6 +248,17 @@ func NewServer(deps ServerDeps) (*Server, error) {
repo: analyticsRepo,
redis: deps.Redis,
},
branding: &brandingHandler{
logger: deps.Logger,
events: eventRepo,
collabs: collabRepo,
repo: brandingRepo,
store: imageStore,
},
uploads: &uploadHandler{
logger: deps.Logger,
store: imageStore,
},
collabs: &collaboratorHandler{
logger: deps.Logger,
events: eventRepo,
@@ -322,6 +356,19 @@ func (s *Server) Handler() http.Handler {
mux.Handle("GET /events/{id}/analytics/export.csv",
authed(http.HandlerFunc(s.analytics.exportCSV)))
// Block D — event branding. Reads are viewer+; PUT is editor+. The
// upload endpoint is gated by auth only (any signed-in user can mint
// an image URL; the URL is no use without an event they can edit
// branding on).
mux.Handle("GET /events/{id}/branding", authed(http.HandlerFunc(s.branding.get)))
mux.Handle("PUT /events/{id}/branding", authed(http.HandlerFunc(s.branding.put)))
mux.Handle("POST /uploads/image",
authed(rl("uploads_image", 30, time.Hour, userIDKey, http.HandlerFunc(s.uploads.post))))
// Public read — the guest RSVP page fetches the host's logo + cover
// without auth. Heavy cache; no rate limiter (one-time fetch per
// guest, behind the CDN in prod anyway).
mux.HandleFunc("GET /uploads/{filename}", s.uploads.serve)
// Block C — collaborators (multi-host). All under /events/{id}/collaborators.
// requireRole inside each handler enforces the right minimum role.
mux.Handle("GET /events/{id}/collaborators",
@@ -342,6 +389,14 @@ func (s *Server) Handler() http.Handler {
mux.Handle("POST /invites/{token}/accept",
authed(http.HandlerFunc(s.collabs.acceptInvite)))
// Self-service invite inbox: bypasses the email-token round-trip so a
// user who lost the invite tab after email verification can still
// accept from their dashboard.
mux.Handle("GET /me/invites",
authed(http.HandlerFunc(s.collabs.myInvites)))
mux.Handle("POST /me/invites/{event_id}/accept",
authed(http.HandlerFunc(s.collabs.acceptForEvent)))
mux.Handle("POST /events/{id}/guests/{guest_id}/tokens",
authed(rl("tokens_issue", 500, 24*time.Hour, userIDKey, http.HandlerFunc(s.tokens.issue))))
mux.Handle("POST /events/{id}/guests/{guest_id}/tokens/rotate",
+21
View File
@@ -35,6 +35,7 @@ type tokenHandler struct {
accessLogs *storage.AccessLogRepo
rsvps *storage.RSVPRepo
collabs *storage.CollaboratorRepo
branding *storage.BrandingRepo
gen *auth.Generator
ttl time.Duration
pub accessPublisher
@@ -416,6 +417,10 @@ type accessResponse struct {
// path so the frontend renders four ready-to-click buttons after a
// successful RSVP. (Tier 2 Block B.)
Calendar calendar.ProviderLinks `json:"calendar"`
// Branding lets the RSVP page render in the host's colour scheme /
// logo / cover image. Nil when the host hasn't customised yet — the
// frontend falls back to defaults. (Tier 2 Block D.)
Branding *domain.Branding `json:"branding,omitempty"`
}
// GET /access/{token} — validate token, log the access attempt, publish to NATS.
@@ -482,6 +487,21 @@ func (h *tokenHandler) access(w http.ResponseWriter, r *http.Request) {
OccurredAt: time.Now().UTC(),
})
var brandingPayload *domain.Branding
if h.branding != nil {
// Same best-effort treatment as the RSVP lookup below — missing
// branding row is the common case, not a failure.
br, err := h.branding.Get(r.Context(), event.ID)
switch {
case err == nil:
brandingPayload = br
case errors.Is(err, domain.ErrBrandingNotFound):
// expected when the host hasn't customised yet
default:
h.logger.Warn("load branding for access", "err", err, "event_id", event.ID)
}
}
var existingRSVP *domain.RSVP
if h.rsvps != nil {
// Best-effort: a missing RSVP just means the guest hasn't submitted
@@ -505,6 +525,7 @@ func (h *tokenHandler) access(w http.ResponseWriter, r *http.Request) {
AccessLog: accessLogID,
RSVP: existingRSVP,
Calendar: h.calendarLinks(event, raw),
Branding: brandingPayload,
})
}