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