feat: ship Tier 1 — auth, authz, rate limits, real notifications, CSV import, billing, backups/DR, privacy

Closes every block in docs/TIER1_PLAN.md from the Claude-scope side. The
homelab / cloud setup steps (SES verification, restore drill, lawyer-
drafted ToS) remain operator-owned but are unblocked.

Block A — Authentication
- Migration 0003: password_hash, email_verified, email_verification_tokens,
  password_reset_tokens, refresh_tokens (with replaced_by family chain).
- Bcrypt hasher, HS256 JWT signer, single-use refresh tokens with rotation
  + replay-detection (revokes the family on reuse).
- /auth/signup, /login, /refresh, /logout, /verify-email,
  /forgot-password, /reset-password — enumeration-safe.
- requireAuth middleware + GET /me.
- Frontend useAuth/useApi with auto-refresh-on-401, login/signup/verify/
  forgot/reset pages, route-guard middleware.

Block B — Authorisation
- EventRepo.GetForHost; Update/Delete scoped by host_id.
- All host routes behind requireAuth + ownership; cross-tenant returns
  404 (no enumeration). ?host_id removed.
- WS auth via short-lived single-use tickets (POST /auth/ws-ticket).
- Tests: TestCrossTenantIsolation — 9 probes.

Block C — Rate limiting
- Redis sliding-window via Lua (atomic ZADD+ZCARD+PEXPIRE).
- Per-route limits matching the plan (signup IP, login IP+email, RSVP/
  access by token, events/guests/tokens by user_id).
- 429 with Retry-After header and JSON body.
- Auth lockout: 5 failed logins → account locked, only password reset
  clears it.
- Frontend: useErrMessage normalises 429 + locked messaging.

Block D — Real notifications
- Migration 0004: provider_message_id, bounce_type, complained columns
  + unsubscribes (CITEXT) suppression table.
- Branded HTML + plaintext templates for verification, reset, invitation,
  confirmation, reminder. Per-page templates avoid html/template's
  contextual-escape collisions.
- Senders: SESv2, Twilio (SMS), SMTP (Mailpit-friendly), Resend HTTP.
- PickEmailSender priority Resend > SMTP > SES > Log — system boots
  cleanly in dev with Mailpit; production flips one env var.
- Webhook endpoints (Twilio status + SES SNS) — bounces add to suppression;
  signature verification stubbed pending creds.
- Auto-send: POST /tokens publishes invitation.send; notifier renders +
  delivers via the configured backend; suppression list honoured.
- Bulk + per-row invitation flow: POST /events/{id}/guests/invitations/bulk
  returns per-guest tokens so phone-only guests can be SMS'd manually.
- Unsubscribe: signed HMAC token (no TTL) + /unsubscribe/[token] page.
- WhatsApp Option A+: wa.me click-to-chat wizard with per-guest progress
  tracking, isLikelyE164 validation, edit-from-wizard.
- Token rotate (POST /tokens/rotate) invalidates the old URL — used by
  the regenerate-link flow.
- Mailpit added to docker-compose for dev inbox.

Block E — CSV import
- Streaming parser: tolerant header detection, UTF-8 BOM + UTF-16 LE/BE
  decoding, row-level validation, 5,000-row cap.
- Strict E.164 phone validation with helpful error message.
- POST /preview + /import + GET /template; preview UI on event page;
  atomic per-batch with dedup on existing emails.

Phone capture across UI
- PhoneInput component: country picker (~50 ISO codes) + national input +
  live E.164 preview + inline length validation.
- Used in Add Guest and Edit Guest modals. Smart paste-handling extracts
  country code from full E.164 strings.

Block F — Billing (Stripe)
- Migration 0005: subscriptions table (user_id → tier/status/period_end +
  Stripe customer/sub ids). Partial unique index keeps one granting sub
  per user.
- internal/billing: Tier + Limits model (Free 1/50, Pro 10/1000, Business
  ∞/5000), Stripe SDK wrapper with IgnoreAPIVersionMismatch for newer
  account API versions.
- /billing/checkout-session, /billing/portal, /billing/status,
  /webhooks/stripe (signature-verified, lifecycle events).
- Tier enforcement: 402 on POST /events, /guests, /import with
  {error, reason, tier, used, limit, upgrade_url} body.
- Frontend: useBilling composable, /dashboard/billing page (current plan,
  usage bars, tier cards), global UpgradeModal triggered by useApi's
  402 interceptor.
- Customer portal kept for self-service cancel/payment-method changes.

Block G — Backups & DR (application side)
- Every migration has a tested .down.sql.
- TestMigrationRoundtrip applies all ups → all downs → all ups against a
  fresh container; catches asymmetric down migrations.
- cmd/restore-verify: 28-check post-restore invariant tool (schema
  presence, no orphans across 10 FK relationships, email uniqueness,
  single-active subscription, row-count snapshot).
- docs/RUNBOOK_RESTORE.md: 9-step restore procedure with RTO/RPO
  targets, drill instructions, rollback path.

Block H — Privacy compliance (application side)
- Migration 0006: deleted_at + terms_accepted_at + privacy_policy_accepted_at
  on users. Partial index on email for live-only uniqueness.
- GET /me/data-export — synchronous JSON dump (user, events, guests,
  tokens, rsvps, access_logs, notifications).
- DELETE /me — soft-delete with PII scrub + refresh-token revocation;
  re-signup with same email works.
- POST /me/accept-terms — idempotent consent recording.
- Frontend /privacy + /terms placeholder pages with substantive (pending
  legal review) copy; footer links; signup terms checkbox; TermsGateModal
  for accounts created before the rollout; export + delete buttons on
  /dashboard/billing.

Tests
- All migrations verified up/down/up.
- Integration suite: TestE2EHappyPath, TestAuthFlow, TestCrossTenantIsolation,
  TestRateLimitSignup, TestLoginLockout, TestUnsubscribeFlow,
  TestSESBounceWebhook, TestTwilioStatusWebhook, TestCsvImportFlow,
  TestCsvImportAtomicRollback, TestBulkIssueInvitations, TestBulkIssueExplicitSubset,
  TestTokenIssuePublishesInvitation, TestTokenIssueWithoutGuestEmailSkipsInvitation,
  TestGuestUpdate, TestGuestDelete, TestTokenRotate, TestSMTPSenderAgainstMailpit,
  TestFreeTierEventLimit, TestFreeTierGuestLimit, TestBusinessTierBypassesLimits,
  TestDataExport, TestDeleteMe, TestAcceptTerms, TestMigrationRoundtrip.
  Full suite runs in ~120s against real Postgres + NATS + Redis + Mailpit.
- Unit suite green across internal/auth, internal/csvimport,
  internal/notification, internal/ratelimit, internal/domain.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Kwaku Danso
2026-05-16 23:54:22 +01:00
parent a0ed34f860
commit 59b8781659
124 changed files with 13702 additions and 445 deletions
+267
View File
@@ -0,0 +1,267 @@
package storage
import (
"context"
"errors"
"net/netip"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/alchemistkay/guestguard/internal/domain"
)
// EmailVerificationRepo manages single-use email verification tokens.
type EmailVerificationRepo struct {
pool *pgxpool.Pool
}
func NewEmailVerificationRepo(db *DB) *EmailVerificationRepo {
return &EmailVerificationRepo{pool: db.Pool}
}
func (r *EmailVerificationRepo) Create(ctx context.Context, userID uuid.UUID, hash string, expiresAt time.Time) error {
_, err := r.pool.Exec(ctx, `
INSERT INTO email_verification_tokens (token_hash, user_id, expires_at)
VALUES ($1, $2, $3)
`, hash, userID, expiresAt)
return err
}
// Consume atomically marks the token as used and returns the owning user_id.
// Returns ErrAuthTokenNotFound / ErrAuthTokenConsumed / ErrAuthTokenExpired.
func (r *EmailVerificationRepo) Consume(ctx context.Context, hash string) (uuid.UUID, error) {
const q = `
UPDATE email_verification_tokens
SET consumed_at = now()
WHERE token_hash = $1
AND consumed_at IS NULL
AND expires_at > now()
RETURNING user_id
`
var uid uuid.UUID
if err := r.pool.QueryRow(ctx, q, hash).Scan(&uid); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return uuid.Nil, classifyAuthTokenLookup(ctx, r.pool,
"SELECT consumed_at, expires_at FROM email_verification_tokens WHERE token_hash=$1",
hash)
}
return uuid.Nil, err
}
return uid, nil
}
// PasswordResetRepo manages single-use password-reset tokens.
type PasswordResetRepo struct {
pool *pgxpool.Pool
}
func NewPasswordResetRepo(db *DB) *PasswordResetRepo {
return &PasswordResetRepo{pool: db.Pool}
}
func (r *PasswordResetRepo) Create(ctx context.Context, userID uuid.UUID, hash string, expiresAt time.Time) error {
_, err := r.pool.Exec(ctx, `
INSERT INTO password_reset_tokens (token_hash, user_id, expires_at)
VALUES ($1, $2, $3)
`, hash, userID, expiresAt)
return err
}
func (r *PasswordResetRepo) Consume(ctx context.Context, hash string) (uuid.UUID, error) {
const q = `
UPDATE password_reset_tokens
SET consumed_at = now()
WHERE token_hash = $1
AND consumed_at IS NULL
AND expires_at > now()
RETURNING user_id
`
var uid uuid.UUID
if err := r.pool.QueryRow(ctx, q, hash).Scan(&uid); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return uuid.Nil, classifyAuthTokenLookup(ctx, r.pool,
"SELECT consumed_at, expires_at FROM password_reset_tokens WHERE token_hash=$1",
hash)
}
return uuid.Nil, err
}
return uid, nil
}
// RefreshTokenRepo manages refresh-token rows. Refresh tokens are rotated:
// every refresh issues a new token and revokes the old one, recording the
// chain in `replaced_by` so we can detect replay (a revoked token being
// presented again triggers a family-wide revocation).
type RefreshTokenRepo struct {
pool *pgxpool.Pool
}
func NewRefreshTokenRepo(db *DB) *RefreshTokenRepo {
return &RefreshTokenRepo{pool: db.Pool}
}
type RefreshToken struct {
Hash string
UserID uuid.UUID
ExpiresAt time.Time
RevokedAt *time.Time
ReplacedBy *string
UserAgent string
IPAddress *netip.Addr
CreatedAt time.Time
}
type CreateRefreshTokenParams struct {
Hash string
UserID uuid.UUID
ExpiresAt time.Time
UserAgent string
IPAddress string
}
func (r *RefreshTokenRepo) Create(ctx context.Context, p CreateRefreshTokenParams) error {
ip := parseIP(p.IPAddress)
_, err := r.pool.Exec(ctx, `
INSERT INTO refresh_tokens (token_hash, user_id, expires_at, user_agent, ip_address)
VALUES ($1, $2, $3, NULLIF($4, ''), $5)
`, p.Hash, p.UserID, p.ExpiresAt, p.UserAgent, ip)
return err
}
func (r *RefreshTokenRepo) Get(ctx context.Context, hash string) (*RefreshToken, error) {
const q = `
SELECT token_hash, user_id, expires_at, revoked_at, replaced_by,
COALESCE(user_agent, ''), host(ip_address), created_at
FROM refresh_tokens WHERE token_hash = $1
`
var rt RefreshToken
var ipText *string
if err := r.pool.QueryRow(ctx, q, hash).Scan(
&rt.Hash, &rt.UserID, &rt.ExpiresAt, &rt.RevokedAt, &rt.ReplacedBy,
&rt.UserAgent, &ipText, &rt.CreatedAt,
); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, domain.ErrAuthTokenNotFound
}
return nil, err
}
if ipText != nil && *ipText != "" {
if addr, err := netip.ParseAddr(*ipText); err == nil {
rt.IPAddress = &addr
}
}
return &rt, nil
}
// Rotate atomically (in a transaction) marks the old token revoked and
// inserts the new one with replaced_by set. Returns ErrAuthTokenNotFound or
// ErrRefreshTokenRevoked if the old token is missing or already revoked.
func (r *RefreshTokenRepo) Rotate(ctx context.Context, oldHash string, next CreateRefreshTokenParams) error {
tx, err := r.pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var revokedAt *time.Time
var userID uuid.UUID
var expiresAt time.Time
err = tx.QueryRow(ctx, `
SELECT user_id, expires_at, revoked_at
FROM refresh_tokens WHERE token_hash = $1 FOR UPDATE
`, oldHash).Scan(&userID, &expiresAt, &revokedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.ErrAuthTokenNotFound
}
return err
}
if revokedAt != nil {
// Replay of a revoked refresh token — revoke the entire family.
if _, err := tx.Exec(ctx, `
UPDATE refresh_tokens SET revoked_at = now()
WHERE user_id = $1 AND revoked_at IS NULL
`, userID); err != nil {
return err
}
if err := tx.Commit(ctx); err != nil {
return err
}
return domain.ErrRefreshTokenRevoked
}
if time.Now().After(expiresAt) {
return domain.ErrAuthTokenExpired
}
if next.UserID != userID {
return errors.New("refresh token user mismatch")
}
ip := parseIP(next.IPAddress)
if _, err := tx.Exec(ctx, `
INSERT INTO refresh_tokens (token_hash, user_id, expires_at, user_agent, ip_address)
VALUES ($1, $2, $3, NULLIF($4, ''), $5)
`, next.Hash, next.UserID, next.ExpiresAt, next.UserAgent, ip); err != nil {
return err
}
if _, err := tx.Exec(ctx, `
UPDATE refresh_tokens SET revoked_at = now(), replaced_by = $2
WHERE token_hash = $1
`, oldHash, next.Hash); err != nil {
return err
}
return tx.Commit(ctx)
}
func (r *RefreshTokenRepo) Revoke(ctx context.Context, hash string) error {
tag, err := r.pool.Exec(ctx, `
UPDATE refresh_tokens SET revoked_at = now()
WHERE token_hash = $1 AND revoked_at IS NULL
`, hash)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrAuthTokenNotFound
}
return nil
}
func (r *RefreshTokenRepo) RevokeAllForUser(ctx context.Context, userID uuid.UUID) error {
_, err := r.pool.Exec(ctx, `
UPDATE refresh_tokens SET revoked_at = now()
WHERE user_id = $1 AND revoked_at IS NULL
`, userID)
return err
}
func parseIP(s string) any {
if s == "" {
return nil
}
addr, err := netip.ParseAddr(s)
if err != nil {
return nil
}
return addr.String()
}
func classifyAuthTokenLookup(ctx context.Context, pool *pgxpool.Pool, q, hash string) error {
var consumedAt *time.Time
var expiresAt time.Time
if err := pool.QueryRow(ctx, q, hash).Scan(&consumedAt, &expiresAt); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return domain.ErrAuthTokenNotFound
}
return err
}
if consumedAt != nil {
return domain.ErrAuthTokenConsumed
}
if time.Now().After(expiresAt) {
return domain.ErrAuthTokenExpired
}
return domain.ErrAuthTokenNotFound
}
+30 -12
View File
@@ -78,6 +78,24 @@ func (r *EventRepo) Get(ctx context.Context, id uuid.UUID) (*domain.Event, error
return ev, nil
}
// GetForHost is the authz-aware variant of Get. It returns ErrEventNotFound
// when the event either doesn't exist or doesn't belong to the host — by
// merging both cases we avoid leaking existence on cross-tenant lookups.
func (r *EventRepo) GetForHost(ctx context.Context, id, hostID uuid.UUID) (*domain.Event, error) {
const q = `
SELECT id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
FROM events WHERE id = $1 AND host_id = $2
`
ev, err := scanEvent(r.pool.QueryRow(ctx, q, id, hostID))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, domain.ErrEventNotFound
}
return nil, err
}
return ev, nil
}
func (r *EventRepo) List(ctx context.Context, hostID uuid.UUID, limit, offset int) ([]*domain.Event, error) {
if limit <= 0 || limit > 200 {
limit = 50
@@ -132,18 +150,18 @@ type UpdateEventParams struct {
Status *domain.EventStatus
}
func (r *EventRepo) Update(ctx context.Context, id uuid.UUID, p UpdateEventParams) (*domain.Event, error) {
func (r *EventRepo) Update(ctx context.Context, id, hostID uuid.UUID, p UpdateEventParams) (*domain.Event, error) {
const q = `
UPDATE events SET
name = COALESCE($2, name),
slug = COALESCE($3, slug),
event_date = COALESCE($4, event_date),
venue = COALESCE($5, venue),
max_capacity = COALESCE($6, max_capacity),
settings = COALESCE($7, settings),
status = COALESCE($8, status),
name = COALESCE($3, name),
slug = COALESCE($4, slug),
event_date = COALESCE($5, event_date),
venue = COALESCE($6, venue),
max_capacity = COALESCE($7, max_capacity),
settings = COALESCE($8, settings),
status = COALESCE($9, status),
updated_at = now()
WHERE id = $1
WHERE id = $1 AND host_id = $2
RETURNING id, host_id, name, slug, event_date, venue, max_capacity, settings, status, created_at, updated_at
`
@@ -156,7 +174,7 @@ func (r *EventRepo) Update(ctx context.Context, id uuid.UUID, p UpdateEventParam
settingsJSON = b
}
row := r.pool.QueryRow(ctx, q, id,
row := r.pool.QueryRow(ctx, q, id, hostID,
p.Name, p.Slug, p.EventDate, p.Venue, p.MaxCapacity, settingsJSON, p.Status,
)
ev, err := scanEvent(row)
@@ -173,8 +191,8 @@ func (r *EventRepo) Update(ctx context.Context, id uuid.UUID, p UpdateEventParam
return ev, nil
}
func (r *EventRepo) Delete(ctx context.Context, id uuid.UUID) error {
tag, err := r.pool.Exec(ctx, `DELETE FROM events WHERE id = $1`, id)
func (r *EventRepo) Delete(ctx context.Context, id, hostID uuid.UUID) error {
tag, err := r.pool.Exec(ctx, `DELETE FROM events WHERE id = $1 AND host_id = $2`, id, hostID)
if err != nil {
return err
}
+212
View File
@@ -3,6 +3,8 @@ package storage
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
@@ -88,6 +90,87 @@ func (r *GuestRepo) ListByEvent(ctx context.Context, eventID uuid.UUID, limit, o
return out, rows.Err()
}
// BulkImportRow is one normalised guest in a CSV import batch.
type BulkImportRow struct {
Name string
Email string // empty if absent
Phone string // empty if absent
PlusOnes int
}
// BulkImportResult reports the outcome of a single import call. The
// SkippedEmails slice records the addresses we silently dropped because a
// guest already exists on the event — useful for the success summary.
type BulkImportResult struct {
Added int
Skipped int
SkippedEmails []string
}
// BulkImportGuests inserts up to len(rows) guest rows into the event in a
// single transaction. Rows whose email matches an existing guest on the
// event are skipped (idempotent re-imports). Within the batch, duplicate
// emails after the first are also skipped. Either the entire batch
// commits or none of it does.
//
// Empty email is treated as "no email" and not deduped — those rows
// always insert (the host might be entering phone-only guests).
func (r *GuestRepo) BulkImportGuests(ctx context.Context, eventID uuid.UUID, rows []BulkImportRow) (BulkImportResult, error) {
res := BulkImportResult{}
if len(rows) == 0 {
return res, nil
}
tx, err := r.pool.Begin(ctx)
if err != nil {
return res, err
}
defer tx.Rollback(ctx)
// Fetch existing emails on the event into a set for O(1) dedup.
existing := map[string]struct{}{}
exRows, err := tx.Query(ctx,
`SELECT lower(email) FROM guests WHERE event_id = $1 AND email IS NOT NULL AND email <> ''`,
eventID)
if err != nil {
return res, fmt.Errorf("load existing emails: %w", err)
}
for exRows.Next() {
var e string
if err := exRows.Scan(&e); err != nil {
exRows.Close()
return res, err
}
existing[e] = struct{}{}
}
exRows.Close()
const ins = `
INSERT INTO guests (event_id, name, email, phone, plus_ones)
VALUES ($1, $2, NULLIF($3, ''), NULLIF($4, ''), $5)
`
for _, row := range rows {
email := strings.ToLower(strings.TrimSpace(row.Email))
if email != "" {
if _, dup := existing[email]; dup {
res.Skipped++
res.SkippedEmails = append(res.SkippedEmails, email)
continue
}
existing[email] = struct{}{}
}
if _, err := tx.Exec(ctx, ins, eventID, row.Name, email, row.Phone, row.PlusOnes); err != nil {
return BulkImportResult{}, fmt.Errorf("insert guest %q: %w", row.Name, err)
}
res.Added++
}
if err := tx.Commit(ctx); err != nil {
return BulkImportResult{}, err
}
return res, nil
}
func scanGuest(s rowScanner) (*domain.Guest, error) {
var g domain.Guest
err := s.Scan(
@@ -100,6 +183,135 @@ func scanGuest(s rowScanner) (*domain.Guest, error) {
return &g, nil
}
// UpdateGuestParams patches a guest. Nil fields are left untouched.
// An empty string for Email / Phone clears the column to NULL, matching
// the frontend "clear this field" UX.
type UpdateGuestParams struct {
Name *string
Email *string
Phone *string
PlusOnes *int
}
// Update applies the patch to (guestID, eventID). Event scoping in the
// WHERE clause prevents a host from patching guests on another host's
// event even if they guess the guest_id. Returns ErrGuestNotFound when
// the guest doesn't exist on the event.
func (r *GuestRepo) Update(ctx context.Context, eventID, guestID uuid.UUID, p UpdateGuestParams) (*domain.Guest, error) {
sets := []string{}
args := []any{guestID, eventID}
add := func(col string, val any) {
args = append(args, val)
sets = append(sets, fmt.Sprintf("%s = $%d", col, len(args)))
}
if p.Name != nil {
add("name", strings.TrimSpace(*p.Name))
}
if p.Email != nil {
if strings.TrimSpace(*p.Email) == "" {
sets = append(sets, "email = NULL")
} else {
add("email", strings.ToLower(strings.TrimSpace(*p.Email)))
}
}
if p.Phone != nil {
if strings.TrimSpace(*p.Phone) == "" {
sets = append(sets, "phone = NULL")
} else {
add("phone", strings.TrimSpace(*p.Phone))
}
}
if p.PlusOnes != nil {
add("plus_ones", *p.PlusOnes)
}
if len(sets) == 0 {
return r.Get(ctx, guestID)
}
q := fmt.Sprintf(`
UPDATE guests SET %s
WHERE id = $1 AND event_id = $2
RETURNING id, event_id, name, email, phone, plus_ones, dietary_notes, table_number, created_at
`, strings.Join(sets, ", "))
g, err := scanGuest(r.pool.QueryRow(ctx, q, args...))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, domain.ErrGuestNotFound
}
return nil, err
}
return g, nil
}
// Delete removes a guest from an event. Cascade-deletes any tokens,
// rsvps, access_logs, and notifications tied to the guest. Event scoping
// in the WHERE clause stops cross-tenant deletes.
func (r *GuestRepo) Delete(ctx context.Context, eventID, guestID uuid.UUID) error {
tag, err := r.pool.Exec(ctx,
`DELETE FROM guests WHERE id = $1 AND event_id = $2`,
guestID, eventID)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrGuestNotFound
}
return nil
}
// GuestForInvitation is the minimum data the bulk-invite path needs about
// each candidate. Pulled in a single query joined against tokens so the
// caller knows up-front who's already received an invitation.
type GuestForInvitation struct {
ID uuid.UUID
Name string
Email string // empty when the guest has no email on file
HasToken bool
}
// ListGuestsForInvitation returns every guest on `eventID`, joined with
// the tokens table so the caller can skip guests that already have one.
// When `onlyIDs` is non-nil/non-empty, the result is filtered to that
// subset (used for explicit selection in the bulk-send UI).
func (r *GuestRepo) ListGuestsForInvitation(ctx context.Context, eventID uuid.UUID, onlyIDs []uuid.UUID) ([]GuestForInvitation, error) {
var (
rows pgx.Rows
err error
)
if len(onlyIDs) == 0 {
rows, err = r.pool.Query(ctx, `
SELECT g.id, g.name, COALESCE(g.email,''),
(t.id IS NOT NULL) AS has_token
FROM guests g
LEFT JOIN tokens t ON t.guest_id = g.id
WHERE g.event_id = $1
ORDER BY g.created_at ASC
`, eventID)
} else {
rows, err = r.pool.Query(ctx, `
SELECT g.id, g.name, COALESCE(g.email,''),
(t.id IS NOT NULL) AS has_token
FROM guests g
LEFT JOIN tokens t ON t.guest_id = g.id
WHERE g.event_id = $1 AND g.id = ANY($2)
ORDER BY g.created_at ASC
`, eventID, onlyIDs)
}
if err != nil {
return nil, err
}
defer rows.Close()
var out []GuestForInvitation
for rows.Next() {
var g GuestForInvitation
if err := rows.Scan(&g.ID, &g.Name, &g.Email, &g.HasToken); err != nil {
return nil, err
}
out = append(out, g)
}
return out, rows.Err()
}
// GuestWithRSVP is the dashboard view: a guest plus the RSVP submitted
// against their token, if any. RSVP fields are nil when no response yet.
type GuestWithRSVP struct {
@@ -0,0 +1,8 @@
DROP TABLE IF EXISTS refresh_tokens;
DROP TABLE IF EXISTS password_reset_tokens;
DROP TABLE IF EXISTS email_verification_tokens;
ALTER TABLE users
DROP COLUMN IF EXISTS email_verified_at,
DROP COLUMN IF EXISTS email_verified,
DROP COLUMN IF EXISTS password_hash;
@@ -0,0 +1,37 @@
ALTER TABLE users
ADD COLUMN IF NOT EXISTS password_hash TEXT,
ADD COLUMN IF NOT EXISTS email_verified BOOLEAN NOT NULL DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS email_verified_at TIMESTAMPTZ;
CREATE TABLE IF NOT EXISTS email_verification_tokens (
token_hash TEXT PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at TIMESTAMPTZ NOT NULL,
consumed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_email_verification_tokens_user ON email_verification_tokens(user_id);
CREATE TABLE IF NOT EXISTS password_reset_tokens (
token_hash TEXT PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at TIMESTAMPTZ NOT NULL,
consumed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_password_reset_tokens_user ON password_reset_tokens(user_id);
CREATE TABLE IF NOT EXISTS refresh_tokens (
token_hash TEXT PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at TIMESTAMPTZ NOT NULL,
revoked_at TIMESTAMPTZ,
replaced_by TEXT REFERENCES refresh_tokens(token_hash) ON DELETE SET NULL,
user_agent TEXT,
ip_address INET,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user_active ON refresh_tokens(user_id) WHERE revoked_at IS NULL;
@@ -0,0 +1,8 @@
DROP TABLE IF EXISTS unsubscribes;
ALTER TABLE notifications
DROP COLUMN IF EXISTS complained,
DROP COLUMN IF EXISTS bounce_type,
DROP COLUMN IF EXISTS provider_message_id;
DROP INDEX IF EXISTS idx_notifications_provider_message_id;
@@ -0,0 +1,23 @@
-- Block D — real notifications: bounce / complaint tracking + suppression list.
-- The `delivered_at` column already exists from 0001.
CREATE EXTENSION IF NOT EXISTS "citext";
ALTER TABLE notifications
ADD COLUMN IF NOT EXISTS provider_message_id TEXT,
ADD COLUMN IF NOT EXISTS bounce_type TEXT, -- 'permanent' | 'transient' | NULL
ADD COLUMN IF NOT EXISTS complained BOOLEAN NOT NULL DEFAULT FALSE;
CREATE INDEX IF NOT EXISTS idx_notifications_provider_message_id
ON notifications(provider_message_id)
WHERE provider_message_id IS NOT NULL;
-- Suppression list: any email present here gets a silent no-op on send.
-- Populated by bounce / complaint webhooks and by guest-initiated
-- unsubscribe clicks.
CREATE TABLE IF NOT EXISTS unsubscribes (
email CITEXT PRIMARY KEY,
reason TEXT,
source TEXT NOT NULL DEFAULT 'manual', -- 'bounce' | 'complaint' | 'manual' | 'user'
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
@@ -0,0 +1,4 @@
DROP INDEX IF EXISTS idx_subscriptions_subscription;
DROP INDEX IF EXISTS idx_subscriptions_customer;
DROP INDEX IF EXISTS uniq_subscriptions_active_user;
DROP TABLE IF EXISTS subscriptions;
@@ -0,0 +1,30 @@
-- Block F — Stripe subscriptions. One row per Stripe customer + (optional)
-- active subscription. Free-tier hosts never get a row; their tier is
-- inferred at read time.
CREATE TABLE IF NOT EXISTS subscriptions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
stripe_customer_id TEXT NOT NULL,
stripe_subscription_id TEXT,
tier TEXT NOT NULL CHECK (tier IN ('free','pro','business')),
status TEXT NOT NULL CHECK (status IN ('active','past_due','canceled','incomplete','trialing','unpaid')),
current_period_end TIMESTAMPTZ,
cancel_at_period_end BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- A user may have at most one *granting* subscription at a time. We
-- include trialing + past_due because those still convey access (past_due
-- is the grace period before Stripe gives up on the card).
CREATE UNIQUE INDEX IF NOT EXISTS uniq_subscriptions_active_user
ON subscriptions(user_id)
WHERE status IN ('active','past_due','trialing');
CREATE INDEX IF NOT EXISTS idx_subscriptions_customer
ON subscriptions(stripe_customer_id);
CREATE INDEX IF NOT EXISTS idx_subscriptions_subscription
ON subscriptions(stripe_subscription_id)
WHERE stripe_subscription_id IS NOT NULL;
@@ -0,0 +1,6 @@
DROP INDEX IF EXISTS idx_users_active_email;
ALTER TABLE users
DROP COLUMN IF EXISTS privacy_policy_accepted_at,
DROP COLUMN IF EXISTS terms_accepted_at,
DROP COLUMN IF EXISTS deleted_at;
@@ -0,0 +1,20 @@
-- Block H — privacy compliance.
--
-- Adds the columns needed for:
-- - Right to erasure (DELETE /me): soft-delete first, hard-delete via
-- a future cron after a 30-day grace window so an accidental click
-- is recoverable.
-- - Terms / privacy-policy acceptance gate (set on signup; older
-- accounts re-prompted via the frontend on next login).
ALTER TABLE users
ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS terms_accepted_at TIMESTAMPTZ,
ADD COLUMN IF NOT EXISTS privacy_policy_accepted_at TIMESTAMPTZ;
-- Most lookups (login, /me, etc.) want to exclude soft-deleted users.
-- A partial index keeps the active subset fast without bloating writes
-- for the rare deleted rows.
CREATE INDEX IF NOT EXISTS idx_users_active_email
ON users(email)
WHERE deleted_at IS NULL;
+223
View File
@@ -0,0 +1,223 @@
package storage
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// Subscription mirrors the subscriptions table row. Stored as a thin
// projection of the Stripe state — we don't try to mirror every field,
// just what middleware + handlers need to decide access.
type Subscription struct {
ID uuid.UUID
UserID uuid.UUID
StripeCustomerID string
StripeSubscriptionID *string
Tier string
Status string
CurrentPeriodEnd *time.Time
CancelAtPeriodEnd bool
CreatedAt time.Time
UpdatedAt time.Time
}
// ErrSubscriptionNotFound is returned when no row matches the lookup.
var ErrSubscriptionNotFound = errors.New("subscription not found")
type SubscriptionRepo struct {
pool *pgxpool.Pool
}
func NewSubscriptionRepo(db *DB) *SubscriptionRepo {
return &SubscriptionRepo{pool: db.Pool}
}
const subscriptionColumns = `
id, user_id, stripe_customer_id, stripe_subscription_id,
tier, status, current_period_end, cancel_at_period_end,
created_at, updated_at
`
// GetActiveByUser returns the user's currently-granting subscription
// (active / trialing / past_due). Returns ErrSubscriptionNotFound when
// the user has no row at all — caller treats that as free tier.
func (r *SubscriptionRepo) GetActiveByUser(ctx context.Context, userID uuid.UUID) (*Subscription, error) {
const q = `
SELECT ` + subscriptionColumns + `
FROM subscriptions
WHERE user_id = $1
AND status IN ('active','past_due','trialing')
ORDER BY updated_at DESC
LIMIT 1
`
return r.scanOne(ctx, q, userID)
}
// GetByCustomer fetches by Stripe customer id — webhooks use this since
// the event payload identifies the customer, not the user.
func (r *SubscriptionRepo) GetByCustomer(ctx context.Context, customerID string) (*Subscription, error) {
const q = `
SELECT ` + subscriptionColumns + `
FROM subscriptions WHERE stripe_customer_id = $1
ORDER BY updated_at DESC LIMIT 1
`
return r.scanOne(ctx, q, customerID)
}
// FindCustomerID returns the Stripe customer id we've already created
// for this user, or "" if none exists yet. Avoids creating duplicate
// Stripe customers across checkout sessions.
func (r *SubscriptionRepo) FindCustomerID(ctx context.Context, userID uuid.UUID) (string, error) {
const q = `
SELECT stripe_customer_id FROM subscriptions
WHERE user_id = $1 ORDER BY created_at ASC LIMIT 1
`
var id string
if err := r.pool.QueryRow(ctx, q, userID).Scan(&id); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return "", nil
}
return "", err
}
return id, nil
}
// UpsertParams collects everything an upsert needs. Pointer types denote
// "skip writing this column" (used when a webhook only carries partial
// data — we never want to clobber tier or period info we don't have).
type UpsertParams struct {
UserID uuid.UUID
StripeCustomerID string
StripeSubscriptionID *string
Tier *string
Status *string
CurrentPeriodEnd *time.Time
CancelAtPeriodEnd *bool
}
// Upsert inserts a new row or updates an existing one keyed by
// stripe_customer_id. Used by both the checkout-success handler and the
// webhook subscription-lifecycle handler.
func (r *SubscriptionRepo) Upsert(ctx context.Context, p UpsertParams) (*Subscription, error) {
const q = `
INSERT INTO subscriptions (
user_id, stripe_customer_id, stripe_subscription_id,
tier, status, current_period_end, cancel_at_period_end
)
VALUES (
$1, $2, $3,
COALESCE($4, 'free'), COALESCE($5, 'incomplete'),
$6, COALESCE($7, FALSE)
)
ON CONFLICT (id) DO NOTHING
RETURNING ` + subscriptionColumns + `
`
row := r.pool.QueryRow(ctx, q,
p.UserID, p.StripeCustomerID, p.StripeSubscriptionID,
p.Tier, p.Status, p.CurrentPeriodEnd, p.CancelAtPeriodEnd,
)
sub, err := scanSubscription(row)
if err == nil {
return sub, nil
}
if !errors.Is(err, pgx.ErrNoRows) {
return nil, err
}
// Race or duplicate insert — fall back to an explicit update on the
// stripe_customer_id (the FK to Stripe's source of truth).
const upd = `
UPDATE subscriptions SET
stripe_subscription_id = COALESCE($3, stripe_subscription_id),
tier = COALESCE($4, tier),
status = COALESCE($5, status),
current_period_end = COALESCE($6, current_period_end),
cancel_at_period_end = COALESCE($7, cancel_at_period_end),
updated_at = now()
WHERE user_id = $1 AND stripe_customer_id = $2
RETURNING ` + subscriptionColumns + `
`
row = r.pool.QueryRow(ctx, upd,
p.UserID, p.StripeCustomerID, p.StripeSubscriptionID,
p.Tier, p.Status, p.CurrentPeriodEnd, p.CancelAtPeriodEnd,
)
return scanSubscription(row)
}
// UpdateByCustomer patches the subscription row keyed by Stripe customer
// id. Used by webhooks where we have the customer reference but not
// always the user id.
func (r *SubscriptionRepo) UpdateByCustomer(ctx context.Context, customerID string, p UpsertParams) error {
const q = `
UPDATE subscriptions SET
stripe_subscription_id = COALESCE($2, stripe_subscription_id),
tier = COALESCE($3, tier),
status = COALESCE($4, status),
current_period_end = COALESCE($5, current_period_end),
cancel_at_period_end = COALESCE($6, cancel_at_period_end),
updated_at = now()
WHERE stripe_customer_id = $1
`
_, err := r.pool.Exec(ctx, q,
customerID, p.StripeSubscriptionID,
p.Tier, p.Status, p.CurrentPeriodEnd, p.CancelAtPeriodEnd,
)
return err
}
// CountEventsInCurrentMonth returns how many events the user has created
// since the 1st of the current UTC month. Used for free-tier "1 event /
// month" and Pro-tier "10 events / month" enforcement.
func (r *SubscriptionRepo) CountEventsInCurrentMonth(ctx context.Context, userID uuid.UUID) (int, error) {
const q = `
SELECT count(*) FROM events
WHERE host_id = $1
AND created_at >= date_trunc('month', now() AT TIME ZONE 'UTC')
`
var n int
if err := r.pool.QueryRow(ctx, q, userID).Scan(&n); err != nil {
return 0, err
}
return n, nil
}
// CountGuestsByEvent returns the current guest count for an event. Used
// for per-event guest cap enforcement.
func (r *SubscriptionRepo) CountGuestsByEvent(ctx context.Context, eventID uuid.UUID) (int, error) {
var n int
if err := r.pool.QueryRow(ctx,
`SELECT count(*) FROM guests WHERE event_id = $1`, eventID,
).Scan(&n); err != nil {
return 0, err
}
return n, nil
}
func (r *SubscriptionRepo) scanOne(ctx context.Context, q string, args ...any) (*Subscription, error) {
sub, err := scanSubscription(r.pool.QueryRow(ctx, q, args...))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrSubscriptionNotFound
}
return nil, err
}
return sub, nil
}
func scanSubscription(s rowScanner) (*Subscription, error) {
var sub Subscription
if err := s.Scan(
&sub.ID, &sub.UserID, &sub.StripeCustomerID, &sub.StripeSubscriptionID,
&sub.Tier, &sub.Status, &sub.CurrentPeriodEnd, &sub.CancelAtPeriodEnd,
&sub.CreatedAt, &sub.UpdatedAt,
); err != nil {
return nil, err
}
return &sub, nil
}
+32
View File
@@ -60,6 +60,38 @@ func (r *TokenRepo) GetByHash(ctx context.Context, hash string) (*domain.Token,
return tk, nil
}
// RotateForGuest replaces the guest's existing token with a freshly-minted
// one in a single transaction. The old token row is hard-deleted (the
// guests.id UNIQUE constraint requires it, and "the old link must stop
// working" is the point). Cascade-deletes the old access_logs rows that
// reference it via the token_id FK with ON DELETE SET NULL — those rows
// stay, with token_id nulled.
func (r *TokenRepo) RotateForGuest(ctx context.Context, p CreateTokenParams) (*domain.Token, error) {
tx, err := r.pool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
if _, err := tx.Exec(ctx, `DELETE FROM tokens WHERE guest_id = $1`, p.GuestID); err != nil {
return nil, err
}
const q = `
INSERT INTO tokens (guest_id, token_hash, expires_at, status)
VALUES ($1, $2, $3, 'active')
RETURNING id, guest_id, token_hash, expires_at, status, used_at, created_at
`
row := tx.QueryRow(ctx, q, p.GuestID, p.TokenHash, p.ExpiresAt)
tk, err := scanToken(row)
if err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
return tk, nil
}
func (r *TokenRepo) MarkUsed(ctx context.Context, id uuid.UUID) error {
tag, err := r.pool.Exec(ctx, `
UPDATE tokens SET status = 'used', used_at = now()
+141 -9
View File
@@ -5,6 +5,7 @@ import (
"errors"
"strings"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
@@ -20,12 +21,38 @@ func NewUserRepo(db *DB) *UserRepo {
return &UserRepo{pool: db.Pool}
}
func (r *UserRepo) Create(ctx context.Context, email, name string) (*domain.User, error) {
const userColumns = `id, email, name,
COALESCE(password_hash, '') AS password_hash,
email_verified, email_verified_at,
deleted_at,
terms_accepted_at, privacy_policy_accepted_at,
created_at, updated_at`
type CreateUserParams struct {
Email string
Name string
PasswordHash string
AcceptTerms bool // when true, records terms + privacy acceptance now
}
func (r *UserRepo) Create(ctx context.Context, p CreateUserParams) (*domain.User, error) {
const q = `
INSERT INTO users (email, name) VALUES ($1, $2)
RETURNING id, email, name, created_at, updated_at
`
row := r.pool.QueryRow(ctx, q, strings.ToLower(strings.TrimSpace(email)), strings.TrimSpace(name))
INSERT INTO users (
email, name, password_hash,
terms_accepted_at, privacy_policy_accepted_at
)
VALUES (
$1, $2, NULLIF($3, ''),
CASE WHEN $4 THEN now() ELSE NULL END,
CASE WHEN $4 THEN now() ELSE NULL END
)
RETURNING ` + userColumns
row := r.pool.QueryRow(ctx, q,
normaliseEmail(p.Email),
strings.TrimSpace(p.Name),
p.PasswordHash,
p.AcceptTerms,
)
u, err := scanUser(row)
if err != nil {
var pgErr *pgconn.PgError
@@ -37,9 +64,12 @@ func (r *UserRepo) Create(ctx context.Context, email, name string) (*domain.User
return u, nil
}
func (r *UserRepo) GetByEmail(ctx context.Context, email string) (*domain.User, error) {
const q = `SELECT id, email, name, created_at, updated_at FROM users WHERE email = $1`
u, err := scanUser(r.pool.QueryRow(ctx, q, strings.ToLower(strings.TrimSpace(email))))
// GetByID returns an active (non-soft-deleted) user. Soft-deleted users
// are treated as "not found" by the API surface — keeps the deletion
// flow safe by default.
func (r *UserRepo) GetByID(ctx context.Context, id uuid.UUID) (*domain.User, error) {
const q = `SELECT ` + userColumns + ` FROM users WHERE id = $1 AND deleted_at IS NULL`
u, err := scanUser(r.pool.QueryRow(ctx, q, id))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, domain.ErrUserNotFound
@@ -49,10 +79,112 @@ func (r *UserRepo) GetByEmail(ctx context.Context, email string) (*domain.User,
return u, nil
}
// GetByEmail mirrors GetByID — soft-deleted users vanish from email
// lookups (so signup/login don't match a tombstoned record).
func (r *UserRepo) GetByEmail(ctx context.Context, email string) (*domain.User, error) {
const q = `SELECT ` + userColumns + ` FROM users WHERE email = $1 AND deleted_at IS NULL`
u, err := scanUser(r.pool.QueryRow(ctx, q, normaliseEmail(email)))
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, domain.ErrUserNotFound
}
return nil, err
}
return u, nil
}
// SoftDelete marks the user as deleted and clears their PII-bearing
// fields. A nightly cron (TBD in ops) will hard-delete rows older than
// 30 days. Until then the row exists for audit + recovery if the user
// changes their mind.
func (r *UserRepo) SoftDelete(ctx context.Context, id uuid.UUID) error {
tag, err := r.pool.Exec(ctx, `
UPDATE users SET
deleted_at = now(),
updated_at = now(),
-- Tombstone PII so the soft-deleted row can sit for 30 days
-- without holding the user's real email + name in cleartext.
-- The original values are gone from the API surface from the
-- moment SoftDelete returns.
email = 'deleted-' || id::text || '@deleted.local',
name = 'Deleted user',
password_hash = NULL
WHERE id = $1 AND deleted_at IS NULL
`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrUserNotFound
}
return nil
}
// AcceptTerms records that the user has consented to the current terms
// of service and privacy policy. Idempotent — re-accepting just resets
// the timestamp.
func (r *UserRepo) AcceptTerms(ctx context.Context, id uuid.UUID) error {
tag, err := r.pool.Exec(ctx, `
UPDATE users SET
terms_accepted_at = now(),
privacy_policy_accepted_at = now(),
updated_at = now()
WHERE id = $1 AND deleted_at IS NULL
`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrUserNotFound
}
return nil
}
func (r *UserRepo) MarkEmailVerified(ctx context.Context, id uuid.UUID) error {
tag, err := r.pool.Exec(ctx, `
UPDATE users
SET email_verified = TRUE,
email_verified_at = COALESCE(email_verified_at, now()),
updated_at = now()
WHERE id = $1
`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrUserNotFound
}
return nil
}
func (r *UserRepo) UpdatePasswordHash(ctx context.Context, id uuid.UUID, hash string) error {
tag, err := r.pool.Exec(ctx, `
UPDATE users SET password_hash = $2, updated_at = now() WHERE id = $1
`, id, hash)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return domain.ErrUserNotFound
}
return nil
}
func scanUser(s rowScanner) (*domain.User, error) {
var u domain.User
if err := s.Scan(&u.ID, &u.Email, &u.Name, &u.CreatedAt, &u.UpdatedAt); err != nil {
if err := s.Scan(
&u.ID, &u.Email, &u.Name,
&u.PasswordHash,
&u.EmailVerified, &u.EmailVerifiedAt,
&u.DeletedAt,
&u.TermsAcceptedAt, &u.PrivacyPolicyAcceptedAt,
&u.CreatedAt, &u.UpdatedAt,
); err != nil {
return nil, err
}
return &u, nil
}
func normaliseEmail(s string) string {
return strings.ToLower(strings.TrimSpace(s))
}