Files
guestguard/internal/api/branding.go
T
Kwaku Danso e5b187c575 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>
2026-05-18 12:04:09 +01:00

247 lines
7.7 KiB
Go

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)
}
}