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
+2
View File
@@ -212,6 +212,8 @@ func run() error {
SuppressionRepo: suppressions,
UnsubscribeSigner: unsubSigner,
StripeClient: stripeClient,
UploadsDir: cfg.UploadsDir,
UploadsPublicURL: cfg.UploadsPublicURL,
})
if err != nil {
return err
+8
View File
@@ -86,6 +86,13 @@ services:
GG_STRIPE_WEBHOOK_SECRET: ${GG_STRIPE_WEBHOOK_SECRET:-}
GG_STRIPE_PRICE_PRO: ${GG_STRIPE_PRICE_PRO:-}
GG_STRIPE_PRICE_BUSINESS: ${GG_STRIPE_PRICE_BUSINESS:-}
# Tier 2 Block D — branding image uploads. Stored on the named
# volume below so they survive container restarts; production
# would back this with S3 + CDN instead.
GG_UPLOADS_DIR: /var/lib/guestguard/uploads
GG_UPLOADS_PUBLIC_URL: http://localhost:8080/uploads
volumes:
- uploads-data:/var/lib/guestguard/uploads
ports:
- "8080:8080"
depends_on:
@@ -154,3 +161,4 @@ services:
volumes:
postgres-data:
nats-data:
uploads-data:
+127 -7
View File
@@ -6,7 +6,46 @@ const route = useRoute()
// page. Inside the app it just clutters the chrome.
const showGithub = computed(() => route.path === '/')
// Profile dropdown state. Closed by default; opens on click, closes on
// outside click / Escape / route change. Industry-standard pattern: the
// account-scoped actions (Account, Billing, Sign out) tuck under an avatar
// affordance instead of crowding the top-level nav.
const profileOpen = ref(false)
const profileRef = ref<HTMLElement | null>(null)
function initials(name?: string | null) {
if (!name) return '·'
return name
.trim()
.split(/\s+/)
.slice(0, 2)
.map((p) => p[0]?.toUpperCase() || '')
.join('') || '·'
}
function onDocClick(e: MouseEvent) {
if (!profileOpen.value) return
const root = profileRef.value
if (root && !root.contains(e.target as Node)) profileOpen.value = false
}
function onKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') profileOpen.value = false
}
if (import.meta.client) {
onMounted(() => {
window.addEventListener('click', onDocClick)
window.addEventListener('keydown', onKeydown)
})
onUnmounted(() => {
window.removeEventListener('click', onDocClick)
window.removeEventListener('keydown', onKeydown)
})
}
watch(() => route.fullPath, () => { profileOpen.value = false })
async function signOut() {
profileOpen.value = false
await auth.logout()
navigateTo('/')
}
@@ -16,17 +55,22 @@ async function signOut() {
<div class="min-h-screen bg-zinc-950 text-zinc-100 antialiased">
<header class="border-b border-zinc-900">
<div class="mx-auto flex max-w-6xl items-center justify-between px-6 py-4">
<NuxtLink to="/" class="flex items-center gap-2 text-lg font-semibold">
<!-- Logo doubles as the "home" affordance. Signed-in users land
on their events list; visitors get the marketing landing. -->
<NuxtLink
:to="auth.isAuthenticated.value ? '/dashboard' : '/'"
class="flex items-center gap-2 text-lg font-semibold"
>
<span class="inline-block h-2.5 w-2.5 rounded-full bg-brand-500"></span>
GuestGuard
</NuxtLink>
<nav class="flex items-center gap-4 text-sm text-zinc-400">
<nav class="flex items-center gap-2 text-sm text-zinc-400">
<a
v-if="showGithub"
href="https://github.com/alchemistkay/guestguard"
target="_blank"
rel="noopener"
class="transition hover:text-zinc-100"
class="rounded-md p-2 transition hover:bg-zinc-900 hover:text-zinc-100"
title="View on GitHub"
aria-label="View on GitHub"
>
@@ -34,14 +78,90 @@ async function signOut() {
<path d="M12 0C5.374 0 0 5.373 0 12c0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23A11.509 11.509 0 0112 5.803c1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576C20.566 21.797 24 17.3 24 12c0-6.627-5.373-12-12-12z"/>
</svg>
</a>
<ClientOnly>
<template v-if="auth.isAuthenticated.value">
<NuxtLink to="/dashboard" class="transition hover:text-zinc-100">Dashboard</NuxtLink>
<NuxtLink to="/dashboard/billing" class="transition hover:text-zinc-100">Billing</NuxtLink>
<button class="transition hover:text-zinc-100" @click="signOut">Sign out</button>
<!-- Logo is the "home events" affordance; the only top-level
nav element for signed-in users is the profile dropdown. -->
<!-- Profile dropdown Account / Billing / Sign out -->
<div ref="profileRef" class="relative">
<button
type="button"
class="flex items-center gap-2 rounded-md px-2 py-1.5 transition hover:bg-zinc-900 hover:text-zinc-100"
:aria-expanded="profileOpen"
aria-haspopup="menu"
aria-label="Account menu"
@click="profileOpen = !profileOpen"
>
<span class="flex h-7 w-7 items-center justify-center rounded-full bg-brand-500/15 text-xs font-semibold text-brand-300">
{{ initials(auth.user.value?.name) }}
</span>
<svg
class="h-3 w-3 text-zinc-500 transition-transform"
:class="profileOpen ? 'rotate-180' : ''"
viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"
>
<path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
</svg>
</button>
<Transition
enter-active-class="transition duration-150 ease-out"
enter-from-class="-translate-y-1 opacity-0"
enter-to-class="translate-y-0 opacity-100"
leave-active-class="transition duration-100 ease-in"
leave-from-class="translate-y-0 opacity-100"
leave-to-class="-translate-y-1 opacity-0"
>
<div
v-if="profileOpen"
role="menu"
class="absolute right-0 top-full z-30 mt-2 w-60 overflow-hidden rounded-lg border border-zinc-800 bg-zinc-950 shadow-2xl"
>
<div class="border-b border-zinc-900 px-3 py-3">
<p class="truncate text-sm font-medium text-zinc-100">
{{ auth.user.value?.name || 'Account' }}
</p>
<p class="truncate text-xs text-zinc-500">{{ auth.user.value?.email }}</p>
</div>
<NuxtLink
to="/dashboard/account"
role="menuitem"
class="flex items-center gap-2 px-3 py-2 text-sm text-zinc-200 transition hover:bg-zinc-900"
>
<svg class="h-4 w-4 text-zinc-500" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd" />
</svg>
Account
</NuxtLink>
<NuxtLink
to="/dashboard/billing"
role="menuitem"
class="flex items-center gap-2 px-3 py-2 text-sm text-zinc-200 transition hover:bg-zinc-900"
>
<svg class="h-4 w-4 text-zinc-500" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path d="M4 4a2 2 0 00-2 2v1h16V6a2 2 0 00-2-2H4zM18 9H2v5a2 2 0 002 2h12a2 2 0 002-2V9zM4 13a1 1 0 011-1h1a1 1 0 110 2H5a1 1 0 01-1-1zm5-1a1 1 0 100 2h1a1 1 0 100-2H9z" />
</svg>
Billing &amp; plan
</NuxtLink>
<button
type="button"
role="menuitem"
class="flex w-full items-center gap-2 border-t border-zinc-900 px-3 py-2 text-left text-sm text-zinc-200 transition hover:bg-zinc-900"
@click="signOut"
>
<svg class="h-4 w-4 text-zinc-500" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M3 3a1 1 0 011-1h6a1 1 0 110 2H5v12h5a1 1 0 110 2H4a1 1 0 01-1-1V3zm12.293 4.293a1 1 0 011.414 0l3 3a1 1 0 010 1.414l-3 3a1 1 0 01-1.414-1.414L16.586 12H9a1 1 0 110-2h7.586l-1.293-1.293a1 1 0 010-1.414z" clip-rule="evenodd" />
</svg>
Sign out
</button>
</div>
</Transition>
</div>
</template>
<template v-else>
<NuxtLink to="/login" class="transition hover:text-zinc-100">Sign in</NuxtLink>
<NuxtLink to="/login" class="px-3 py-1.5 transition hover:text-zinc-100">Sign in</NuxtLink>
<NuxtLink to="/signup" class="btn-primary !px-3 !py-1.5 text-xs">Get started</NuxtLink>
</template>
</ClientOnly>
+16 -3
View File
@@ -5,14 +5,27 @@
// Apple Calendar has no web-deeplink — it imports .ics files directly from the
// device. So Apple and "Other" both point at the .ics download URL; the only
// difference is the label so a desktop guest knows which to click.
defineProps<{
const props = defineProps<{
links: {
google: string
outlook: string
yahoo: string
ics: string
}
token: string
}>()
// The backend embeds a fully-qualified ics URL built from GG_PUBLIC_BASE_URL,
// which in production points at the same origin as the API (ingress). In
// dev the public base is the Nuxt frontend (port 3000) — that origin has no
// /access/.../calendar.ics route, so clicking would 404. We always
// reconstruct against runtimeConfig.apiBase, which is the host that
// actually serves the .ics endpoint regardless of deployment topology.
const config = useRuntimeConfig()
const icsHref = computed(() => {
const base = (config.public.apiBase as string) || ''
return `${base}/access/${props.token}/calendar.ics`
})
</script>
<template>
@@ -50,7 +63,7 @@ defineProps<{
<!-- Apple Calendar imports .ics from the file system; pointing at the
download triggers the OS handler on macOS/iOS. -->
<a
:href="links.ics"
:href="icsHref"
class="flex items-center justify-center gap-1.5 rounded-md border border-zinc-700 bg-zinc-950 px-3 py-2 text-xs font-medium text-zinc-200 transition hover:border-brand-600 hover:bg-brand-500/10 hover:text-brand-200"
>
<svg class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
@@ -61,7 +74,7 @@ defineProps<{
<!-- Catch-all .ics for everything that isn't a hosted web calendar. -->
<a
:href="links.ics"
:href="icsHref"
class="flex items-center justify-center gap-1.5 rounded-md border border-zinc-700 bg-zinc-950 px-3 py-2 text-xs font-medium text-zinc-200 transition hover:border-brand-600 hover:bg-brand-500/10 hover:text-brand-200"
>
<svg class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
+321
View File
@@ -0,0 +1,321 @@
<script setup lang="ts">
// Tier 2 Block D — per-event branding editor. Editor+ only; we hide the
// inputs for viewers (the server enforces the role too).
//
// Live preview happens client-side: we don't PUT until the host hits Save,
// but the colours/logo/cover update the preview pane on every change so
// they see what their guests will see before committing.
interface Branding {
event_id: string
primary_color?: string | null
accent_color?: string | null
logo_url?: string | null
cover_image_url?: string | null
font_family?: string | null
greeting_message?: string | null
updated_at?: string
}
interface BrandingResponse {
event_id: string
primary_color?: string | null
accent_color?: string | null
logo_url?: string | null
cover_image_url?: string | null
font_family?: string | null
greeting_message?: string | null
allowed_fonts: string[]
}
const props = defineProps<{
eventId: string
yourRole?: 'owner' | 'editor' | 'viewer' | null
// Event name + date are echoed in the preview so the host sees the
// composed page, not just the colour swatches.
eventName?: string
eventVenue?: string
eventDate?: string
}>()
const config = useRuntimeConfig()
const auth = useAuth()
const loading = ref(true)
const saving = ref(false)
const error = ref<string | null>(null)
const allowedFonts = ref<string[]>([])
// Form state — strings so empty maps cleanly to "clear this field".
const primary = ref('')
const accent = ref('')
const logoURL = ref('')
const coverURL = ref('')
const font = ref('')
const greeting = ref('')
const canEdit = computed(() => props.yourRole === 'owner' || props.yourRole === 'editor')
async function refresh() {
loading.value = true
try {
const data = await useApi<BrandingResponse>(`/events/${props.eventId}/branding`)
allowedFonts.value = data.allowed_fonts || []
primary.value = data.primary_color ?? ''
accent.value = data.accent_color ?? ''
logoURL.value = data.logo_url ?? ''
coverURL.value = data.cover_image_url ?? ''
font.value = data.font_family ?? ''
greeting.value = data.greeting_message ?? ''
} catch (e: any) {
error.value = useErrMessage(e, 'Could not load branding')
} finally {
loading.value = false
}
}
onMounted(refresh)
// --- uploads ---
const uploadingLogo = ref(false)
const uploadingCover = ref(false)
async function upload(file: File): Promise<string> {
const apiBase = config.public.apiBase as string
const token = auth.liveAccessToken()
const form = new FormData()
form.append('file', file)
const res = await fetch(`${apiBase}/uploads/image`, {
method: 'POST',
headers: token ? { Authorization: `Bearer ${token}` } : {},
credentials: 'include',
body: form,
})
if (!res.ok) {
let msg = `HTTP ${res.status}`
try { msg = (await res.json()).error || msg } catch { /* no body */ }
throw new Error(msg)
}
const json = await res.json()
return json.url as string
}
async function onLogoSelect(e: Event) {
const file = (e.target as HTMLInputElement).files?.[0]
if (!file) return
uploadingLogo.value = true
error.value = null
try { logoURL.value = await upload(file) }
catch (e: any) { error.value = useErrMessage(e, 'Logo upload failed') }
finally { uploadingLogo.value = false }
}
async function onCoverSelect(e: Event) {
const file = (e.target as HTMLInputElement).files?.[0]
if (!file) return
uploadingCover.value = true
error.value = null
try { coverURL.value = await upload(file) }
catch (e: any) { error.value = useErrMessage(e, 'Cover upload failed') }
finally { uploadingCover.value = false }
}
async function save() {
saving.value = true
error.value = null
try {
await useApi(`/events/${props.eventId}/branding`, {
method: 'PUT',
body: {
primary_color: primary.value,
accent_color: accent.value,
logo_url: logoURL.value,
cover_image_url: coverURL.value,
font_family: font.value,
greeting_message: greeting.value,
},
})
} catch (e: any) {
error.value = useErrMessage(e, 'Could not save branding')
} finally {
saving.value = false
}
}
// Preview style — drives both the colour swatches and the mini RSVP
// card preview underneath. Reactive on every input so the host sees
// changes immediately, even before clicking Save.
const previewStyle = computed(() => ({
'--brand-primary': primary.value || '#22c55e',
'--brand-accent': accent.value || '#15803d',
fontFamily: font.value || 'inherit',
}))
function fmtDate(iso?: string) {
if (!iso) return ''
try { return new Date(iso).toLocaleString() } catch { return iso }
}
</script>
<template>
<section class="card">
<header class="mb-3 flex items-center justify-between">
<h2 class="text-lg font-semibold">Branding</h2>
<button
v-if="canEdit"
type="button"
class="btn-primary text-sm"
:disabled="saving"
@click="save"
>{{ saving ? 'Saving…' : 'Save branding' }}</button>
</header>
<p class="mb-4 text-xs text-zinc-500">
Customise how your invitation page looks. Colours, font, logo, and cover image apply to
every guest's RSVP page.
</p>
<p v-if="error" class="mb-3 text-sm text-red-400">{{ error }}</p>
<p v-if="loading" class="text-sm text-zinc-500">Loading branding…</p>
<div v-else class="grid grid-cols-1 gap-6 lg:grid-cols-2">
<!-- Editor -->
<div class="space-y-4">
<div class="grid grid-cols-2 gap-3">
<div>
<label class="label">Primary colour</label>
<div class="flex items-center gap-2">
<input
v-model="primary"
type="color"
class="h-10 w-12 cursor-pointer rounded border border-zinc-700 bg-zinc-900 disabled:opacity-50"
:disabled="!canEdit"
/>
<input
v-model="primary"
type="text"
placeholder="#22c55e"
class="input flex-1 font-mono text-xs"
:disabled="!canEdit"
/>
</div>
</div>
<div>
<label class="label">Accent colour</label>
<div class="flex items-center gap-2">
<input
v-model="accent"
type="color"
class="h-10 w-12 cursor-pointer rounded border border-zinc-700 bg-zinc-900 disabled:opacity-50"
:disabled="!canEdit"
/>
<input
v-model="accent"
type="text"
placeholder="#15803d"
class="input flex-1 font-mono text-xs"
:disabled="!canEdit"
/>
</div>
</div>
</div>
<div>
<label class="label">Font family</label>
<select v-model="font" class="input" :disabled="!canEdit">
<option value="">Default (Inter)</option>
<option v-for="f in allowedFonts" :key="f" :value="f">{{ f }}</option>
</select>
</div>
<div>
<label class="label">Greeting message (shown above the form)</label>
<textarea
v-model="greeting"
class="input min-h-[72px]"
placeholder="Looking forward to celebrating with you!"
:disabled="!canEdit"
/>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="label">Logo</label>
<input
type="file"
accept="image/png,image/jpeg"
class="block w-full text-xs text-zinc-400 file:mr-2 file:rounded file:border-0 file:bg-zinc-800 file:px-2 file:py-1 file:text-zinc-200 file:cursor-pointer"
:disabled="!canEdit || uploadingLogo"
@change="onLogoSelect"
/>
<div v-if="logoURL" class="mt-2 flex items-center gap-2">
<img :src="logoURL" alt="logo preview" class="h-12 w-12 rounded object-contain bg-zinc-900" />
<button
v-if="canEdit"
type="button"
class="text-xs text-zinc-500 hover:text-red-300"
@click="logoURL = ''"
>Remove</button>
</div>
</div>
<div>
<label class="label">Cover image</label>
<input
type="file"
accept="image/png,image/jpeg"
class="block w-full text-xs text-zinc-400 file:mr-2 file:rounded file:border-0 file:bg-zinc-800 file:px-2 file:py-1 file:text-zinc-200 file:cursor-pointer"
:disabled="!canEdit || uploadingCover"
@change="onCoverSelect"
/>
<div v-if="coverURL" class="mt-2 flex items-center gap-2">
<img :src="coverURL" alt="cover preview" class="h-12 w-24 rounded object-cover" />
<button
v-if="canEdit"
type="button"
class="text-xs text-zinc-500 hover:text-red-300"
@click="coverURL = ''"
>Remove</button>
</div>
</div>
</div>
<p class="text-xs text-zinc-500">
Images: PNG or JPEG, up to 2 MB. They're re-encoded server-side so EXIF data is stripped.
</p>
</div>
<!-- Live preview -->
<div>
<p class="mb-2 text-xs font-medium uppercase tracking-wider text-zinc-500">Preview</p>
<div
class="overflow-hidden rounded-lg border border-zinc-800 bg-zinc-950"
:style="previewStyle"
>
<div
v-if="coverURL"
class="h-28 w-full bg-cover bg-center"
:style="{ backgroundImage: `url(${coverURL})` }"
></div>
<div v-else class="h-28 w-full" :style="{ background: 'var(--brand-primary)' }"></div>
<div class="p-4">
<div class="mb-3 flex items-center gap-3">
<img v-if="logoURL" :src="logoURL" alt="" class="h-10 w-10 rounded object-contain bg-zinc-900" />
<div>
<p class="text-xs uppercase tracking-widest" :style="{ color: 'var(--brand-primary)' }">Invitation</p>
<h3 class="text-xl font-semibold text-zinc-50">{{ eventName || 'Your event name' }}</h3>
</div>
</div>
<p class="mb-3 text-xs text-zinc-400">
{{ eventVenue || 'Venue' }} · {{ fmtDate(eventDate) || 'When' }}
</p>
<p v-if="greeting" class="mb-4 text-sm text-zinc-300">{{ greeting }}</p>
<button
type="button"
class="w-full rounded-md px-3 py-2 text-sm font-medium text-zinc-950"
:style="{ background: 'var(--brand-primary)' }"
disabled
>Submit RSVP</button>
</div>
</div>
</div>
</div>
</section>
</template>
+203
View File
@@ -0,0 +1,203 @@
<script setup lang="ts">
// Account page — owns the data-export + account-deletion controls that
// used to sit on the billing tab. Privacy concerns ≠ billing concerns;
// hosts shouldn't have to scroll past pricing to find "delete my account".
definePageMeta({ middleware: ['auth'] })
const router = useRouter()
const auth = useAuth()
const config = useRuntimeConfig()
const exporting = ref(false)
const deleteConfirmOpen = ref(false)
const deleteConfirmation = ref('')
const deleting = ref(false)
const deleteError = ref<string | null>(null)
const toast = ref<string | null>(null)
let toastTimer: ReturnType<typeof setTimeout> | null = null
function showToast(text: string) {
toast.value = text
if (toastTimer) clearTimeout(toastTimer)
toastTimer = setTimeout(() => { toast.value = null }, 5000)
}
async function exportData() {
exporting.value = true
try {
const apiBase = config.public.apiBase as string
const token = auth.liveAccessToken()
// Plain fetch (not useApi) so the response is treated as a download.
const res = await fetch(`${apiBase}/me/data-export`, {
headers: token ? { Authorization: `Bearer ${token}` } : {},
credentials: 'include',
})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'guestguard-data-export.json'
a.click()
URL.revokeObjectURL(url)
showToast('Export downloaded.')
} catch (e: any) {
showToast(useErrMessage(e, 'Export failed'))
} finally {
exporting.value = false
}
}
async function confirmDelete() {
deleting.value = true
deleteError.value = null
try {
await useApi('/me', { method: 'DELETE' })
// Soft-delete revoked our refresh token; clear local session and
// bounce to the marketing landing.
auth.clearSession()
await router.push('/')
} catch (e: any) {
deleteError.value = useErrMessage(e, 'Could not delete account')
} finally {
deleting.value = false
}
}
</script>
<template>
<section class="space-y-6">
<div>
<NuxtLink to="/dashboard" class="mb-2 inline-block text-sm text-zinc-400 hover:text-zinc-200">
Back to events
</NuxtLink>
<h1 class="text-2xl font-semibold">Account</h1>
<p class="mt-1 text-sm text-zinc-400">
Manage your profile and personal data.
</p>
</div>
<ClientOnly>
<!-- Profile summary -->
<div class="card">
<h2 class="mb-3 text-lg font-semibold">Profile</h2>
<dl class="grid grid-cols-1 gap-3 text-sm sm:grid-cols-2">
<div>
<dt class="text-xs uppercase tracking-wider text-zinc-500">Name</dt>
<dd class="mt-1 text-zinc-100">{{ auth.user.value?.name || '—' }}</dd>
</div>
<div>
<dt class="text-xs uppercase tracking-wider text-zinc-500">Email</dt>
<dd class="mt-1 break-all text-zinc-100">{{ auth.user.value?.email || '—' }}</dd>
</div>
</dl>
</div>
<!-- Your data -->
<div class="card">
<h2 class="mb-1 text-lg font-semibold">Your data</h2>
<p class="mb-4 text-xs text-zinc-500">
Export a copy of everything we hold about you, or delete your account.
</p>
<div class="space-y-3">
<button
type="button"
class="flex w-full items-center justify-between rounded-md border border-zinc-700 bg-zinc-950 px-3 py-3 text-left transition hover:border-zinc-500 hover:bg-zinc-900 disabled:opacity-50"
:disabled="exporting"
@click="exportData"
>
<span>
<span class="block text-sm font-medium text-zinc-100">Export my data</span>
<span class="block text-xs text-zinc-500">
Download a JSON file with your events, guests, RSVPs, and account info.
</span>
</span>
<span class="text-xs text-zinc-400">{{ exporting ? '…' : '↓' }}</span>
</button>
<button
type="button"
class="flex w-full items-center justify-between rounded-md border border-red-800/40 bg-red-950/10 px-3 py-3 text-left transition hover:border-red-700 hover:bg-red-950/20"
@click="deleteConfirmOpen = true"
>
<span>
<span class="block text-sm font-medium text-red-300">Delete my account</span>
<span class="block text-xs text-red-400/70">
Soft-deleted immediately, permanently erased after 30 days. You'll be signed out everywhere.
</span>
</span>
<span class="text-xs text-red-400">→</span>
</button>
</div>
</div>
<template #fallback>
<div class="card text-sm text-zinc-500">Loading…</div>
</template>
</ClientOnly>
<!-- Delete-account confirmation -->
<Teleport to="body">
<div
v-if="deleteConfirmOpen"
class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm"
@click.self="deleteConfirmOpen = false"
>
<div
role="alertdialog"
aria-modal="true"
aria-labelledby="del-acct-title"
class="w-full max-w-md rounded-lg border border-zinc-800 bg-zinc-900 p-5 shadow-2xl"
>
<h3 id="del-acct-title" class="mb-1 text-base font-semibold">Delete account?</h3>
<p class="mb-3 text-sm text-zinc-400">
Your account will be soft-deleted now and permanently erased
after 30 days. All your events, guests, and RSVP history go
with it. You'll be signed out from every device.
</p>
<p class="mb-3 text-xs text-zinc-500">
Type <code class="rounded bg-zinc-800 px-1 py-0.5 font-mono text-zinc-300">delete</code>
to confirm.
</p>
<input
v-model="deleteConfirmation"
type="text"
placeholder="delete"
class="input mb-3 font-mono"
autocomplete="off"
/>
<div class="flex items-center justify-end gap-2">
<button class="text-sm text-zinc-400 hover:text-zinc-200" :disabled="deleting" @click="deleteConfirmOpen = false">Cancel</button>
<button
class="rounded-md bg-red-500/90 px-3 py-1.5 text-sm font-medium text-white shadow-sm transition hover:bg-red-500 disabled:opacity-40"
:disabled="deleting || deleteConfirmation.trim().toLowerCase() !== 'delete'"
@click="confirmDelete"
>
{{ deleting ? 'Deleting…' : 'Delete forever' }}
</button>
</div>
<p v-if="deleteError" class="mt-3 text-sm text-red-400">{{ deleteError }}</p>
</div>
</div>
</Teleport>
<!-- Toast -->
<Transition
enter-active-class="transition duration-200 ease-out"
enter-from-class="translate-y-2 opacity-0"
enter-to-class="translate-y-0 opacity-100"
leave-active-class="transition duration-200 ease-in"
leave-from-class="translate-y-0 opacity-100"
leave-to-class="translate-y-2 opacity-0"
>
<button
v-if="toast"
type="button"
class="fixed bottom-6 right-6 z-50 max-w-sm rounded-lg border border-brand-700/60 bg-brand-950/90 px-4 py-3 text-left text-sm text-brand-100 shadow-lg backdrop-blur"
@click="toast = null"
>
<span aria-hidden="true" class="mr-2"></span>{{ toast }}
</button>
</Transition>
</section>
</template>
+2 -136
View File
@@ -2,65 +2,13 @@
definePageMeta({ middleware: ['auth'] })
const route = useRoute()
const router = useRouter()
const billing = useBilling()
const auth = useAuth()
const config = useRuntimeConfig()
const switching = ref<'pro' | 'business' | null>(null)
const portalLoading = ref(false)
const error = ref<string | null>(null)
const toast = ref<string | null>(null)
let toastTimer: ReturnType<typeof setTimeout> | null = null
// Your data
const exporting = ref(false)
const deleteConfirmOpen = ref(false)
const deleteConfirmation = ref('')
const deleting = ref(false)
const deleteError = ref<string | null>(null)
async function exportData() {
exporting.value = true
try {
const apiBase = config.public.apiBase as string
const token = auth.liveAccessToken()
// Plain fetch (not useApi) so the response is treated as a download.
const res = await fetch(`${apiBase}/me/data-export`, {
headers: token ? { Authorization: `Bearer ${token}` } : {},
credentials: 'include',
})
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'guestguard-data-export.json'
a.click()
URL.revokeObjectURL(url)
showToast('Export downloaded.')
} catch (e: any) {
showToast(useErrMessage(e, 'Export failed'))
} finally {
exporting.value = false
}
}
async function confirmDelete() {
deleting.value = true
deleteError.value = null
try {
await useApi('/me', { method: 'DELETE' })
// Soft-delete revoked our refresh token; clear local session and
// bounce to the marketing landing.
auth.clearSession()
await router.push('/')
} catch (e: any) {
deleteError.value = useErrMessage(e, 'Could not delete account')
} finally {
deleting.value = false
}
}
function showToast(text: string) {
toast.value = text
if (toastTimer) clearTimeout(toastTimer)
@@ -147,7 +95,7 @@ function periodEndLabel(iso?: string): string {
<section class="space-y-6">
<div>
<NuxtLink to="/dashboard" class="mb-2 inline-block text-sm text-zinc-400 hover:text-zinc-200">
Back to dashboard
Back to events
</NuxtLink>
<h1 class="text-2xl font-semibold">Billing &amp; plan</h1>
<p class="mt-1 text-sm text-zinc-400">
@@ -281,96 +229,14 @@ function periodEndLabel(iso?: string): string {
<p class="text-xs text-zinc-500">
Receipts and invoices are emailed automatically by Stripe.
Need to cancel? Use <a href="#" class="text-brand-400 hover:text-brand-300" @click.prevent="manageSubscription">Manage subscription</a> above.
Data export and account deletion now live on the <NuxtLink to="/dashboard/account" class="text-brand-400 hover:text-brand-300">Account</NuxtLink> page.
</p>
<!-- ===== Your data ===== -->
<div class="card mt-2">
<h2 class="mb-1 text-lg font-semibold">Your data</h2>
<p class="mb-4 text-xs text-zinc-500">
Export a copy of everything we hold about you, or delete your account.
</p>
<div class="space-y-3">
<button
type="button"
class="flex w-full items-center justify-between rounded-md border border-zinc-700 bg-zinc-950 px-3 py-3 text-left transition hover:border-zinc-500 hover:bg-zinc-900 disabled:opacity-50"
:disabled="exporting"
@click="exportData"
>
<span>
<span class="block text-sm font-medium text-zinc-100">Export my data</span>
<span class="block text-xs text-zinc-500">
Download a JSON file with your events, guests, RSVPs, and account info.
</span>
</span>
<span class="text-xs text-zinc-400">{{ exporting ? '…' : '↓' }}</span>
</button>
<button
type="button"
class="flex w-full items-center justify-between rounded-md border border-red-800/40 bg-red-950/10 px-3 py-3 text-left transition hover:border-red-700 hover:bg-red-950/20"
@click="deleteConfirmOpen = true"
>
<span>
<span class="block text-sm font-medium text-red-300">Delete my account</span>
<span class="block text-xs text-red-400/70">
Soft-deleted immediately, permanently erased after 30 days. You'll be signed out everywhere.
</span>
</span>
<span class="text-xs text-red-400">→</span>
</button>
</div>
</div>
<template #fallback>
<div class="card text-sm text-zinc-500">Loading</div>
</template>
</ClientOnly>
<!-- Delete-account confirmation -->
<Teleport to="body">
<div
v-if="deleteConfirmOpen"
class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm"
@click.self="deleteConfirmOpen = false"
>
<div
role="alertdialog"
aria-modal="true"
aria-labelledby="del-acct-title"
class="w-full max-w-md rounded-lg border border-zinc-800 bg-zinc-900 p-5 shadow-2xl"
>
<h3 id="del-acct-title" class="mb-1 text-base font-semibold">Delete account?</h3>
<p class="mb-3 text-sm text-zinc-400">
Your account will be soft-deleted now and permanently erased
after 30 days. All your events, guests, and RSVP history go
with it. You'll be signed out from every device.
</p>
<p class="mb-3 text-xs text-zinc-500">
Type <code class="rounded bg-zinc-800 px-1 py-0.5 font-mono text-zinc-300">delete</code>
to confirm.
</p>
<input
v-model="deleteConfirmation"
type="text"
placeholder="delete"
class="input mb-3 font-mono"
autocomplete="off"
/>
<div class="flex items-center justify-end gap-2">
<button class="text-sm text-zinc-400 hover:text-zinc-200" :disabled="deleting" @click="deleteConfirmOpen = false">Cancel</button>
<button
class="rounded-md bg-red-500/90 px-3 py-1.5 text-sm font-medium text-white shadow-sm transition hover:bg-red-500 disabled:opacity-40"
:disabled="deleting || deleteConfirmation.trim().toLowerCase() !== 'delete'"
@click="confirmDelete"
>
{{ deleting ? 'Deleting…' : 'Delete forever' }}
</button>
</div>
<p v-if="deleteError" class="mt-3 text-sm text-red-400">{{ deleteError }}</p>
</div>
</div>
</Teleport>
<!-- Toast for return-from-Stripe -->
<Transition
enter-active-class="transition duration-200 ease-out"
+13 -1
View File
@@ -728,7 +728,7 @@ function checkLabel(band?: string): string {
<section v-else class="space-y-8">
<div>
<NuxtLink to="/dashboard" class="mb-2 inline-block text-sm text-zinc-400 hover:text-zinc-200">
Back to dashboard
Back to events
</NuxtLink>
<div class="flex items-center justify-between">
<h1 class="text-2xl font-semibold">{{ event.name }}</h1>
@@ -1120,6 +1120,18 @@ function checkLabel(band?: string): string {
</aside>
</div>
<!-- Branding (Tier 2 Block D). Editor+ can change colours/logo/cover;
viewers see read-only. -->
<div v-if="event" class="mt-6">
<BrandingCard
:event-id="eventId"
:your-role="event.your_role"
:event-name="event.name"
:event-venue="event.venue"
:event-date="event.event_date"
/>
</div>
<!-- Analytics (Tier 2 Block E). Read-only summary; viewer+ can see it. -->
<div v-if="event" class="mt-6">
<AnalyticsCard :event-id="eventId" />
+2 -2
View File
@@ -129,7 +129,7 @@ const sampleCapacity = computed(() => maxCapacity.value || 50)
<template>
<section>
<NuxtLink to="/dashboard" class="mb-6 inline-block text-sm text-zinc-400 hover:text-zinc-200">
Back to dashboard
Back to events
</NuxtLink>
<div class="grid gap-12 lg:grid-cols-2 lg:items-start">
@@ -139,7 +139,7 @@ const sampleCapacity = computed(() => maxCapacity.value || 50)
<div v-if="!host" class="card text-sm text-zinc-400">
Please sign in first.
<NuxtLink to="/dashboard" class="text-brand-400">Go to dashboard</NuxtLink>
<NuxtLink to="/dashboard" class="text-brand-400">Go to events</NuxtLink>
</div>
<form v-else class="card space-y-4" @submit.prevent="submit">
+174 -19
View File
@@ -1,32 +1,56 @@
<script setup lang="ts">
definePageMeta({ middleware: ['auth'] })
// Tier 2 Block C once a user can be invited as editor/viewer onto other
// hosts' events, the dashboard has to surface that distinction. We split
// the list into "Your events" (the ones the signed-in user created) and
// "Shared with you" (every event they're a collaborator on but didn't
// create). The split is driven by host_id; the role pill on each card
// tells the collaborator what they can actually do.
interface EventSummary {
id: string
host_id: string
name: string
slug: string
event_date: string
status: string
venue: string
max_capacity: number
your_role?: 'owner' | 'editor' | 'viewer'
}
interface EventsResponse {
events: EventSummary[]
}
interface PendingInvite {
event_id: string
event_name: string
role: 'owner' | 'editor' | 'viewer'
inviter_name: string
expires_at: string
created_at: string
}
const auth = useAuth()
const events = ref<EventSummary[]>([])
const loadingEvents = ref(false)
const loadError = ref<string | null>(null)
// Pending invites for the signed-in user's email. Shown as a banner above
// the event list so a user who just verified their email + signed in can
// accept without re-clicking the invitation email link (which would have
// opened in a different tab and lost the original signup context).
const pendingInvites = ref<PendingInvite[]>([])
const acceptingInvite = ref<string | null>(null)
const inviteError = ref<string | null>(null)
async function loadEvents() {
if (!auth.user.value) return
loadingEvents.value = true
loadError.value = null
try {
// host is derived server-side from the session no query param needed.
const res = await useApi<EventsResponse>('/events')
events.value = res.events
} catch (e: any) {
@@ -36,11 +60,63 @@ async function loadEvents() {
}
}
watch(() => auth.user.value, loadEvents, { immediate: true })
async function loadPendingInvites() {
if (!auth.user.value) return
try {
const res = await useApi<{ invites: PendingInvite[] }>('/me/invites')
pendingInvites.value = res.invites || []
} catch {
// Non-fatal: the dashboard works fine without the banner.
pendingInvites.value = []
}
}
async function acceptInvite(eventID: string) {
acceptingInvite.value = eventID
inviteError.value = null
try {
await useApi(`/me/invites/${eventID}/accept`, { method: 'POST' })
// Reload both lists the new event should appear in "Shared with you".
await Promise.all([loadEvents(), loadPendingInvites()])
} catch (e: any) {
inviteError.value = useErrMessage(e, 'Could not accept invitation')
} finally {
acceptingInvite.value = null
}
}
function dismissInvite(eventID: string) {
// Local-only dismissal the invite stays valid on the server so the
// user can still revisit it from the inviter's resend, or after
// refreshing the page. Keeps the dashboard tidy if they aren't ready
// to accept right now.
pendingInvites.value = pendingInvites.value.filter((i) => i.event_id !== eventID)
}
watch(() => auth.user.value, () => {
loadEvents()
loadPendingInvites()
}, { immediate: true })
const myEvents = computed(() =>
events.value.filter((e) => auth.user.value && e.host_id === auth.user.value.id),
)
const sharedEvents = computed(() =>
events.value.filter((e) => !auth.user.value || e.host_id !== auth.user.value.id),
)
function fmtDate(iso: string) {
try { return new Date(iso).toLocaleString() } catch { return iso }
}
function roleBadgeClass(role?: string) {
switch (role) {
case 'owner': return 'bg-brand-900/40 text-brand-300'
case 'editor': return 'bg-amber-900/30 text-amber-300'
case 'viewer': return 'bg-zinc-800 text-zinc-300'
default: return 'bg-zinc-800 text-zinc-400'
}
}
</script>
<template>
@@ -53,31 +129,110 @@ function fmtDate(iso: string) {
<div v-else>
<div class="mb-6 flex items-center justify-between">
<div>
<h1 class="text-2xl font-semibold">Your events</h1>
<p class="text-sm text-zinc-400">Signed in as {{ auth.user.value.name }} ({{ auth.user.value.email }})</p>
<h1 class="text-2xl font-semibold">Events</h1>
<p class="text-sm text-zinc-400">
Welcome back, {{ auth.user.value.name }}.
</p>
</div>
<NuxtLink to="/dashboard/events/new" class="btn-primary">New event</NuxtLink>
</div>
<!-- Pending invites banner the safety net for users who lost
the original invite tab during the verify-email round-trip. -->
<div v-if="pendingInvites.length > 0" class="mb-6 space-y-3">
<p v-if="inviteError" class="text-sm text-red-400">{{ inviteError }}</p>
<div
v-for="invite in pendingInvites"
:key="invite.event_id"
class="flex items-center justify-between gap-3 rounded-lg border border-brand-700/60 bg-brand-500/[0.06] p-4"
>
<div class="min-w-0 flex-1">
<p class="text-xs font-medium uppercase tracking-wider text-brand-400">Team invitation</p>
<p class="mt-1 text-sm text-zinc-100">
<strong>{{ invite.inviter_name || 'A teammate' }}</strong>
invited you to
<strong>{{ invite.event_name }}</strong>
as <span class="capitalize text-brand-300">{{ invite.role }}</span>.
</p>
</div>
<div class="flex shrink-0 items-center gap-2">
<button
type="button"
class="text-xs text-zinc-400 hover:text-zinc-200"
@click="dismissInvite(invite.event_id)"
>Later</button>
<button
type="button"
class="btn-primary text-sm"
:disabled="acceptingInvite === invite.event_id"
@click="acceptInvite(invite.event_id)"
>
{{ acceptingInvite === invite.event_id ? 'Accepting…' : 'Accept' }}
</button>
</div>
</div>
</div>
<div v-if="loadingEvents" class="text-sm text-zinc-500">Loading</div>
<div v-else-if="loadError" class="card text-sm text-red-400">{{ loadError }}</div>
<div v-else-if="events.length === 0" class="card text-sm text-zinc-400">
No events yet. Create one to get started.
<div v-else-if="events.length === 0 && pendingInvites.length === 0" class="card text-sm text-zinc-400">
No events yet. Create one to get started, or wait for a teammate to invite you.
</div>
<div v-else class="grid gap-4 md:grid-cols-2">
<NuxtLink
v-for="ev in events"
:key="ev.id"
:to="`/dashboard/events/${ev.id}`"
class="card transition hover:border-brand-700 hover:bg-zinc-900/80"
>
<div class="mb-1 flex items-center justify-between">
<h2 class="font-semibold text-zinc-50">{{ ev.name }}</h2>
<span class="text-xs uppercase tracking-wide text-zinc-500">{{ ev.status }}</span>
<div v-else class="space-y-8">
<!-- Events the signed-in user created. -->
<div>
<header class="mb-3 flex items-baseline justify-between">
<h2 class="text-sm font-medium uppercase tracking-wider text-zinc-400">
Yours · {{ myEvents.length }}
</h2>
</header>
<div v-if="myEvents.length === 0" class="card text-sm text-zinc-500">
You haven't created an event yet.
<NuxtLink to="/dashboard/events/new" class="ml-1 text-brand-400 hover:text-brand-300">Start one</NuxtLink>.
</div>
<p class="text-sm text-zinc-400">{{ ev.venue || '—' }}</p>
<p class="mt-2 text-xs text-zinc-500">{{ fmtDate(ev.event_date) }}</p>
</NuxtLink>
<div v-else class="grid gap-4 md:grid-cols-2">
<NuxtLink
v-for="ev in myEvents"
:key="ev.id"
:to="`/dashboard/events/${ev.id}`"
class="card transition hover:border-brand-700 hover:bg-zinc-900/80"
>
<div class="mb-1 flex items-center justify-between">
<h3 class="font-semibold text-zinc-50">{{ ev.name }}</h3>
<span class="text-xs uppercase tracking-wide text-zinc-500">{{ ev.status }}</span>
</div>
<p class="text-sm text-zinc-400">{{ ev.venue || '—' }}</p>
<p class="mt-2 text-xs text-zinc-500">{{ fmtDate(ev.event_date) }}</p>
</NuxtLink>
</div>
</div>
<!-- Events the user was invited to. -->
<div v-if="sharedEvents.length > 0">
<header class="mb-3 flex items-baseline justify-between">
<h2 class="text-sm font-medium uppercase tracking-wider text-zinc-400">
Shared with you · {{ sharedEvents.length }}
</h2>
</header>
<div class="grid gap-4 md:grid-cols-2">
<NuxtLink
v-for="ev in sharedEvents"
:key="ev.id"
:to="`/dashboard/events/${ev.id}`"
class="card transition hover:border-brand-700 hover:bg-zinc-900/80"
>
<div class="mb-1 flex items-center justify-between gap-2">
<h3 class="truncate font-semibold text-zinc-50">{{ ev.name }}</h3>
<span
class="rounded-full px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide"
:class="roleBadgeClass(ev.your_role)"
>{{ ev.your_role || 'member' }}</span>
</div>
<p class="text-sm text-zinc-400">{{ ev.venue || '—' }}</p>
<p class="mt-2 text-xs text-zinc-500">{{ fmtDate(ev.event_date) }}</p>
</NuxtLink>
</div>
</div>
</div>
</div>
+24 -3
View File
@@ -1,19 +1,40 @@
<script setup lang="ts">
// Sign-in page. Honors `?email=` (pre-fill) and `?redirect=` (post-login
// landing). When sessionStorage carries a parked redirect from an earlier
// signup verify-email round-trip, prefer that so the collaborator-invite
// flow resumes naturally.
const auth = useAuth()
const route = useRoute()
const email = ref('')
const queryEmail = typeof route.query.email === 'string' ? route.query.email : ''
const email = ref(queryEmail)
const password = ref('')
const submitting = ref(false)
const error = ref<string | null>(null)
// Resolve the post-login destination once. Order of precedence:
// 1. ?redirect= on the URL (explicit caller intent)
// 2. gg.postAuthRedirect in sessionStorage (parked by signup.vue)
// 3. /dashboard fallback
function resolveRedirect(): string {
const queryRedirect = typeof route.query.redirect === 'string' ? route.query.redirect : ''
if (queryRedirect) return queryRedirect
if (import.meta.client) {
const parked = sessionStorage.getItem('gg.postAuthRedirect')
if (parked) {
sessionStorage.removeItem('gg.postAuthRedirect')
return parked
}
}
return '/dashboard'
}
async function submit() {
error.value = null
submitting.value = true
try {
await auth.login(email.value, password.value)
const redirect = (route.query.redirect as string) || '/dashboard'
await navigateTo(redirect)
await navigateTo(resolveRedirect())
} catch (e: any) {
error.value = useErrMessage(e, 'Login failed')
} finally {
+79 -17
View File
@@ -15,6 +15,15 @@ interface CalendarLinks {
ics: string
}
interface BrandingPayload {
primary_color?: string | null
accent_color?: string | null
logo_url?: string | null
cover_image_url?: string | null
font_family?: string | null
greeting_message?: string | null
}
interface AccessResponse {
guest: { id: string; name: string; email?: string | null; plus_ones: number }
event: { id: string; name: string; venue: string; event_date: string }
@@ -22,6 +31,7 @@ interface AccessResponse {
access_log_id: string
rsvp?: ExistingRSVP | null
calendar?: CalendarLinks
branding?: BrandingPayload | null
}
interface RSVPSubmitResponse {
@@ -143,6 +153,20 @@ function fmtDate(iso?: string) {
// as /access loads the guest can grab them before submitting.
const calendar = computed<CalendarLinks | null>(() => access.value?.calendar ?? null)
// Branding (Tier 2 Block D). Null = use defaults. Each field is optional;
// missing pieces fall back to the GuestGuard look.
const branding = computed<BrandingPayload | null>(() => access.value?.branding ?? null)
const brandingStyle = computed(() => {
const b = branding.value
if (!b) return {}
const style: Record<string, string> = {}
if (b.primary_color) style['--brand-primary'] = b.primary_color
if (b.accent_color) style['--brand-accent'] = b.accent_color
if (b.font_family) style.fontFamily = b.font_family
return style
})
const greetingMessage = computed(() => branding.value?.greeting_message || '')
// showForm = no prior submission, or the guest has clicked "Change my response"
const showForm = computed(() => editing.value || !existing.value)
const submitLabel = computed(() => {
@@ -152,7 +176,10 @@ const submitLabel = computed(() => {
</script>
<template>
<section class="mx-auto max-w-xl py-8">
<!-- Branding (Tier 2 Block D) lives at the section root so every card
below inherits the CSS vars + font. brandingStyle is empty when the
host hasn't customised, so defaults apply naturally. -->
<section class="mx-auto max-w-xl py-8" :style="brandingStyle">
<div v-if="loading" class="text-sm text-zinc-500">Looking up your invitation</div>
<div v-else-if="loadError" class="card border-red-900/60 bg-red-950/30">
@@ -186,6 +213,7 @@ const submitLabel = computed(() => {
<AddToCalendar
v-if="calendar && result.rsvp.response === 'attending'"
:links="calendar"
:token="token"
class="mt-5 border-t border-zinc-800 pt-4"
/>
@@ -217,6 +245,7 @@ const submitLabel = computed(() => {
<AddToCalendar
v-if="calendar && existing.response === 'attending'"
:links="calendar"
:token="token"
class="mb-4 border-t border-zinc-800 pt-4"
/>
@@ -231,21 +260,48 @@ const submitLabel = computed(() => {
</p>
</div>
<div v-else-if="access && showForm" class="card">
<p class="text-xs uppercase tracking-widest text-brand-500">
{{ existing ? 'Update your response' : 'Invitation' }}
</p>
<h1 class="mb-1 text-2xl font-semibold">{{ access.event.name }}</h1>
<p class="mb-6 text-sm text-zinc-400">
{{ access.event.venue }} · {{ fmtDate(access.event.event_date) }}
</p>
<div v-else-if="access && showForm" class="card overflow-hidden p-0">
<!-- Cover image only renders when the host uploaded one. -->
<div
v-if="branding?.cover_image_url"
class="h-32 w-full bg-cover bg-center"
:style="{ backgroundImage: `url(${branding.cover_image_url})` }"
></div>
<p class="mb-6 text-sm">
Hi <span class="font-medium text-zinc-100">{{ access.guest.name }}</span>
<template v-if="existing">change your response below {{ editsRemaining }}
{{ editsRemaining === 1 ? 'edit' : 'edits' }} remaining.</template>
<template v-else>please confirm your response below.</template>
</p>
<div class="p-6">
<div class="mb-3 flex items-center gap-3">
<img
v-if="branding?.logo_url"
:src="branding.logo_url"
alt=""
class="h-10 w-10 rounded object-contain bg-zinc-900"
/>
<div>
<p
class="text-xs uppercase tracking-widest"
:style="branding?.primary_color ? { color: 'var(--brand-primary)' } : undefined"
:class="branding?.primary_color ? '' : 'text-brand-500'"
>
{{ existing ? 'Update your response' : 'Invitation' }}
</p>
<h1 class="text-2xl font-semibold">{{ access.event.name }}</h1>
</div>
</div>
<p class="mb-4 text-sm text-zinc-400">
{{ access.event.venue }} · {{ fmtDate(access.event.event_date) }}
</p>
<p
v-if="greetingMessage"
class="mb-4 rounded-md border border-brand-900/40 bg-brand-500/[0.04] p-3 text-sm text-zinc-300"
>{{ greetingMessage }}</p>
<p class="mb-6 text-sm">
Hi <span class="font-medium text-zinc-100">{{ access.guest.name }}</span>
<template v-if="existing">change your response below {{ editsRemaining }}
{{ editsRemaining === 1 ? 'edit' : 'edits' }} remaining.</template>
<template v-else>please confirm your response below.</template>
</p>
<div class="mb-4">
<label class="label">Response</label>
@@ -294,7 +350,12 @@ const submitLabel = computed(() => {
</div>
<div class="flex items-center gap-3">
<button class="btn-primary flex-1" :disabled="submitting" @click="submit">
<button
class="btn-primary flex-1"
:style="branding?.primary_color ? { background: 'var(--brand-primary)' } : undefined"
:disabled="submitting"
@click="submit"
>
{{ submitLabel }}
</button>
<button v-if="existing" type="button" class="btn-ghost" :disabled="submitting" @click="cancelEditing">
@@ -302,7 +363,8 @@ const submitLabel = computed(() => {
</button>
</div>
<p v-if="submitError" class="mt-3 text-sm text-red-400">{{ submitError }}</p>
<p v-if="submitError" class="mt-3 text-sm text-red-400">{{ submitError }}</p>
</div>
</div>
</section>
</template>
+28 -3
View File
@@ -1,7 +1,17 @@
<script setup lang="ts">
// Sign-up page. Honors `?email=` (pre-fill) and `?redirect=` query params
// so the collaborator-invite flow can hand a user from /invites/<token>
// through signup verify-email login back to /invites/<token>.
// The redirect target survives across the verify-email round-trip via
// sessionStorage (the verify link is server-generated and can't carry it
// without a schema change).
const auth = useAuth()
const route = useRoute()
const email = ref('')
const email = ref(typeof route.query.email === 'string' ? route.query.email : '')
const redirect = computed(() =>
typeof route.query.redirect === 'string' ? route.query.redirect : ''
)
const name = ref('')
const password = ref('')
const acceptTerms = ref(false)
@@ -14,6 +24,11 @@ async function submit() {
submitting.value = true
try {
await auth.signup(email.value, name.value, password.value, acceptTerms.value)
// Park the desired post-verify destination so verify-email.vue can
// resume the flow once the inbox round-trip completes.
if (redirect.value && import.meta.client) {
sessionStorage.setItem('gg.postAuthRedirect', redirect.value)
}
sent.value = true
} catch (e: any) {
error.value = useErrMessage(e, 'Sign-up failed')
@@ -21,6 +36,16 @@ async function submit() {
submitting.value = false
}
}
// Login link target. If we have a redirect carry it through; pre-fill the
// email field too so the user doesn't retype it.
const loginHref = computed(() => {
const q = new URLSearchParams()
if (email.value) q.set('email', email.value)
if (redirect.value) q.set('redirect', redirect.value)
const qs = q.toString()
return qs ? `/login?${qs}` : '/login'
})
</script>
<template>
@@ -34,7 +59,7 @@ async function submit() {
If <span class="text-zinc-200">{{ email }}</span> is reachable, we've sent a verification link.
Click it to finish setting up your account.
</p>
<NuxtLink to="/login" class="btn-ghost mt-4 w-full">Back to sign in</NuxtLink>
<NuxtLink :to="loginHref" class="btn-ghost mt-4 w-full">I've verified sign in</NuxtLink>
</div>
<form v-else class="card space-y-4" @submit.prevent="submit">
@@ -84,7 +109,7 @@ async function submit() {
<p class="mt-6 text-center text-sm text-zinc-400">
Already have an account?
<NuxtLink to="/login" class="text-brand-400 hover:text-brand-300">Sign in</NuxtLink>
<NuxtLink :to="loginHref" class="text-brand-400 hover:text-brand-300">Sign in</NuxtLink>
</p>
</section>
</template>
+17 -2
View File
@@ -1,4 +1,9 @@
<script setup lang="ts">
// Email verification landing. The verification link is server-generated
// and can't carry the original post-verify redirect (e.g. an invite path)
// in its URL signup.vue parks that target in sessionStorage and we read
// it back here to compose a follow-on "Sign in" link that resumes the
// flow.
const auth = useAuth()
const route = useRoute()
@@ -6,7 +11,17 @@ type Status = 'pending' | 'success' | 'error'
const status = ref<Status>('pending')
const error = ref<string | null>(null)
// Computed lazily so the first render (SSR) doesn't touch sessionStorage.
const loginHref = ref('/login')
onMounted(async () => {
if (import.meta.client) {
const parked = sessionStorage.getItem('gg.postAuthRedirect')
if (parked) {
loginHref.value = `/login?redirect=${encodeURIComponent(parked)}`
}
}
const token = route.query.token
if (typeof token !== 'string' || !token) {
status.value = 'error'
@@ -32,12 +47,12 @@ onMounted(async () => {
<template v-else-if="status === 'success'">
<p class="mb-3 font-medium text-brand-300">Email verified.</p>
<p class="mb-4 text-zinc-400">You can now sign in to your account.</p>
<NuxtLink to="/login" class="btn-primary w-full">Sign in</NuxtLink>
<NuxtLink :to="loginHref" class="btn-primary w-full">Sign in</NuxtLink>
</template>
<template v-else>
<p class="mb-3 font-medium text-red-400">We couldn't verify that link.</p>
<p class="mb-4 text-zinc-400">{{ error }}</p>
<NuxtLink to="/login" class="btn-ghost w-full">Back to sign in</NuxtLink>
<NuxtLink :to="loginHref" class="btn-ghost w-full">Back to sign in</NuxtLink>
</template>
</div>
</section>
+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,
})
}
+9
View File
@@ -62,6 +62,12 @@ type Config struct {
StripePriceBusiness string // Stripe Price ID for Business monthly
UnsubscribeSecret string // HMAC key for signing unsubscribe links
// Uploads (Tier 2 Block D). LocalFSStore writes to UploadsDir and
// serves via the API's /uploads/<file> route; in production this is
// a deployment concern (S3 bucket + CDN URL).
UploadsDir string
UploadsPublicURL string
}
func Load() (*Config, error) {
@@ -114,6 +120,9 @@ func Load() (*Config, error) {
StripePriceBusiness: os.Getenv("GG_STRIPE_PRICE_BUSINESS"),
UnsubscribeSecret: os.Getenv("GG_UNSUBSCRIBE_SECRET"),
UploadsDir: getenv("GG_UPLOADS_DIR", "/var/lib/guestguard/uploads"),
UploadsPublicURL: getenv("GG_UPLOADS_PUBLIC_URL", "http://localhost:8080/uploads"),
}
if cfg.Env == "production" && cfg.TokenSecret == "" {
+73
View File
@@ -0,0 +1,73 @@
package domain
import (
"errors"
"regexp"
"time"
"github.com/google/uuid"
)
// Branding is one event's visual customisation. All fields are optional —
// a brand-new event renders with the GuestGuard defaults until the host
// fills any of these in. Tier 2 Block D.
type Branding struct {
EventID uuid.UUID `json:"event_id"`
PrimaryColor *string `json:"primary_color,omitempty"`
AccentColor *string `json:"accent_color,omitempty"`
LogoURL *string `json:"logo_url,omitempty"`
CoverImageURL *string `json:"cover_image_url,omitempty"`
FontFamily *string `json:"font_family,omitempty"`
GreetingMessage *string `json:"greeting_message,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
// AllowedFonts is the curated picker list the host can choose from. Locking
// it down keeps render times sane (no hot-loading arbitrary @font-face
// files) and avoids smuggling untrusted CSS into our emails.
var AllowedFonts = []string{
"Inter",
"Playfair Display",
"Cormorant Garamond",
"Lora",
"DM Sans",
"Manrope",
}
// IsAllowedFont reports whether `f` is in the curated set. Empty string is
// fine — the RSVP page falls back to its default.
func IsAllowedFont(f string) bool {
if f == "" {
return true
}
for _, a := range AllowedFonts {
if f == a {
return true
}
}
return false
}
// hexColorRe matches #abc, #abcd, #aabbcc, #aabbccdd (alpha optional).
// Lowercase + uppercase OK. Length checked because Go regexp + Postgres
// don't agree on Unicode digits and we want plain ASCII here.
var hexColorRe = regexp.MustCompile(`^#([0-9A-Fa-f]{3,8})$`)
// IsValidHexColor accepts the three common hex shorthand forms. Empty is OK
// (clears the column).
func IsValidHexColor(c string) bool {
if c == "" {
return true
}
if !hexColorRe.MatchString(c) {
return false
}
n := len(c) - 1
return n == 3 || n == 4 || n == 6 || n == 8
}
var (
ErrBrandingNotFound = errors.New("branding not found")
ErrInvalidColor = errors.New("color must be a hex value (e.g. #22c55e)")
ErrUnknownFont = errors.New("font is not in the allowlist")
)
+38
View File
@@ -0,0 +1,38 @@
package domain
import "testing"
func TestIsValidHexColor(t *testing.T) {
cases := map[string]bool{
"": true, // clears the field
"#22c55e": true,
"#22C55E": true,
"#abc": true,
"#abcd": true,
"#aabbccdd": true,
"22c55e": false, // missing #
"#": false,
"#xyz": false,
"#aabbccddee": false, // too long
"#ab": false, // too short
"rgb(0,0,0)": false,
}
for in, want := range cases {
if got := IsValidHexColor(in); got != want {
t.Errorf("IsValidHexColor(%q) = %v, want %v", in, got, want)
}
}
}
func TestIsAllowedFont(t *testing.T) {
for _, ok := range []string{"", "Inter", "Playfair Display"} {
if !IsAllowedFont(ok) {
t.Errorf("expected %q to be allowed", ok)
}
}
for _, bad := range []string{"Comic Sans", "Arial", "javascript:alert(1)"} {
if IsAllowedFont(bad) {
t.Errorf("expected %q to be rejected", bad)
}
}
}
+118
View File
@@ -0,0 +1,118 @@
package storage
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/alchemistkay/guestguard/internal/domain"
)
// BrandingRepo holds the per-event customisation row. Updates are upserts —
// a host's first PATCH to the branding endpoint inserts the row, subsequent
// PATCHes update only the fields the host sent. Tier 2 Block D.
type BrandingRepo struct {
pool *pgxpool.Pool
}
func NewBrandingRepo(db *DB) *BrandingRepo {
return &BrandingRepo{pool: db.Pool}
}
// Get returns the branding row for `eventID`, or ErrBrandingNotFound when
// the event has no customisation yet. The caller should render the default
// theme in that case — a missing row isn't an error condition.
func (r *BrandingRepo) Get(ctx context.Context, eventID uuid.UUID) (*domain.Branding, error) {
const q = `
SELECT event_id, primary_color, accent_color, logo_url,
cover_image_url, font_family, greeting_message, updated_at
FROM event_branding WHERE event_id = $1
`
var b domain.Branding
err := r.pool.QueryRow(ctx, q, eventID).Scan(
&b.EventID, &b.PrimaryColor, &b.AccentColor, &b.LogoURL,
&b.CoverImageURL, &b.FontFamily, &b.GreetingMessage, &b.UpdatedAt,
)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, domain.ErrBrandingNotFound
}
return nil, err
}
return &b, nil
}
// UpsertParams holds the patchable fields. Nil pointers leave the existing
// value untouched on update; empty strings clear the column to NULL (so
// hosts can revert to defaults without deleting the whole row).
type UpsertBrandingParams struct {
EventID uuid.UUID
PrimaryColor *string
AccentColor *string
LogoURL *string
CoverImageURL *string
FontFamily *string
GreetingMessage *string
}
// Upsert inserts or partially updates the branding row. The COALESCE +
// NULLIF idiom in the UPDATE branch means a nil pointer maps to NULL in
// SQL and is coalesced away (= keep existing), while an empty string is
// kept as-is and stored as NULL (= clear). That lets the API support both
// "no change" and "reset to default" cleanly.
func (r *BrandingRepo) Upsert(ctx context.Context, p UpsertBrandingParams) (*domain.Branding, error) {
const q = `
INSERT INTO event_branding (
event_id, primary_color, accent_color, logo_url,
cover_image_url, font_family, greeting_message, updated_at
)
VALUES (
$1, NULLIF($2, ''), NULLIF($3, ''), NULLIF($4, ''),
NULLIF($5, ''), NULLIF($6, ''), NULLIF($7, ''), now()
)
ON CONFLICT (event_id) DO UPDATE SET
primary_color = COALESCE($2, event_branding.primary_color),
accent_color = COALESCE($3, event_branding.accent_color),
logo_url = COALESCE($4, event_branding.logo_url),
cover_image_url = COALESCE($5, event_branding.cover_image_url),
font_family = COALESCE($6, event_branding.font_family),
greeting_message = COALESCE($7, event_branding.greeting_message),
updated_at = now()
RETURNING event_id, primary_color, accent_color, logo_url,
cover_image_url, font_family, greeting_message, updated_at
`
// Convert "" → NULL handling: we pass the same *string into both
// COALESCE (the keep-existing path) and NULLIF (the reset path). The
// caller passes nil to mean "leave alone" — we surface that as NULL
// pgx side which COALESCE swallows.
var b domain.Branding
err := r.pool.QueryRow(ctx, q,
p.EventID,
nilOrPtr(p.PrimaryColor),
nilOrPtr(p.AccentColor),
nilOrPtr(p.LogoURL),
nilOrPtr(p.CoverImageURL),
nilOrPtr(p.FontFamily),
nilOrPtr(p.GreetingMessage),
).Scan(
&b.EventID, &b.PrimaryColor, &b.AccentColor, &b.LogoURL,
&b.CoverImageURL, &b.FontFamily, &b.GreetingMessage, &b.UpdatedAt,
)
if err != nil {
return nil, err
}
return &b, nil
}
// nilOrPtr passes nil through as nil (pgx → NULL); otherwise unwraps the
// string so we get a TEXT param instead of pgx receiving a *string and
// double-wrapping it.
func nilOrPtr(s *string) any {
if s == nil {
return nil
}
return *s
}
+142
View File
@@ -195,6 +195,33 @@ func assertNotLastOwner(ctx context.Context, tx pgx.Tx, eventID uuid.UUID) error
return nil
}
// RolesForUser returns a map of event_id → role for every event the user
// has any accepted role on. Used by GET /events so the dashboard can
// split "your events" from "shared with you" without making N queries
// (one per event card).
func (r *CollaboratorRepo) RolesForUser(ctx context.Context, userID uuid.UUID) (map[uuid.UUID]domain.Role, error) {
rows, err := r.pool.Query(ctx, `
SELECT event_id, role FROM event_collaborators
WHERE user_id = $1 AND accepted_at IS NOT NULL
`, userID)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[uuid.UUID]domain.Role{}
for rows.Next() {
var (
id uuid.UUID
role domain.Role
)
if err := rows.Scan(&id, &role); err != nil {
return nil, err
}
out[id] = role
}
return out, rows.Err()
}
// ListEventIDsForUser returns the set of event IDs the user has any accepted
// role on. Used by GET /events to widen the dashboard list beyond just
// `events.host_id = userID`.
@@ -341,6 +368,121 @@ func (r *CollaboratorRepo) AcceptInvite(
return tx.Commit(ctx)
}
// PendingInviteForUser is one pending invitation in a user's inbox-style
// list: their own dashboard's "you've been invited" banner. We surface the
// event name + inviter name here so the frontend renders one card per
// invite without N follow-up lookups.
type PendingInviteForUser struct {
EventID uuid.UUID `json:"event_id"`
EventName string `json:"event_name"`
Role domain.Role `json:"role"`
InvitedBy uuid.UUID `json:"invited_by"`
InviterName string `json:"inviter_name"`
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
}
// ListPendingForEmail returns every unconsumed, non-expired invite addressed
// to `email`. The most recent invite per (email, event) wins — older
// duplicates are squashed so the user sees one card per event even if the
// owner re-sent the invitation. Drives the dashboard banner that lets a
// just-signed-in user accept without re-clicking the email link.
func (r *InviteRepo) ListPendingForEmail(ctx context.Context, email string) ([]PendingInviteForUser, error) {
email = strings.ToLower(strings.TrimSpace(email))
rows, err := r.pool.Query(ctx, `
SELECT DISTINCT ON (ci.event_id)
ci.event_id, e.name, ci.role, ci.invited_by,
COALESCE(u.name, '') AS inviter_name,
ci.expires_at, ci.created_at
FROM collaborator_invites ci
JOIN events e ON e.id = ci.event_id
LEFT JOIN users u ON u.id = ci.invited_by
WHERE lower(ci.email) = $1
AND ci.consumed_at IS NULL
AND ci.expires_at > now()
ORDER BY ci.event_id, ci.created_at DESC
`, email)
if err != nil {
return nil, err
}
defer rows.Close()
out := []PendingInviteForUser{}
for rows.Next() {
var p PendingInviteForUser
if err := rows.Scan(
&p.EventID, &p.EventName, &p.Role, &p.InvitedBy,
&p.InviterName, &p.ExpiresAt, &p.CreatedAt,
); err != nil {
return nil, err
}
out = append(out, p)
}
return out, rows.Err()
}
// AcceptByEventAndEmail finds the latest pending invite for (email, eventID)
// and atomically consumes it + inserts the collaborator row. Used by the
// dashboard "Accept" button — the user authenticates with their session,
// and we match by email so the cross-tab signup flow doesn't need the raw
// token. Returns ErrInviteNotFound when no matching invite is pending.
func (r *CollaboratorRepo) AcceptByEventAndEmail(
ctx context.Context,
eventID uuid.UUID,
email string,
userID uuid.UUID,
) (domain.Role, error) {
email = strings.ToLower(strings.TrimSpace(email))
tx, err := r.pool.Begin(ctx)
if err != nil {
return "", err
}
defer tx.Rollback(ctx)
// Lock the latest matching invite so two concurrent accepts can't
// both consume the same row.
var (
tokenHash string
role domain.Role
invitedBy uuid.UUID
)
err = tx.QueryRow(ctx, `
SELECT token_hash, role, invited_by
FROM collaborator_invites
WHERE event_id = $1
AND lower(email) = $2
AND consumed_at IS NULL
AND expires_at > now()
ORDER BY created_at DESC
LIMIT 1
FOR UPDATE
`, eventID, email).Scan(&tokenHash, &role, &invitedBy)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return "", domain.ErrInviteNotFound
}
return "", err
}
if _, err := tx.Exec(ctx, `
UPDATE collaborator_invites
SET consumed_at = now()
WHERE token_hash = $1
`, tokenHash); err != nil {
return "", err
}
if _, err := tx.Exec(ctx, `
INSERT INTO event_collaborators (event_id, user_id, role, invited_by, invited_at, accepted_at)
VALUES ($1, $2, $3, $4, now(), now())
ON CONFLICT (event_id, user_id) DO NOTHING
`, eventID, userID, role, invitedBy); err != nil {
return "", err
}
if err := tx.Commit(ctx); err != nil {
return "", err
}
return role, nil
}
// ListPendingForEvent returns invitations the host hasn't seen accepted yet,
// shown alongside accepted collaborators on the Team tab.
func (r *InviteRepo) ListPendingForEvent(ctx context.Context, eventID uuid.UUID) ([]domain.CollaboratorInvite, error) {
@@ -0,0 +1 @@
DROP TABLE IF EXISTS event_branding;
@@ -0,0 +1,17 @@
-- Tier 2 Block D — event branding.
--
-- Per-event customisation of the RSVP page and outbound emails. The
-- custom-domain sub-block was deferred to Tier 3 (the application surface
-- is small but ingress + automatic TLS provisioning isn't — see
-- TIER2_PLAN.md open question #1).
CREATE TABLE IF NOT EXISTS event_branding (
event_id UUID PRIMARY KEY REFERENCES events(id) ON DELETE CASCADE,
primary_color TEXT,
accent_color TEXT,
logo_url TEXT,
cover_image_url TEXT,
font_family TEXT,
greeting_message TEXT,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+143
View File
@@ -0,0 +1,143 @@
// Package uploads handles image uploads for the branding flow (Tier 2 Block D).
//
// In dev we write to the local filesystem and serve via a dedicated HTTP
// handler; in production the same interface should be backed by S3 + CDN
// (left as a deployment task, not application code — same split the project
// uses for backups and DB infra).
//
// Validation philosophy: never trust the Content-Type header from the
// client. We decode the bytes through Go's image stdlib and re-encode them
// to a known format. That strips EXIF, normalises the byte stream, and
// turns a "spoof an exe as a PNG" attempt into a decode error instead of a
// stored payload.
package uploads
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"image"
// Register the standard decoders so image.Decode recognises jpeg/png.
"image/jpeg"
"image/png"
"io"
"os"
"path/filepath"
"strings"
)
// MaxUploadBytes caps every accepted upload. 2 MB covers logos + cover
// photos comfortably; the host's browser usually scales further when the
// page actually renders.
const MaxUploadBytes = 2 * 1024 * 1024
// Format names normalised post-decode. Anything else we reject.
const (
FormatJPEG = "jpeg"
FormatPNG = "png"
)
// ImageStore is the production seam. LocalFSStore is the dev impl; a future
// S3Store will satisfy the same interface so handlers don't change.
type ImageStore interface {
// Save persists the (re-encoded) bytes under a fresh random key and
// returns the public URL the frontend should reference.
Save(ctx context.Context, body []byte, format string) (publicURL string, err error)
// FilePath maps a publicly-served filename back to a local path so the
// dev HTTP handler can stream it. S3 impls would return "" + an error
// (their URLs hit the CDN directly, not the API).
FilePath(filename string) (string, error)
}
// LocalFSStore writes each upload to a flat directory on disk. Filenames
// are 16 hex bytes + the canonical extension so two uploads can't collide
// and a guessing attacker has 128 bits to brute-force.
type LocalFSStore struct {
// Dir is the on-disk directory. Created on first call if missing.
Dir string
// PublicBase is the URL prefix the frontend will use to fetch saved
// images, e.g. "http://localhost:8080/uploads". The API exposes a
// matching handler at PublicBase's path.
PublicBase string
}
// Save re-encodes and writes the image to disk. Returns the full public
// URL the host should store in their branding row.
func (s *LocalFSStore) Save(ctx context.Context, body []byte, format string) (string, error) {
if err := os.MkdirAll(s.Dir, 0o755); err != nil {
return "", fmt.Errorf("mkdir uploads: %w", err)
}
ext := ".jpg"
if format == FormatPNG {
ext = ".png"
}
name := randName() + ext
dest := filepath.Join(s.Dir, name)
if err := os.WriteFile(dest, body, 0o644); err != nil {
return "", fmt.Errorf("write upload: %w", err)
}
base := strings.TrimRight(s.PublicBase, "/")
return base + "/" + name, nil
}
// FilePath maps a served filename back to its local path. Refuses any
// path with a separator so we can't be tricked into serving /etc/passwd.
func (s *LocalFSStore) FilePath(filename string) (string, error) {
if filename == "" || strings.ContainsAny(filename, "/\\") || strings.HasPrefix(filename, ".") {
return "", errors.New("invalid upload filename")
}
return filepath.Join(s.Dir, filename), nil
}
// DecodeAndReencode validates `raw` as a recognised image format and
// returns the re-encoded bytes plus the canonical format name. Anything
// that doesn't parse as JPEG/PNG (or that exceeds MaxUploadBytes) returns
// an error.
//
// We deliberately don't trust the Content-Type header here — `image.Decode`
// sniffs the magic bytes. Stripped through the encoder, the output is the
// same image without EXIF / hidden chunks.
func DecodeAndReencode(raw []byte) (out []byte, format string, err error) {
if len(raw) == 0 {
return nil, "", errors.New("empty upload")
}
if len(raw) > MaxUploadBytes {
return nil, "", fmt.Errorf("upload exceeds %d byte limit", MaxUploadBytes)
}
img, gotFormat, err := image.Decode(bytes.NewReader(raw))
if err != nil {
return nil, "", fmt.Errorf("not a recognised image: %w", err)
}
var buf bytes.Buffer
switch gotFormat {
case "jpeg":
format = FormatJPEG
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 88}); err != nil {
return nil, "", fmt.Errorf("re-encode jpeg: %w", err)
}
case "png":
format = FormatPNG
if err := png.Encode(&buf, img); err != nil {
return nil, "", fmt.Errorf("re-encode png: %w", err)
}
default:
return nil, "", fmt.Errorf("unsupported image format %q (jpeg/png only)", gotFormat)
}
return buf.Bytes(), format, nil
}
// PeekReader reads up to MaxUploadBytes+1 from r. We add one byte so the
// caller can tell "exactly at the limit" from "over the limit" without
// pulling the whole body into RAM up front for size-only rejection.
func PeekReader(r io.Reader) ([]byte, error) {
return io.ReadAll(io.LimitReader(r, MaxUploadBytes+1))
}
func randName() string {
var b [16]byte
_, _ = rand.Read(b[:])
return hex.EncodeToString(b[:])
}
+93
View File
@@ -0,0 +1,93 @@
package uploads
import (
"bytes"
"image"
"image/color"
"image/jpeg"
"image/png"
"strings"
"testing"
)
// makePNG and makeJPEG produce a tiny valid image for the round-trip tests.
func makePNG(t *testing.T) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, 4, 4))
img.Set(0, 0, color.RGBA{34, 197, 94, 255})
var b bytes.Buffer
if err := png.Encode(&b, img); err != nil {
t.Fatalf("encode png: %v", err)
}
return b.Bytes()
}
func makeJPEG(t *testing.T) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, 4, 4))
img.Set(0, 0, color.RGBA{34, 197, 94, 255})
var b bytes.Buffer
if err := jpeg.Encode(&b, img, &jpeg.Options{Quality: 80}); err != nil {
t.Fatalf("encode jpeg: %v", err)
}
return b.Bytes()
}
func TestDecodeAndReencode_PNG(t *testing.T) {
out, format, err := DecodeAndReencode(makePNG(t))
if err != nil {
t.Fatalf("decode png: %v", err)
}
if format != FormatPNG {
t.Errorf("format: got %q want png", format)
}
// Output must be valid PNG (round-trip decode).
if _, _, err := image.Decode(bytes.NewReader(out)); err != nil {
t.Errorf("re-encoded png is not valid: %v", err)
}
}
func TestDecodeAndReencode_JPEG(t *testing.T) {
out, format, err := DecodeAndReencode(makeJPEG(t))
if err != nil {
t.Fatalf("decode jpeg: %v", err)
}
if format != FormatJPEG {
t.Errorf("format: got %q want jpeg", format)
}
if _, _, err := image.Decode(bytes.NewReader(out)); err != nil {
t.Errorf("re-encoded jpeg is not valid: %v", err)
}
}
func TestDecodeAndReencode_RejectsNonImage(t *testing.T) {
_, _, err := DecodeAndReencode([]byte("hello, world"))
if err == nil {
t.Fatal("expected an error decoding a non-image payload")
}
if !strings.Contains(err.Error(), "not a recognised image") {
t.Errorf("error: got %q want 'not a recognised image'", err)
}
}
func TestDecodeAndReencode_RejectsTooLarge(t *testing.T) {
big := make([]byte, MaxUploadBytes+1)
_, _, err := DecodeAndReencode(big)
if err == nil || !strings.Contains(err.Error(), "exceeds") {
t.Errorf("expected size-limit error, got %v", err)
}
}
func TestLocalFSStore_FilePath_RejectsTraversal(t *testing.T) {
s := &LocalFSStore{Dir: "/tmp/x", PublicBase: "http://localhost/up"}
cases := []string{"../etc/passwd", "a/b.png", "..", ".env"}
for _, in := range cases {
if _, err := s.FilePath(in); err == nil {
t.Errorf("FilePath(%q) should have refused", in)
}
}
// A bare random filename should be accepted.
if _, err := s.FilePath("ok.png"); err != nil {
t.Errorf("FilePath(ok.png) should have accepted: %v", err)
}
}
+255
View File
@@ -0,0 +1,255 @@
//go:build integration
package integration_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"image"
"image/color"
"image/png"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// Tier 2 Block D — branding + uploads.
type brandingResponse struct {
EventID string `json:"event_id"`
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"`
AllowedFonts []string `json:"allowed_fonts"`
}
// TestBrandingGetReturnsDefaults asserts a fresh event with no branding row
// gets a 200 with null fields + the allowed_fonts list.
func TestBrandingGetReturnsDefaults(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in -short mode")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
t.Cleanup(cancel)
srv, _, _, token := setupAuthedAPI(t, ctx)
eventID := createEvent(t, srv.URL, token, "Branding Defaults", "branding-defaults")
var body brandingResponse
getJSONAuthed(t, fmt.Sprintf("%s/events/%s/branding", srv.URL, eventID),
token, http.StatusOK, &body)
if body.PrimaryColor != nil || body.LogoURL != nil {
t.Fatalf("expected null fields on a fresh event: %+v", body)
}
if len(body.AllowedFonts) == 0 {
t.Fatal("expected allowed_fonts list to be populated")
}
}
// TestBrandingPutPersists asserts a PUT round-trips the values + clears
// empty-string fields back to null.
func TestBrandingPutPersists(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in -short mode")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
t.Cleanup(cancel)
srv, _, _, token := setupAuthedAPI(t, ctx)
eventID := createEvent(t, srv.URL, token, "Branding Put", "branding-put")
// First write — sets all fields.
primary := "#22c55e"
accent := "#15803d"
font := "Playfair Display"
greeting := "Welcome!"
putJSON(t, fmt.Sprintf("%s/events/%s/branding", srv.URL, eventID), token,
map[string]any{
"primary_color": primary,
"accent_color": accent,
"font_family": font,
"greeting_message": greeting,
}, http.StatusOK, nil)
// Read back.
var got brandingResponse
getJSONAuthed(t, fmt.Sprintf("%s/events/%s/branding", srv.URL, eventID),
token, http.StatusOK, &got)
if got.PrimaryColor == nil || *got.PrimaryColor != primary {
t.Errorf("primary_color: got %v want %s", got.PrimaryColor, primary)
}
if got.FontFamily == nil || *got.FontFamily != font {
t.Errorf("font_family: got %v want %s", got.FontFamily, font)
}
// Partial PUT — only update greeting; other fields stay.
putJSON(t, fmt.Sprintf("%s/events/%s/branding", srv.URL, eventID), token,
map[string]any{"greeting_message": "Updated!"}, http.StatusOK, nil)
getJSONAuthed(t, fmt.Sprintf("%s/events/%s/branding", srv.URL, eventID),
token, http.StatusOK, &got)
if got.PrimaryColor == nil || *got.PrimaryColor != primary {
t.Errorf("primary_color should persist across partial PUT: got %v", got.PrimaryColor)
}
if got.GreetingMessage == nil || *got.GreetingMessage != "Updated!" {
t.Errorf("greeting_message: got %v", got.GreetingMessage)
}
}
// TestBrandingPutRejectsBadInputs covers the server-side validators.
func TestBrandingPutRejectsBadInputs(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in -short mode")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
t.Cleanup(cancel)
srv, _, _, token := setupAuthedAPI(t, ctx)
eventID := createEvent(t, srv.URL, token, "Branding Validation", "branding-validation")
// Bad colour.
assertStatus(t, http.MethodPut, fmt.Sprintf("%s/events/%s/branding", srv.URL, eventID),
token, map[string]any{"primary_color": "rgb(0,0,0)"}, http.StatusBadRequest)
// Unknown font.
assertStatus(t, http.MethodPut, fmt.Sprintf("%s/events/%s/branding", srv.URL, eventID),
token, map[string]any{"font_family": "Comic Sans"}, http.StatusBadRequest)
// Logo URL not on our /uploads/ path → rejected to prevent
// arbitrary-origin <img> smuggling.
assertStatus(t, http.MethodPut, fmt.Sprintf("%s/events/%s/branding", srv.URL, eventID),
token, map[string]any{"logo_url": "https://evil.example/x.png"}, http.StatusBadRequest)
}
// TestUploadAndServeImage walks the full upload + retrieve loop: POST a
// PNG, get a URL back, fetch that URL and verify the bytes parse as PNG.
func TestUploadAndServeImage(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in -short mode")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
t.Cleanup(cancel)
// Override the upload dir to a temp path so tests don't litter the
// real volume. The setup function reads env so we set it before
// constructing the API.
tmp := t.TempDir()
t.Setenv("GG_UPLOADS_DIR", tmp)
t.Setenv("GG_UPLOADS_PUBLIC_URL", "http://127.0.0.1:0/uploads") // overwritten below
srv, _, _, token := setupAuthedAPI(t, ctx)
// Encode a tiny PNG to upload.
img := image.NewRGBA(image.Rect(0, 0, 4, 4))
img.Set(0, 0, color.RGBA{34, 197, 94, 255})
var pngBuf bytes.Buffer
if err := png.Encode(&pngBuf, img); err != nil {
t.Fatalf("encode png: %v", err)
}
var body bytes.Buffer
mw := multipart.NewWriter(&body)
fw, err := mw.CreateFormFile("file", "logo.png")
must(t, err, "create form file")
_, _ = fw.Write(pngBuf.Bytes())
must(t, mw.Close(), "close mw")
req, err := http.NewRequest(http.MethodPost, srv.URL+"/uploads/image", &body)
must(t, err, "build req")
req.Header.Set("Content-Type", mw.FormDataContentType())
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
must(t, err, "do upload")
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
b, _ := io.ReadAll(resp.Body)
t.Fatalf("upload status=%d body=%s", resp.StatusCode, b)
}
var out struct{ URL string `json:"url"` }
must(t, json.NewDecoder(resp.Body).Decode(&out), "decode upload resp")
if out.URL == "" {
t.Fatal("empty URL in upload response")
}
// Sanity: the file landed on disk.
entries, err := os.ReadDir(tmp)
must(t, err, "read uploads dir")
if len(entries) == 0 {
t.Fatal("no files written to uploads dir")
}
_ = filepath.Base(out.URL)
// Now fetch it. The URL was built against the configured public base,
// which the test override points at 127.0.0.1:0 — replace the host
// with the actual test server host so we can pull the file.
path := "/uploads/" + filepath.Base(out.URL)
gotResp, err := http.Get(srv.URL + path)
must(t, err, "fetch upload")
defer gotResp.Body.Close()
if gotResp.StatusCode != http.StatusOK {
t.Fatalf("fetch status=%d", gotResp.StatusCode)
}
if ct := gotResp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "image/") {
t.Errorf("content-type: %q", ct)
}
gotBytes, err := io.ReadAll(gotResp.Body)
must(t, err, "read upload bytes")
if _, _, err := image.Decode(bytes.NewReader(gotBytes)); err != nil {
t.Errorf("fetched bytes do not decode as image: %v", err)
}
}
// TestUploadRejectsNonImage confirms a text body is rejected at the API.
func TestUploadRejectsNonImage(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in -short mode")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
t.Cleanup(cancel)
tmp := t.TempDir()
t.Setenv("GG_UPLOADS_DIR", tmp)
srv, _, _, token := setupAuthedAPI(t, ctx)
req, err := http.NewRequest(http.MethodPost, srv.URL+"/uploads/image",
bytes.NewReader([]byte("just some text, not an image")))
must(t, err, "build req")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
must(t, err, "do upload")
defer resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
b, _ := io.ReadAll(resp.Body)
t.Fatalf("expected 400, got %d body=%s", resp.StatusCode, b)
}
}
// --- helpers ---
func putJSON(t *testing.T, url, bearer string, body any, wantStatus int, out any) {
t.Helper()
b, _ := json.Marshal(body)
req, err := http.NewRequest(http.MethodPut, url, bytes.NewReader(b))
must(t, err, "build req")
req.Header.Set("Content-Type", "application/json")
if bearer != "" {
req.Header.Set("Authorization", "Bearer "+bearer)
}
resp, err := http.DefaultClient.Do(req)
must(t, err, "do put")
defer resp.Body.Close()
if resp.StatusCode != wantStatus {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("PUT %s status=%d want=%d body=%s", url, resp.StatusCode, wantStatus, body)
}
if out != nil {
must(t, json.NewDecoder(resp.Body).Decode(out), "decode put resp")
}
}
+7
View File
@@ -11,6 +11,7 @@ import (
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
@@ -142,6 +143,10 @@ func setupAuthedAPI(t *testing.T, ctx context.Context) (srv *httptest.Server, db
t.Cleanup(db.Close)
must(t, db.Migrate(ctx), "migrate")
// Block D — branding test pulls GG_UPLOADS_DIR from env to control
// the on-disk location of uploaded images. Other tests don't care,
// so an empty value (the default) leaves uploads disabled (POST
// /uploads/image returns 503) and the rest of the server still works.
apiSrv, err := api.NewServer(api.ServerDeps{
Logger: logger,
DB: db,
@@ -153,6 +158,8 @@ func setupAuthedAPI(t *testing.T, ctx context.Context) (srv *httptest.Server, db
EmailVerificationTTL: 1 * time.Hour,
PasswordResetTTL: 1 * time.Hour,
PublicBaseURL: "http://localhost",
UploadsDir: os.Getenv("GG_UPLOADS_DIR"),
UploadsPublicURL: os.Getenv("GG_UPLOADS_PUBLIC_URL"),
})
must(t, err, "build api server")
srv = httptest.NewServer(apiSrv.Handler())