Author SHA1 Message Date
kiskaadee 30d9a889a3 feat(security): harden authentication edge cases and verify deployment independence
- Reject forged, replayed, and expired CSRF state with HTTP 400 Bad Request
- Enforce cryptographic validation rejecting tampered ID token signatures and mismatched/missing nonces with HTTP 401 Unauthorized
- Reject missing, invalid, or mismatched PKCE code_verifier with HTTP 401 Unauthorized (InvalidCodeVerifierError)
- Invalidate expired ID tokens and session cookies returning HTTP 401 Unauthorized
- Enforce role-based access control blocking authenticated non-admin users from admin APIs with HTTP 403 Forbidden
- Eliminate legacy Remote-User trust ensuring session identity strictly governs authorization
- Document and verify dual deployment modes (Standalone Mode vs Homelab Production Mode behind Traefik TLS proxy)
- Add comprehensive security hardening regression suite (tests/test_security_hardening.py) and .env.example template
- Ensure clean multi-stage Docker build
2026-10-03 01:26:05 -05:00
kiskaadee e1f745608a feat(ui): integrate browser SSO authentication and admin logout
- Integrate React SPA admin layout with OIDC authentication check and unauthenticated login redirection
- Support authenticated session resolution via /birthday/api/auth/me and display user identity in admin navigation bar
- Add working Logout button calling /birthday/api/auth/logout to revoke session, clear HttpOnly cookie, and transition UI to unauthenticated state
- Update auth routes callback target to /birthday/admin and handle GET/POST logout redirects
- Add end-to-end browser acceptance tests using Playwright verifying complete interactive login and logout flow
2026-10-03 01:04:40 -05:00
kiskaadee 39ac42cfce feat(admin): migrate admin routes to group authorization and enforce negative Remote-User barrier
- Migrate all admin endpoints in backend/app/routes/admin.py to consume the group authorization dependency require_admin (bdinvite_admins group)
- Completely purge legacy Remote-User header dependency from admin route implementations and API documentation
- Enforce strict negative barrier rejecting requests containing Remote-User without a valid authenticated session with HTTP 401 Unauthorized
- Enforce access control verification: 401 for anonymous requests, 403 for non-admin authenticated users, 200 for bdinvite_admins members
- Update admin test suite and related fixtures in backend/tests/ to authenticate via session cookies and verify full admin functionality and negative barriers
2026-10-03 00:23:43 -05:00
kiskaadee 27015d0d72 feat(auth): implement FastAPI authentication and group authorization dependencies
- FastAPI dependency injection module in backend/app/auth/dependencies.py with get_current_identity, require_authenticated, and require_group factory
- Application admin policy require_admin = require_group("bdinvite_admins")
- Isolated verification and test suite in backend/tests/test_dependencies.py
2026-10-03 00:12:54 -05:00
kiskaadee 815a5847c6 feat(auth): implement browser session management and fixation protection
- Browser session contract with HttpOnly=True and SameSite
- Configurable Secure cookie flag
- Session fixation barrier rotating session ID on login
- Session lifecycle, expiration, and safe rejection of tampered cookies
- Logout endpoint (/birthday/api/auth/logout) revoking session and clearing cookie (Max-Age=0)
- Unit and integration tests in backend/tests/test_session_management.py
2026-10-02 23:39:59 -05:00
kiskaadee 35be202adc feat(auth): map verified OIDC claims to domain Identity and groups
- Extract standard claims (sub, email, name) and groups mapping into domain Identity model
- Support configurable groups_claim and dotted group_claim_path resolution
- Enforce Identity Origin Integrity in OIDCAuthAdapter against unvalidated request headers
- Verify claims extraction and session flows against pre-seeded live fixture users (admin and guest)
2026-10-02 23:15:16 -05:00
kiskaadee 0a4032a344 feat(auth): implement generic OIDC client with PKCE and cryptographic token verification 2026-10-02 23:03:46 -05:00
kiskaadee df498979d9 feat(auth): define AuthPort protocol and Identity domain model 2026-10-02 22:48:41 -05:00
kiskaadee 42927b9858 fix(admin): display registration timestamps in configured event timezone 2026-10-01 13:53:33 -05:00
kiskaadee 338dc20126 feat(frontend): add RSVP inline editing, deletion, and direct map preview 2026-10-01 13:37:26 -05:00
kiskaadee 6880b74b60 feat(admin): add UPDATE and DELETE endpoints for RSVP management 2026-10-01 13:37:21 -05:00
kiskaadee c44ecfc14b fix(map): support share.google domains and address geocoding fallback
- Add share.google and .google TLDs to allowed GOogle Maps domain
  whitelist
- Accept optional fallback_query in resolve_google_maps_coordinates
- Build geocoding candidate queries using address_lines and venue name
  when links lack embedded GPS coordinates
- Pass venue location details to coordinate resolver across admin update
  and preview regeneration routes
- Update test suite to verify share.google host validation and fallback
  parameter propagation
2026-10-01 12:46:59 -05:00
kiskaadee c8264b3d76 feat(map): autogenerate static map preview from Google Maps URL
- Add map_preview service resolving short links, cordinates, and OSM 3x3
  tile stitching
- Draw theme-matched golden venue marker pin centered on location
  cordinates
- Validate Google Maps URL structure and domain invariants in Pydantic
  schema
- Trigger automatic regeneration on PUT /config only when map_url
  changes
- Add POST /admin/map-preview/generate for ad-hoc generation withoug
  database writes
- Add circular preview widget and "Regenerar Mapa" action button to
  ConfigEditor
- Add public GET /birthday/api/map-preview.png endpoint with
  cache-control headers
- Update backend specifications and test suite
2026-10-01 12:28:59 -05:00
kiskaadee 818413b4f4 fix(traefik): protect admin API routes with Authelia ForwardAuth
Extend bdinvite-admin Traefik router rule to cover both /birthday/admin
and /birthday/api/admin prefixes, ensuring Authelia intercepts API requests
and injects the Remote-User header expected by FastAPI.
2026-10-01 11:44:59 -05:00
kiskaadee f4a70ffe1d feat(infra): add multi-stage Dockerfile, split Traefik routing, and
appctl manifest.

- Implement multi-stage Dockerfile compiling React with Node 20 and
  serving via uv/FastAPI
- Configure docker-compose.yml with split Traefik routers (public 10,
  admin Authelia 20)
- Add appctl manifest apptaml targeting demos.roadtotech.me on proxy-net
- Add .dockerignore for clean build context
- Update roadmap reflecting completion of Phase 5 infrastructure tasks.
2026-10-01 01:41:52 -05:00
kiskaadee b1bb564957 fix(routing): redirect /birthday to canonical /birthday/ and mock dev
auth

- Redirect /birthday to /birthday/ with HTTP 307 in FastAPI and 301 in
  Vite dev server
- Update pytest test_spa_catch_all to assert redirect behavior
- Add development Remote-User header in Vite proxy for unblocked local
  admin testing
2026-10-01 01:39:29 -05:00
kiskaadee d4ae37fef8 feat(frontend): implement interactive invitation SPA and admin dashboard
- Add React 18 + Vite + Typescript application architecture with
  basename /birthday
- Implement invitation experience with golden bokeh particle canvas adn
  countdown timer
- Build Colombian phone validated RSVP flow with optimistic submission
  state machine
- Add Authelia-protected admin dashboard with live RSVP table and
  configuration editor
- Embed self-hosted display and Montserrat fonts without external CDN
  dependencies
- Include self-contained Biome linter configuration with parent VCS root
  resolution
- Update project roadmap reflecting completion of phases 2, 3 and 4
2026-09-30 23:38:18 -05:00
kiskaadee 6f9026a5e6 build(env): provide Nix devShell and direnv auto-activation
- Add declarative shell.nix bundling Node 24, Biome 2.5, uv and Python
  3.11
- Add .envrc with use nix for seamless environment loading on directory
  change
- Ignore .direnv cache directory in .gitignore
2026-09-30 23:34:57 -05:00
kiskaadee 77ead3b99a docs(backend): enrich OpenAPI schemas, response contracts, and add docs
redirect

- document 201, 409, 422 and 500 semantic response models on RSVP route
- document Authelia Remote-User security requirement and 401 response on
  admin routes
- add interactive examples and spanish descriptions across all Pydantic
  schemas
- add /docs redirect to /birthday/api/docs for developer ergonomics
- hide SPA static catch-all routes from OpenAPI schema
- resolve static assets directly from disk before SPA catch-all fallback
2026-09-30 22:49:04 -05:00
kiskaadee 83dead536b chore(backend): organize test imports and update lockfile
- sort imports in test suite to satisty ruff I001 rules
- sync uv.lock dependencies
2026-09-30 22:16:05 -05:00
kiskaadee 856da792e0 fix(backend): serve static assets from disk before SPA catch-all
fallback
2026-09-30 22:13:38 -05:00
kiskaadee a7567aa69b feat(backend): implement FastAPI core service, SQLite WAL and admin
endpoints

- add SQLAlchemy models for RSVPS and singleton invitation configuration
- implement phone number normalization (10d Colombia standard) and
  duplicate detection
- add Authelia Remote-User security guard on all admin endpoints
- use typing.Annotated for FastAPI dependencies and date.fromisoformat
- add CSV export for RSVP responses
- add SPA catch-all mount under /birthday/
- add linting and static check configuration
2026-09-30 20:47:08 -05:00
kiskaadee 9dbcf72295 docs: establish project foundation and technical documentation
- Add frontend speficication with section-based layout and countdown
  states
- Add backend specification with FastAPI, SQLite WAL, and Authelia auth
  guard
- Add infrastructure specification with Traefik split-routing and appctl
  manifest
- Add project roadmap, README gitignore, and updated UNLICENSE
2026-09-30 20:23:02 -05:00
83 changed files with 15283 additions and 0 deletions

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
node_modules/
frontend/node_modules/
frontend/dist/
.venv/
backend/.venv/
.pytest_cache/
__pycache__/
*.pyc
data/
backend/data/
.git/
.direnv/
.env*
+55
View File
@@ -0,0 +1,55 @@
# ==============================================================================
# BDInvite Environment Configuration Template (.env.example)
#
# BDInvite supports two operational deployment modes configured via environment:
# 1. Direct Standalone Mode (local dev & testing with mock-oauth2-server or Keycloak)
# 2. Homelab Production Mode (behind Traefik TLS proxy with Authelia or OIDC IdP)
# ==============================================================================
# ------------------------------------------------------------------------------
# 1. General Service Configuration
# ------------------------------------------------------------------------------
SERVICE_NAME=bdinvite
SERVICE_DOMAIN=demos.roadtotech.me
BASE_PATH=/birthday
APP_PORT=8000
DATABASE_URL=sqlite:///./data/bdinvite.db
DATA_DIR=./data
# ------------------------------------------------------------------------------
# 2. OpenID Connect (OIDC) Authentication Settings
# ------------------------------------------------------------------------------
# Mode A: Standalone Mode (Default Local Development)
# OIDC_ISSUER=http://localhost:8088/default
# OIDC_CLIENT_ID=bdinvite-client
# OIDC_CLIENT_SECRET=bdinvite-secret
# OIDC_REDIRECT_URI=http://localhost:8000/birthday/api/auth/callback
# Mode B: Homelab Production Mode (Traefik TLS + Authelia / IdP)
# OIDC_ISSUER=https://auth.roadtotech.me
# OIDC_CLIENT_ID=bdinvite
# OIDC_CLIENT_SECRET=change-me-to-production-secret
# OIDC_REDIRECT_URI=https://demos.roadtotech.me/birthday/api/auth/callback
OIDC_ISSUER=http://localhost:8088/default
OIDC_CLIENT_ID=bdinvite-client
OIDC_CLIENT_SECRET=bdinvite-secret
OIDC_REDIRECT_URI=http://localhost:8000/birthday/api/auth/callback
OIDC_GROUPS_CLAIM=groups
# OIDC_GROUP_CLAIM_PATH=realm_access.roles
# ------------------------------------------------------------------------------
# 3. Browser Session Management Settings
# ------------------------------------------------------------------------------
SESSION_COOKIE_NAME=bdinvite_session
# Set SESSION_COOKIE_SECURE to true in production behind HTTPS/TLS reverse proxy.
# Set to false only for local standalone testing over plain HTTP.
SESSION_COOKIE_SECURE=false
# Session cookie SameSite attribute ("lax", "strict", "none")
SESSION_COOKIE_SAMESITE=lax
SESSION_COOKIE_PATH=/
# SESSION_COOKIE_DOMAIN=roadtotech.me
SESSION_EXPIRE_SECONDS=86400
+1
View File
@@ -0,0 +1 @@
use nix
+34
View File
@@ -0,0 +1,34 @@
# Dependencies
frontend/node_modules/
# Python
backend/__pycache__/
backend/**/__pycache__/
*.pyc
*.pyo
.venv/
**/.venv/
.pytest_cache/
**/.pytest_cache/
backend/data/
# Build output
frontend/dist/
backend/static/
*.tsbuildinfo
# Data (volume-mounted, contains SQLite DB)
data/
# Environment
.env
*.env.local
.direnv/
# IDE
.vscode/
.idea/
# OS
.DS_Store
Thumbs.db
+17
View File
@@ -0,0 +1,17 @@
# Stage 1: Build React frontend
FROM node:20-alpine AS frontend-build
WORKDIR /build
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY frontend/ ./
RUN npm run build
# Stage 2: Python runtime
FROM ghcr.io/astral-sh/uv:python3.11-bookworm-slim
WORKDIR /app
ENV UV_COMPILE_BYTECODE=1
COPY backend/pyproject.toml backend/uv.lock* ./
RUN uv sync --frozen --no-install-project --no-dev
COPY backend/ .
COPY --from=frontend-build /build/dist ./static
CMD ["uv", "run", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
View File
Whitespace-only changes.
+28
View File
@@ -1 +1,29 @@
# bdinvite
Interactive digital birthday invitation with RSVP.
## Overview
A mobile-first invitation app with animated golden bokeh particles, an RSVP form with semantic state feedback, a live countdown timer, and an admin dashboard for managing responses and invitation content.
- **Guest**: `demos.roadtotech.me/birthday/`
- **Admin**: `demos.roadtotech.me/birthday/admin` (Authelia-protected)
## Stack
| Layer | Technology |
|---|---|
| Frontend | React, Vite, TypeScript, Canvas 2D, CSS Modules |
| Backend | FastAPI, SQLAlchemy, Pydantic, SQLite (WAL) |
| Infrastructure | Docker (multi-stage), Traefik, Authelia SSO |
## Documentation
- [Frontend Specification](specs/front.md)
- [Backend Specification](specs/backend.md)
- [Infrastructure Specification](specs/infra.md)
- [Roadmap](ROADMAP.md)
## License
[Unlicense](UNLICENSE) — public domain.
+79
View File
@@ -0,0 +1,79 @@
# Roadmap
## Phase 0 — Documentation Foundation
- [x] Frontend specification
- [x] Backend specification
- [x] Infrastructure specification
- [x] Project README
- [x] Roadmap
- [x] License (Unlicense)
## Phase 1 — Backend
- [x] Project scaffolding (`pyproject.toml`, app directory)
- [x] SQLite database with WAL mode
- [x] SQLAlchemy models (`RSVP`, `InvitationConfig`)
- [x] Pydantic request/response schemas
- [x] Config seeding and CRUD
- [x] `POST /birthday/api/rsvp` with phone normalization
- [x] `GET /birthday/api/config`
- [x] Admin endpoints with `Remote-User` guard
- [x] CSV export endpoint
- [x] SPA catch-all route
- [x] Backend tests (15 unit/integration tests passing)
## Phase 2 — Frontend Scaffolding
- [x] Vite + React + TypeScript setup
- [x] React Router with `basename=/birthday`
- [x] API client (`/birthday/api/*`)
- [x] Config loading state (`CONFIG_LOADING` → `INVITATION` | `CONFIG_ERROR`)
- [x] Self-hosted font files (display script + Montserrat)
- [x] CSS Modules setup and global styles
- [x] TypeScript interfaces for config and API responses
## Phase 3 — Guest Experience
- [x] Invitation hero section (fixed aspect ratio)
- [x] Canvas 2D particle background (golden bokeh)
- [x] RSVP CTA with smooth scroll transition
- [x] RSVP form with client-side validation (Colombian phone format)
- [x] Submission state machine (`SUBMITTING` → `SUCCESS` | `DUPLICATE` | `ERROR`)
- [x] Confirmation section: personalized message
- [x] Countdown timer (timezone-aware, `NOS VEMOS EN DD:HH:MM:SS`)
- [x] Map preview (circular static image, link to `mapUrl`)
- [x] Venue info (compact name + address)
- [x] `sessionStorage` post-RSVP state preservation
- [x] Accessibility (semantic HTML, keyboard nav, aria-live, focus states)
- [x] `prefers-reduced-motion` support (static particles)
- [x] Responsive behavior (mobile-first, desktop stage)
## Phase 4 — Admin Dashboard
- [x] Admin layout shell (header, navigation)
- [x] RSVP table with total count
- [x] Search/filter RSVPs
- [x] CSV export download button
- [x] Config editor form (flat fields, Pydantic-validated)
- [x] Text preview of invitation content
## Phase 5 — Infrastructure & Deployment
- [x] Dockerfile (multi-stage build)
- [x] `docker-compose.yml` with split Traefik routing
- [x] `app.yaml` manifest for `appctl`
- [x] `.gitignore` finalized
- [x] Local Docker build verification
- [ ] Deployment to `demos.roadtotech.me`
- [ ] Post-deployment verification
- [ ] Authelia admin route verification
## Future
- [ ] Font selection (visual comparison of candidates)
- [x] Application-owned map preview asset (replace URL with static file)
- [ ] Miniature rendered invitation preview in admin config editor
- [ ] Enhanced admin features (edit/delete RSVP, attendance status, guest count)
- [ ] CSV import
+24
View File
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
+18
View File
@@ -0,0 +1,18 @@
name: "bdinvite"
aliases:
- "birthday"
- "invite"
domain: "demos.roadtotech.me"
description: "Interactive Digital Birthday Invitation with RSVP"
visible: true
auth: false
networks:
- proxy-net
env:
BASE_PATH: "/birthday"
homepage:
title: "Birthday Invite"
group: "Applications"
icon: "party.png"
container: "bdinvite"
weight: 30
+1
View File
@@ -0,0 +1 @@
"""Birthday Invitation Application Package."""
+68
View File
@@ -0,0 +1,68 @@
"""Authentication package providing domain models, hexagonal ports, and OIDC client."""
from .dependencies import (
AdminUserDep,
AuthAdapterDep,
AuthenticatedUserDep,
CurrentIdentityDep,
get_auth_adapter,
get_current_identity,
require_admin,
require_authenticated,
require_group,
set_auth_adapter,
)
from .oidc import (
InvalidCodeVerifierError,
InvalidNonceError,
InvalidStateError,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
OIDCDiscovery,
OIDCError,
OIDCTransaction,
SessionRecord,
TokenValidationError,
claims_to_identity,
extract_identity_from_claims,
generate_code_challenge,
generate_code_verifier,
generate_nonce,
generate_state,
resolve_claim_path,
)
from .port import AuthPort, Identity
__all__ = [
"AdminUserDep",
"AuthAdapterDep",
"AuthPort",
"AuthenticatedUserDep",
"CurrentIdentityDep",
"Identity",
"InvalidCodeVerifierError",
"InvalidNonceError",
"InvalidStateError",
"OIDCAuthAdapter",
"OIDCClient",
"OIDCConfig",
"OIDCDiscovery",
"OIDCError",
"OIDCTransaction",
"SessionRecord",
"TokenValidationError",
"claims_to_identity",
"extract_identity_from_claims",
"generate_code_challenge",
"generate_code_verifier",
"generate_nonce",
"generate_state",
"get_auth_adapter",
"get_current_identity",
"require_admin",
"require_authenticated",
"require_group",
"resolve_claim_path",
"set_auth_adapter",
]
+108
View File
@@ -0,0 +1,108 @@
"""FastAPI dependency injection module for authentication and authorization."""
from collections.abc import Callable
from typing import Annotated, Optional
from fastapi import Depends, HTTPException, Request, status
from ..config import settings
from .oidc import OIDCAuthAdapter, OIDCClient, OIDCConfig
from .port import Identity
_auth_adapter: Optional[OIDCAuthAdapter] = None
def get_auth_adapter() -> OIDCAuthAdapter:
"""Provide singleton or cached OIDCAuthAdapter for dependency injection."""
global _auth_adapter
if _auth_adapter is None:
client_config = OIDCConfig(
issuer=settings.OIDC_ISSUER,
client_id=settings.OIDC_CLIENT_ID,
client_secret=settings.OIDC_CLIENT_SECRET,
redirect_uri=settings.OIDC_REDIRECT_URI,
groups_claim=settings.OIDC_GROUPS_CLAIM,
group_claim_path=settings.OIDC_GROUP_CLAIM_PATH,
)
client = OIDCClient(client_config)
_auth_adapter = OIDCAuthAdapter(
client=client,
session_cookie_name=settings.SESSION_COOKIE_NAME,
cookie_secure=settings.SESSION_COOKIE_SECURE,
cookie_samesite=settings.SESSION_COOKIE_SAMESITE,
cookie_path=settings.SESSION_COOKIE_PATH,
cookie_domain=settings.SESSION_COOKIE_DOMAIN,
session_lifetime=float(settings.SESSION_EXPIRE_SECONDS),
)
return _auth_adapter
def set_auth_adapter(adapter: Optional[OIDCAuthAdapter]) -> None:
"""Override the active auth adapter (for test isolation and fixture injection)."""
global _auth_adapter
_auth_adapter = adapter
AuthAdapterDep = Annotated[OIDCAuthAdapter, Depends(get_auth_adapter)]
def get_current_identity(
request: Request,
adapter: OIDCAuthAdapter = Depends(get_auth_adapter),
) -> Optional[Identity]:
"""Resolve the active Identity from the session or adapter, or None if unauthenticated."""
if not isinstance(adapter, OIDCAuthAdapter):
adapter = get_auth_adapter()
return adapter.current_identity(request)
def require_authenticated(
identity: Optional[Identity] = Depends(get_current_identity),
) -> Identity:
"""Enforce authentication, raising HTTP 401 Unauthorized if anonymous."""
if identity is None or not isinstance(identity, Identity):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
headers={"WWW-Authenticate": "Bearer"},
)
return identity
def require_group(group_name: str) -> Callable[..., Identity]:
"""Dependency factory enforcing membership in a specified group.
Raises HTTP 401 Unauthorized if anonymous, and HTTP 403 Forbidden
if authenticated but missing the required group in identity.groups.
"""
def _require_group_dependency(
identity: Optional[Identity] = Depends(get_current_identity),
) -> Identity:
if identity is None or not isinstance(identity, Identity):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required",
headers={"WWW-Authenticate": "Bearer"},
)
if group_name not in identity.groups:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f"Forbidden: user is not a member of group '{group_name}'",
)
return identity
_require_group_dependency.__name__ = f"require_group_{group_name}"
_require_group_dependency.__qualname__ = (
f"require_group.<locals>.require_group_{group_name}"
)
return _require_group_dependency
# Application Authorization Policy:
require_admin: Callable[..., Identity] = require_group("bdinvite_admins")
# Type annotations for endpoint dependency injection
CurrentIdentityDep = Annotated[Optional[Identity], Depends(get_current_identity)]
AuthenticatedUserDep = Annotated[Identity, Depends(require_authenticated)]
AdminUserDep = Annotated[Identity, Depends(require_admin)]
File diff suppressed because it is too large. Load diff
+49
View File
@@ -0,0 +1,49 @@
"""Authentication port and identity abstractions for hexagonal architecture."""
from dataclasses import dataclass, field
from typing import Optional, Protocol, runtime_checkable
from fastapi import Request, Response
@dataclass(frozen=True)
class Identity:
"""Domain model representing a validated authenticated user identity.
Identity Origin Integrity Invariant:
An Identity instance must only represent validated authentication results
(such as from an authorized identity provider, cryptographically verified token,
or trusted authentication adapter). It must never be constructed directly
from raw, unvalidated client request headers.
"""
subject: str
email: str
name: Optional[str] = None
groups: list[str] = field(default_factory=list)
def __post_init__(self) -> None:
if self.groups is None: # type: ignore[reportUnnecessaryComparison]
object.__setattr__(self, "groups", [])
elif not isinstance(self.groups, list):
object.__setattr__(self, "groups", list(self.groups))
@runtime_checkable
class AuthPort(Protocol):
"""Hexagonal inbound/outbound port interface for authentication."""
def current_identity(self, request: Request) -> Optional[Identity]:
"""Extract and return the verified Identity from the incoming request.
Returns None if the request is unauthenticated or credentials are invalid.
"""
...
def login(self, request: Request) -> Response:
"""Handle or initiate the authentication flow (e.g. redirecting to an IdP)."""
...
def logout(self, request: Request) -> Response:
"""Handle session termination or logout redirection."""
...
+72
View File
@@ -0,0 +1,72 @@
from pathlib import Path
from typing import Literal
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""Application and deployment configuration supporting multi-mode deployment.
BDInvite supports two primary operational deployment modes via environment variables:
1. Direct Standalone Mode (Local Development & Testing):
- Runs directly or in lightweight container with direct port binding (e.g. 8000).
- Integrates directly with any standard OIDC identity provider (e.g. mock-oauth2-server,
local Keycloak, or Dex).
- Insecure session cookies (`SESSION_COOKIE_SECURE=False`) allow local HTTP testing.
- Example:
OIDC_ISSUER="http://localhost:8088/default"
OIDC_REDIRECT_URI="http://localhost:8000/birthday/api/auth/callback"
SESSION_COOKIE_SECURE=false
2. Homelab Production Mode (Reverse Proxy & Edge Ingress):
- Deployed behind Traefik reverse proxy terminating TLS on edge domain.
- Integrates with central Homelab OIDC Provider (such as Authelia, Keycloak, or Authentik).
- Secure session cookies (`SESSION_COOKIE_SECURE=True`) enforce HTTPS-only transmission.
- Zero trust in unvalidated client headers (e.g. legacy proxy headers are completely ignored).
- Example:
SERVICE_DOMAIN="demos.roadtotech.me"
OIDC_ISSUER="https://auth.roadtotech.me"
OIDC_CLIENT_ID="bdinvite"
OIDC_CLIENT_SECRET="<secret>"
OIDC_REDIRECT_URI="https://demos.roadtotech.me/birthday/api/auth/callback"
SESSION_COOKIE_SECURE=true
SESSION_COOKIE_NAME="bdinvite_session"
"""
SERVICE_NAME: str = "bdinvite"
SERVICE_DOMAIN: str = "demos.roadtotech.me"
BASE_PATH: str = "/birthday"
APP_PORT: int = 8000
DATABASE_URL: str = "sqlite:///./data/bdinvite.db"
DATA_DIR: str = "./data"
# OIDC & Auth Settings
OIDC_ISSUER: str = "http://localhost:8088/default"
OIDC_CLIENT_ID: str = "bdinvite-client"
OIDC_CLIENT_SECRET: str | None = "bdinvite-secret"
OIDC_REDIRECT_URI: str = "http://localhost:8000/birthday/api/auth/callback"
OIDC_GROUPS_CLAIM: str = "groups"
OIDC_GROUP_CLAIM_PATH: str | None = None
# Browser Session Management Settings
SESSION_COOKIE_NAME: str = "bdinvite_session"
SESSION_COOKIE_SECURE: bool = False
SESSION_COOKIE_SAMESITE: Literal["lax", "strict", "none"] = "lax"
SESSION_COOKIE_PATH: str = "/"
SESSION_COOKIE_DOMAIN: str | None = None
SESSION_EXPIRE_SECONDS: int = 86400
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
@property
def data_path(self) -> Path:
return Path(self.DATA_DIR).resolve()
@property
def map_preview_file(self) -> Path:
return self.data_path / "map_preview.png"
settings = Settings()
+43
View File
@@ -0,0 +1,43 @@
import os
from collections.abc import Generator
from sqlalchemy import create_engine, event
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
from .config import settings
# Ensure data directory exists if a local relative file path is used
if settings.DATABASE_URL.startswith("sqlite:///./data/"):
os.makedirs("./data", exist_ok=True)
connect_args = {}
if settings.DATABASE_URL.startswith("sqlite"):
connect_args["check_same_thread"] = False
engine = create_engine(
settings.DATABASE_URL,
connect_args=connect_args,
)
@event.listens_for(engine, "connect")
def set_sqlite_pragma(dbapi_connection, connection_record):
if settings.DATABASE_URL.startswith("sqlite"):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA journal_mode=WAL;")
cursor.close()
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
class Base(DeclarativeBase):
pass
def get_db() -> Generator[Session, None, None]:
db = SessionLocal()
try:
yield db
finally:
db.close()
+147
View File
@@ -0,0 +1,147 @@
import os
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from .config import settings
from .database import Base, SessionLocal, engine
from .routes import admin, auth, config, rsvp
from .services.config import seed_default_config
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
# Ensure tables are created on startup
Base.metadata.create_all(bind=engine)
# Seed default configuration row
with SessionLocal() as db:
seed_default_config(db)
yield
app = FastAPI(
title="Birthday Invitation API",
version="1.0.0",
description=(
"API REST para la invitación interactiva de cumpleaños con sistema RSVP.\n\n"
"### Arquitectura de Seguridad\n"
"- **Rutas Públicas (`/birthday/api/*`)**: Acceso abierto para los invitados.\n"
"- **Rutas Administrativas (`/birthday/api/admin/*`)**: Protegidas por autenticación "
"OIDC y autorización basada en grupos (`bdinvite_admins`)."
),
openapi_tags=[
{
"name": "RSVP",
"description": "Registro y validación de confirmación de asistencia para invitados.",
},
{
"name": "Config",
"description": "Consulta pública de la configuración singleton del evento.",
},
{
"name": "Admin",
"description": "Gestión de asistentes, descarga CSV y edición de contenido protegida por autorización administrativa.",
},
],
lifespan=lifespan,
docs_url="/birthday/api/docs",
openapi_url="/birthday/api/openapi.json",
)
@app.get("/docs", include_in_schema=False)
async def redirect_to_docs():
return RedirectResponse(url="/birthday/api/docs")
# CORS configuration
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Exception handler to normalize validation errors into our contract
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
errors: dict[str, str] = {}
for err in exc.errors():
loc = err.get("loc", [])
field = str(loc[-1]) if loc else "general"
msg = err.get("msg", "Entrada inválida")
# Clean standard Pydantic error prefixes if present
msg = msg.removeprefix("Value error, ")
errors[field] = msg
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={"result": "VALIDATION_ERROR", "errors": errors},
)
# Register API routes with exact path prefixes per specification
app.include_router(rsvp.router, prefix="/birthday/api")
app.include_router(config.router, prefix="/birthday/api")
app.include_router(auth.router, prefix="/birthday/api/auth")
app.include_router(admin.router, prefix="/birthday/api/admin")
@app.get(
"/birthday/api/map-preview.png",
tags=["Config"],
summary="Obtener imagen de vista previa del mapa generada",
description="Retorna el archivo PNG de vista previa del mapa generado centrado en la ubicación.",
)
async def get_map_preview():
if settings.map_preview_file.exists():
return FileResponse(
settings.map_preview_file,
media_type="image/png",
headers={"Cache-Control": "public, max-age=300"},
)
return RedirectResponse(
url="https://tile.openstreetmap.org/15/8802/13443.png",
status_code=status.HTTP_307_TEMPORARY_REDIRECT,
)
# Static files and SPA serving
STATIC_DIR = os.path.join(os.path.dirname(__file__), "..", "static")
ASSETS_DIR = os.path.join(STATIC_DIR, "assets")
if os.path.isdir(ASSETS_DIR):
app.mount("/birthday/assets", StaticFiles(directory=ASSETS_DIR), name="assets")
@app.get("/birthday", include_in_schema=False)
async def redirect_birthday_slash():
return RedirectResponse(url="/birthday/", status_code=status.HTTP_307_TEMPORARY_REDIRECT)
@app.get("/birthday/", include_in_schema=False)
@app.get("/birthday/{full_path:path}", include_in_schema=False)
async def spa_catch_all(full_path: str = ""):
if full_path:
requested_file = os.path.join(STATIC_DIR, full_path)
if os.path.isfile(requested_file):
return FileResponse(requested_file)
index_file = os.path.join(STATIC_DIR, "index.html")
if os.path.isfile(index_file):
return FileResponse(index_file)
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"service": "bdinvite",
"status": "ready",
"message": "Frontend static assets not yet compiled in this environment.",
},
)
+98
View File
@@ -0,0 +1,98 @@
from datetime import UTC, datetime
from sqlalchemy import DateTime, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column
from .database import Base
def utc_now() -> datetime:
return datetime.now(UTC)
class RSVP(Base):
__tablename__ = "rsvps"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(100), nullable=False)
phone: Mapped[str] = mapped_column(String(20), nullable=False, unique=True, index=True)
email: Mapped[str | None] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=utc_now
)
class InvitationConfig(Base):
__tablename__ = "invitation_config"
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1)
title: Mapped[str] = mapped_column(String(200), nullable=False, default="Birthday Party")
invitation_text: Mapped[str] = mapped_column(
String(500),
nullable=False,
default="You're invited to the birthday party honoring",
)
honoree_name: Mapped[str] = mapped_column(String(200), nullable=False, default="Isabelle Snow")
event_date: Mapped[str] = mapped_column(String(20), nullable=False, default="2026-10-28")
event_time: Mapped[str] = mapped_column(String(10), nullable=False, default="19:00")
event_timezone: Mapped[str] = mapped_column(
String(50), nullable=False, default="America/Bogota"
)
address_name: Mapped[str] = mapped_column(
String(200), nullable=False, default="Fresco Ristorante"
)
address_lines: Mapped[str] = mapped_column(
Text,
nullable=False,
default="514 S Brand Blvd\nGlendale, CA 91204",
)
map_preview_url: Mapped[str] = mapped_column(
String(500),
nullable=False,
default="https://tile.openstreetmap.org/15/8802/13443.png",
)
map_url: Mapped[str] = mapped_column(
String(500),
nullable=False,
default="https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA",
)
rsvp_heading: Mapped[str] = mapped_column(String(100), nullable=False, default="¿Nos vemos?")
rsvp_cta: Mapped[str] = mapped_column(
String(100), nullable=False, default="CONFIRMA TU ASISTENCIA"
)
submit_label: Mapped[str] = mapped_column(String(100), nullable=False, default="TE VEO AHÍ")
msg_success: Mapped[str] = mapped_column(
String(300),
nullable=False,
default="¡Perfecto! Tu asistencia ha sido confirmada.",
)
msg_success_greeting: Mapped[str] = mapped_column(
String(100), nullable=False, default="Gracias, {name}."
)
msg_duplicate: Mapped[str] = mapped_column(
String(300),
nullable=False,
default="Parece que ya tenemos tus datos registrados.",
)
msg_error: Mapped[str] = mapped_column(
String(300),
nullable=False,
default="No pudimos registrar tu asistencia. Inténtalo nuevamente.",
)
msg_config_error: Mapped[str] = mapped_column(
String(300),
nullable=False,
default="No pudimos cargar la invitación. Inténtalo nuevamente.",
)
countdown_label: Mapped[str] = mapped_column(
String(100), nullable=False, default="NOS VEMOS EN"
)
countdown_in_progress: Mapped[str] = mapped_column(
String(100), nullable=False, default="EVENTO EN CURSO"
)
countdown_finished: Mapped[str] = mapped_column(
String(100), nullable=False, default="EVENTO FINALIZADO"
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=utc_now, onupdate=utc_now
)
+5
View File
@@ -0,0 +1,5 @@
"""API Route definitions."""
from . import admin, auth, config, rsvp
__all__ = ["admin", "auth", "config", "rsvp"]
+308
View File
@@ -0,0 +1,308 @@
import csv
import io
from datetime import UTC, datetime
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy.orm import Session
from ..auth import AdminUserDep, Identity, require_admin
from ..config import settings
from ..database import get_db
from ..schemas import (
GenerateMapPreviewRequest,
GenerateMapPreviewResponse,
InvitationConfigResponse,
InvitationConfigUpdate,
RSVPAdminItem,
RSVPListResponse,
RSVPUpdate,
)
from ..services.config import get_config, seed_default_config, update_config
from ..services.map_preview import generate_map_preview_image, resolve_google_maps_coordinates
from ..services.rsvp import delete_rsvp, get_rsvps, update_rsvp
router = APIRouter(tags=["Admin"], dependencies=[Depends(require_admin)])
AdminDep = AdminUserDep
DbDep = Annotated[Session, Depends(get_db)]
ADMIN_RESPONSES = {
401: {
"description": "No autenticado. Se requiere una sesión válida o token de autorización.",
},
403: {
"description": "Acceso prohibido. El usuario autenticado no pertenece al grupo administrativo.",
},
}
@router.get(
"/rsvps",
response_model=RSVPListResponse,
summary="Listar asistentes confirmados",
description=(
"Obtiene el total y la lista de todos los invitados que han confirmado asistencia. "
"Permite filtrado por coincidencia parcial (`?search=`) sobre nombre, teléfono o correo."
),
responses={
200: {"model": RSVPListResponse, "description": "Lista de confirmaciones obtenida."},
**ADMIN_RESPONSES,
},
)
def list_rsvps(
admin: AdminDep,
db: DbDep,
search: Annotated[
str | None,
Query(
description="Término de búsqueda opcional (subcadena en nombre, teléfono o email)",
examples=["Andrés"],
),
] = None,
):
rsvps = get_rsvps(db, search=search)
return RSVPListResponse(
count=len(rsvps),
rsvps=rsvps, # type: ignore[arg-type]
)
@router.delete(
"/rsvps/{rsvp_id}",
status_code=status.HTTP_204_NO_CONTENT,
summary="Eliminar confirmación de asistencia",
description="Elimina permanentemente un registro de RSVP por su identificador.",
responses={
204: {"description": "Registro eliminado con éxito."},
404: {"description": "Registro no encontrado."},
**ADMIN_RESPONSES,
},
)
def delete_rsvp_endpoint(
rsvp_id: int,
admin: AdminDep,
db: DbDep,
):
deleted = delete_rsvp(db, rsvp_id)
if not deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"No se encontró el registro con ID {rsvp_id}",
)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.patch(
"/rsvps/{rsvp_id}",
response_model=RSVPAdminItem,
summary="Editar una confirmación de asistencia",
description="Actualiza el nombre, teléfono o correo de un asistente confirmado.",
responses={
200: {"model": RSVPAdminItem, "description": "Registro actualizado exitosamente."},
400: {"description": "Error de validación en los campos proporcionados."},
404: {"description": "Registro no encontrado."},
409: {"description": "El número de teléfono ya está registrado por otro asistente."},
**ADMIN_RESPONSES,
},
)
def update_rsvp_endpoint(
rsvp_id: int,
payload: RSVPUpdate,
admin: AdminDep,
db: DbDep,
):
status_res, updated = update_rsvp(db, rsvp_id, payload)
if status_res == "NOT_FOUND":
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"No se encontró el registro con ID {rsvp_id}",
)
if status_res == "DUPLICATE":
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="El número de teléfono ya está registrado para otro asistente.",
)
assert updated is not None
return updated
@router.get(
"/export",
summary="Exportar confirmaciones en formato CSV",
description=(
"Genera dinámicamente un archivo CSV con las columnas: `name`, `phone`, `email` y `created_at`. "
"Descarga el archivo directamente con encabezados `Content-Disposition: attachment`."
),
responses={
200: {
"content": {"text/csv": {}},
"description": "Descarga del archivo CSV `rsvps.csv`.",
},
**ADMIN_RESPONSES,
},
)
def export_rsvps_csv(
admin: AdminDep,
db: DbDep,
):
rsvps = get_rsvps(db)
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(["name", "phone", "email", "created_at"])
for item in rsvps:
created_iso = ""
if item.created_at:
dt = item.created_at if item.created_at.tzinfo else item.created_at.replace(tzinfo=UTC)
created_iso = dt.isoformat()
writer.writerow([item.name, item.phone, item.email or "", created_iso])
csv_content = output.getvalue()
return Response(
content=csv_content,
media_type="text/csv",
headers={"Content-Disposition": 'attachment; filename="rsvps.csv"'},
)
@router.get(
"/config",
response_model=InvitationConfigResponse,
summary="Obtener configuración editable",
description="Retorna el objeto completo de configuración para poblar el formulario de administración.",
responses={
200: {"model": InvitationConfigResponse, "description": "Configuración obtenida correctamente."},
**ADMIN_RESPONSES,
},
)
def get_admin_config(
admin: AdminDep,
db: DbDep,
):
config = get_config(db)
if not config:
config = seed_default_config(db)
return config
@router.put(
"/config",
response_model=InvitationConfigResponse,
summary="Actualizar configuración de la invitación",
description=(
"Reemplaza los valores de la configuración singleton del evento. "
"Si la URL de Google Maps cambió, valida y regenera automáticamente la vista previa del mapa. "
"Aplica validación de fecha ISO, hora en formato militar 24h y zona horaria válida IANA. "
"Los cambios toman efecto de inmediato sin requerir recarga del contenedor."
),
responses={
200: {"model": InvitationConfigResponse, "description": "Configuración actualizada con éxito."},
**ADMIN_RESPONSES,
},
)
@router.patch(
"/config",
response_model=InvitationConfigResponse,
summary="Actualizar configuración de la invitación",
description=(
"Actualiza los valores de la configuración singleton del evento. "
"Si la URL de Google Maps cambió, valida y regenera automáticamente la vista previa del mapa. "
"Aplica validación de fecha ISO, hora en formato militar 24h y zona horaria válida IANA. "
"Los cambios toman efecto de inmediato sin requerir recarga del contenedor."
),
responses={
200: {"model": InvitationConfigResponse, "description": "Configuración actualizada con éxito."},
**ADMIN_RESPONSES,
},
)
async def update_admin_config(
update_in: InvitationConfigUpdate,
admin: AdminDep,
db: DbDep,
):
current = get_config(db)
if not current:
current = seed_default_config(db)
# Condition: Trigger generation ONLY if map_url was changed
if current.map_url != update_in.map_url:
try:
fallback = f"{update_in.address_lines}\n{update_in.address_name}"
lat, lng, _ = await resolve_google_maps_coordinates(
update_in.map_url, fallback_query=fallback
)
await generate_map_preview_image(lat, lng)
update_in.map_preview_url = f"{settings.BASE_PATH}/api/map-preview.png"
except ValueError as err:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=str(err),
) from err
except Exception as err:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Error al generar la vista previa del mapa: {err}",
) from err
updated = update_config(db, update_in)
return updated
@router.post(
"/map-preview/generate",
response_model=GenerateMapPreviewResponse,
summary="Regenerar la vista previa del mapa",
description=(
"Genera o regenera la imagen del mapa en disco para la URL provista o la configurada actualmente, "
"sin realizar escrituras innecesarias a la base de datos."
),
responses={
200: {"model": GenerateMapPreviewResponse, "description": "Vista previa generada exitosamente."},
**ADMIN_RESPONSES,
},
)
async def regenerate_map_preview_endpoint(
admin: AdminDep,
db: DbDep,
payload: GenerateMapPreviewRequest | None = None,
):
current = get_config(db)
target_url = payload.map_url.strip() if (payload and payload.map_url) else None
if not target_url:
if not current or not current.map_url:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="No se proporcionó una URL de Google Maps ni existe una guardada en la configuración.",
)
target_url = current.map_url
try:
fallback = f"{current.address_lines}\n{current.address_name}" if current else None
lat, lng, _ = await resolve_google_maps_coordinates(
target_url, fallback_query=fallback
)
await generate_map_preview_image(lat, lng)
timestamp = int(datetime.now(UTC).timestamp())
return GenerateMapPreviewResponse(
map_preview_url=f"{settings.BASE_PATH}/api/map-preview.png?t={timestamp}",
lat=lat,
lng=lng,
message="Vista previa del mapa generada exitosamente.",
)
except ValueError as err:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=str(err),
) from err
except Exception as err:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Error al generar la vista previa del mapa: {err}",
) from err
+111
View File
@@ -0,0 +1,111 @@
"""Authentication and browser session management API routes."""
from typing import Annotated, Optional
from fastapi import APIRouter, Depends, Query, Request, Response, status
from fastapi.responses import JSONResponse, RedirectResponse
from ..auth import OIDCAuthAdapter, OIDCClient, OIDCConfig
from ..config import settings
router = APIRouter(tags=["Auth"])
from ..auth.dependencies import (
AuthAdapterDep,
get_auth_adapter,
set_auth_adapter,
)
@router.get(
"/login",
summary="Initiate OIDC authentication flow",
description="Redirects user browser to the configured OIDC provider authorization endpoint.",
)
def login(request: Request, adapter: AuthAdapterDep) -> Response:
return adapter.login(request)
@router.get(
"/callback",
summary="Handle OIDC authentication callback",
description=(
"Processes authorization code and state from IdP. "
"Enforces session fixation barrier by issuing a fresh session identifier "
"and sets HttpOnly SameSite browser session cookie."
),
)
def callback(
request: Request,
adapter: AuthAdapterDep,
code: str = Query(..., description="Authorization code from IdP"),
state: str = Query(..., description="CSRF state parameter"),
) -> Response:
target_url = "/birthday/admin"
response = RedirectResponse(url=target_url, status_code=status.HTTP_302_FOUND)
adapter.handle_callback(
code=code,
state=state,
response=response,
request=request,
)
return response
@router.get(
"/logout",
summary="Logout user session (Browser redirect)",
description="Revokes the session on server/storage, clears browser cookie (Max-Age=0), and redirects.",
)
@router.post(
"/logout",
summary="Logout user session (API)",
description="Revokes the session on server/storage, clears browser cookie (Max-Age=0), and returns JSON confirmation.",
)
def logout(
request: Request,
adapter: AuthAdapterDep,
redirect_uri: Optional[str] = Query(None, description="Optional post-logout redirect URI"),
) -> Response:
accept_header = request.headers.get("accept", "")
if request.method == "POST" or "application/json" in accept_header:
json_resp = JSONResponse(
status_code=status.HTTP_200_OK,
content={"result": "SUCCESS", "message": "Session terminated successfully"},
)
return adapter.logout(request, response=json_resp)
target = redirect_uri or "/birthday/admin?logged_out=1"
redirect_resp = RedirectResponse(url=target, status_code=status.HTTP_302_FOUND)
return adapter.logout(request, response=redirect_resp)
@router.get(
"/session",
summary="Check authenticated browser session",
description="Resolves incoming session cookie to verified Identity. Returns None if unauthenticated.",
)
@router.get(
"/me",
summary="Check current identity",
description="Alias for /session returning verified Identity.",
)
def get_session(request: Request, adapter: AuthAdapterDep) -> Response:
identity = adapter.current_identity(request)
if identity is None:
return JSONResponse(
status_code=status.HTTP_200_OK,
content={"authenticated": False, "identity": None},
)
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
"authenticated": True,
"identity": {
"subject": identity.subject,
"email": identity.email,
"name": identity.name,
"groups": identity.groups,
},
},
)
+45
View File
@@ -0,0 +1,45 @@
from typing import Annotated
from fastapi import APIRouter, Depends, status
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from ..database import get_db
from ..schemas import InvitationConfigResponse, RSVPErrorResponse
from ..services.config import get_config, seed_default_config
router = APIRouter(tags=["Config"])
DbDep = Annotated[Session, Depends(get_db)]
@router.get(
"/config",
response_model=InvitationConfigResponse,
summary="Obtener configuración de la invitación",
description=(
"Retorna la configuración singleton actual del evento para ser renderizada en la "
"experiencia web pública del invitado (textos, homenajeado, coordenadas de tiempo y lugar)."
),
responses={
200: {
"model": InvitationConfigResponse,
"description": "Configuración del evento obtenida correctamente.",
},
500: {
"model": RSVPErrorResponse,
"description": "Fallo al inicializar o consultar el registro singleton.",
},
},
)
def read_config(db: DbDep):
config = get_config(db)
if not config:
config = seed_default_config(db)
if not config:
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"result": "ERROR"},
)
return config
+74
View File
@@ -0,0 +1,74 @@
from typing import Annotated
from fastapi import APIRouter, Depends, status
from fastapi.responses import JSONResponse
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from ..database import get_db
from ..schemas import (
RSVPCreate,
RSVPDuplicateResponse,
RSVPErrorResponse,
RSVPSuccessResponse,
RSVPValidationErrorResponse,
)
from ..services.rsvp import create_rsvp
router = APIRouter(tags=["RSVP"])
DbDep = Annotated[Session, Depends(get_db)]
@router.post(
"/rsvp",
status_code=status.HTTP_201_CREATED,
summary="Registrar confirmación de asistencia",
description=(
"Recibe y procesa la confirmación de asistencia de un invitado. "
"El número telefónico es normalizado estrictamente al formato móvil colombiano de 10 dígitos "
"(comenzando en 3). Si el teléfono ya existe en el sistema, retorna un discriminador semántico "
"`DUPLICATE` con código HTTP 409."
),
responses={
201: {
"model": RSVPSuccessResponse,
"description": "Confirmación registrada exitosamente.",
},
409: {
"model": RSVPDuplicateResponse,
"description": "El número de teléfono ya ha sido registrado previamente.",
},
422: {
"model": RSVPValidationErrorResponse,
"description": "Fallo de validación de formato en los datos ingresados.",
},
500: {
"model": RSVPErrorResponse,
"description": "Error no controlado al persistir en la base de datos.",
},
},
)
def submit_rsvp(rsvp_in: RSVPCreate, db: DbDep):
try:
result_status, new_rsvp = create_rsvp(db, rsvp_in)
if result_status == "DUPLICATE":
return JSONResponse(
status_code=status.HTTP_409_CONFLICT,
content={"result": "DUPLICATE"},
)
assert new_rsvp is not None
return JSONResponse(
status_code=status.HTTP_201_CREATED,
content={"result": "SUCCESS", "name": new_rsvp.name},
)
except ValueError as e:
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={"result": "VALIDATION_ERROR", "errors": {"phone": str(e)}},
)
except SQLAlchemyError:
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"result": "ERROR"},
)
+406
View File
@@ -0,0 +1,406 @@
import re
from datetime import UTC, date, datetime
from typing import Literal
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator
def normalize_phone(raw: str) -> str:
"""Normalize Colombian mobile numbers.
Rules:
1. Strip all non-digit characters.
2. If starts with '57' and has 12 digits, strip '57'.
3. Must be exactly 10 digits and start with '3'.
"""
digits = re.sub(r"\D", "", raw)
if digits.startswith("57") and len(digits) == 12:
digits = digits[2:]
if len(digits) != 10 or not digits.startswith("3"):
raise ValueError("Formato de teléfono inválido")
return digits
class RSVPCreate(BaseModel):
name: str = Field(
...,
min_length=1,
max_length=100,
description="Nombre completo del invitado",
examples=["Andrés García"],
)
phone: str = Field(
...,
min_length=1,
max_length=50,
description="Número móvil en formato colombiano (10 dígitos, con o sin prefijo +57)",
examples=["+57 300 123 4567"],
)
email: str | None = Field(
default=None,
max_length=255,
description="Correo electrónico opcional para confirmación y recordatorios",
examples=["andres@example.com"],
)
@field_validator("name")
@classmethod
def normalize_name(cls, v: str) -> str:
cleaned = " ".join(v.strip().split())
if not cleaned:
raise ValueError("El nombre no puede estar vacío.")
return cleaned
@field_validator("phone")
@classmethod
def validate_phone(cls, v: str) -> str:
return normalize_phone(v)
@field_validator("email")
@classmethod
def validate_email(cls, v: str | None) -> str | None:
if v is None:
return None
cleaned = v.strip()
if not cleaned:
return None
email_regex = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
if not re.match(email_regex, cleaned):
raise ValueError("Formato de correo electrónico inválido")
return cleaned.lower()
class RSVPUpdate(BaseModel):
name: str | None = Field(
default=None,
min_length=1,
max_length=100,
description="Nombre completo del invitado",
examples=["Andrés García"],
)
phone: str | None = Field(
default=None,
min_length=1,
max_length=50,
description="Número móvil en formato colombiano (10 dígitos, con o sin prefijo +57)",
examples=["+57 300 123 4567"],
)
email: str | None = Field(
default=None,
max_length=255,
description="Correo electrónico opcional para confirmación y recordatorios",
examples=["andres@example.com"],
)
@field_validator("name")
@classmethod
def normalize_name(cls, v: str | None) -> str | None:
if v is None:
return None
cleaned = " ".join(v.strip().split())
if not cleaned:
raise ValueError("El nombre no puede estar vacío.")
return cleaned
@field_validator("phone")
@classmethod
def validate_phone(cls, v: str | None) -> str | None:
if v is None:
return None
return normalize_phone(v)
@field_validator("email")
@classmethod
def validate_email(cls, v: str | None) -> str | None:
if v is None:
return None
cleaned = v.strip()
if not cleaned:
return None
email_regex = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
if not re.match(email_regex, cleaned):
raise ValueError("Formato de correo electrónico inválido")
return cleaned.lower()
class RSVPSuccessResponse(BaseModel):
result: Literal["SUCCESS"] = Field(
default="SUCCESS",
description="Discriminador semántico de confirmación exitosa",
)
name: str = Field(
...,
description="Nombre del invitado registrado",
examples=["Andrés García"],
)
class RSVPDuplicateResponse(BaseModel):
result: Literal["DUPLICATE"] = Field(
default="DUPLICATE",
description="Indica que el número de teléfono móvil ya tiene una confirmación registrada",
)
class RSVPValidationErrorResponse(BaseModel):
result: Literal["VALIDATION_ERROR"] = Field(
default="VALIDATION_ERROR",
description="Indica error de validación en los datos enviados",
)
errors: dict[str, str] = Field(
...,
description="Mapa de nombres de campos con sus respectivos mensajes de error",
examples=[{"phone": "Formato de teléfono inválido"}],
)
class RSVPErrorResponse(BaseModel):
result: Literal["ERROR"] = Field(
default="ERROR",
description="Error interno no controlado durante el procesamiento",
)
class RSVPAdminItem(BaseModel):
id: int = Field(..., description="Identificador único del registro en base de datos", examples=[1])
name: str = Field(..., description="Nombre completo del asistente", examples=["Ana García"])
phone: str = Field(..., description="Número telefónico normalizado a 10 dígitos", examples=["3001234567"])
email: str | None = Field(default=None, description="Correo electrónico registrado", examples=["ana@example.com"])
created_at: datetime = Field(..., description="Marca de tiempo UTC de la confirmación")
model_config = ConfigDict(from_attributes=True)
@field_serializer("created_at")
def serialize_created_at(self, dt: datetime) -> str:
if dt.tzinfo is None:
dt = dt.replace(tzinfo=UTC)
return dt.isoformat()
class RSVPListResponse(BaseModel):
count: int = Field(..., description="Cantidad total de confirmaciones encontradas", examples=[37])
rsvps: list[RSVPAdminItem] = Field(..., description="Lista de asistentes confirmados")
class InvitationConfigBase(BaseModel):
title: str = Field(
...,
min_length=1,
max_length=200,
description="Título principal de la portada (tipografía script grande)",
examples=["Birthday Party"],
)
invitation_text: str = Field(
...,
min_length=1,
max_length=500,
description="Texto introductorio de la invitación",
examples=["You're invited to the birthday party honoring"],
)
honoree_name: str = Field(
...,
min_length=1,
max_length=200,
description="Nombre del homenajeado(a)",
examples=["Isabelle Snow"],
)
event_date: str = Field(
...,
description="Fecha del evento en formato ISO 8601 (YYYY-MM-DD)",
examples=["2026-10-28"],
)
event_time: str = Field(
...,
description="Hora de inicio del evento en formato 24 horas (HH:MM)",
examples=["19:00"],
)
event_timezone: str = Field(
...,
description="Identificador de zona horaria IANA para el cálculo exacto de la cuenta regresiva",
examples=["America/Bogota"],
)
address_name: str = Field(
...,
min_length=1,
max_length=200,
description="Nombre del restaurante, salón o recinto",
examples=["Fresco Ristorante"],
)
address_lines: str = Field(
...,
min_length=1,
description="Líneas de dirección del lugar (separadas por salto de línea)",
examples=["514 S Brand Blvd\nGlendale, CA 91204"],
)
map_preview_url: str = Field(
...,
min_length=1,
max_length=500,
description="URL de la imagen miniatura que se muestra en el widget circular",
examples=["https://tile.openstreetmap.org/15/8802/13443.png"],
)
map_url: str = Field(
...,
min_length=1,
max_length=500,
description="Enlace externo a Google Maps u otro servicio de navegación",
examples=["https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA"],
)
rsvp_heading: str = Field(
...,
min_length=1,
max_length=100,
description="Encabezado del formulario de confirmación",
examples=["¿Nos vemos?"],
)
rsvp_cta: str = Field(
...,
min_length=1,
max_length=100,
description="Texto del botón CTA en la portada que desplaza al formulario",
examples=["CONFIRMA TU ASISTENCIA"],
)
submit_label: str = Field(
...,
min_length=1,
max_length=100,
description="Texto del botón de envío del formulario",
examples=["TE VEO AHÍ"],
)
msg_success: str = Field(
...,
min_length=1,
max_length=300,
description="Mensaje principal tras confirmar asistencia",
examples=["¡Perfecto! Tu asistencia ha sido confirmada."],
)
msg_success_greeting: str = Field(
...,
min_length=1,
max_length=100,
description="Saludo personalizado; {name} se reemplaza con el nombre del invitado",
examples=["Gracias, {name}."],
)
msg_duplicate: str = Field(
...,
min_length=1,
max_length=300,
description="Mensaje mostrado si el número ya está registrado",
examples=["Parece que ya tenemos tus datos registrados."],
)
msg_error: str = Field(
...,
min_length=1,
max_length=300,
description="Mensaje en caso de fallo general del servidor",
examples=["No pudimos registrar tu asistencia. Inténtalo nuevamente."],
)
msg_config_error: str = Field(
...,
min_length=1,
max_length=300,
description="Mensaje si la configuración no puede cargarse en el navegador",
examples=["No pudimos cargar la invitación. Inténtalo nuevamente."],
)
countdown_label: str = Field(
...,
min_length=1,
max_length=100,
description="Etiqueta superior del contador regresivo",
examples=["NOS VEMOS EN"],
)
countdown_in_progress: str = Field(
...,
min_length=1,
max_length=100,
description="Texto mostrado cuando el evento está ocurriendo en tiempo real",
examples=["EVENTO EN CURSO"],
)
countdown_finished: str = Field(
...,
min_length=1,
max_length=100,
description="Texto mostrado cuando el evento ha culminado",
examples=["EVENTO FINALIZADO"],
)
@field_validator("event_date")
@classmethod
def validate_event_date(cls, v: str) -> str:
match = re.match(r"^\d{4}-\d{2}-\d{2}$", v.strip())
if not match:
raise ValueError("La fecha debe estar en formato YYYY-MM-DD")
try:
date.fromisoformat(v.strip())
except ValueError as err:
raise ValueError("Fecha de evento inválida") from err
return v.strip()
@field_validator("event_time")
@classmethod
def validate_event_time(cls, v: str) -> str:
match = re.match(r"^([01]\d|2[0-3]):([0-5]\d)$", v.strip())
if not match:
raise ValueError("La hora debe estar en formato HH:MM (24 horas)")
return v.strip()
@field_validator("event_timezone")
@classmethod
def validate_event_timezone(cls, v: str) -> str:
clean = v.strip()
try:
ZoneInfo(clean)
except (ZoneInfoNotFoundError, ValueError):
raise ValueError(f"Zona horaria IANA desconocida: {clean}")
return clean
@field_validator("map_url")
@classmethod
def validate_map_url(cls, v: str) -> str:
from .services.map_preview import validate_google_maps_url_format
clean = v.strip()
validate_google_maps_url_format(clean)
return clean
class InvitationConfigUpdate(InvitationConfigBase):
pass
class InvitationConfigResponse(InvitationConfigBase):
id: int = Field(default=1, description="Identificador único del registro singleton (siempre 1)")
updated_at: datetime | None = Field(default=None, description="Última modificación en UTC")
model_config = ConfigDict(from_attributes=True)
@field_serializer("updated_at")
def serialize_updated_at(self, dt: datetime | None) -> str | None:
if dt is None:
return None
if dt.tzinfo is None:
dt = dt.replace(tzinfo=UTC)
return dt.isoformat()
class GenerateMapPreviewRequest(BaseModel):
map_url: str | None = Field(
default=None,
description="URL de Google Maps a procesar. Si se omite, se usa la configurada actualmente.",
examples=["https://maps.app.goo.gl/abcd1234efgh5678"],
)
class GenerateMapPreviewResponse(BaseModel):
map_preview_url: str = Field(description="URL para acceder a la imagen de vista previa generada")
lat: float = Field(description="Latitud resuelta")
lng: float = Field(description="Longitud resuelta")
message: str = Field(default="Vista previa generada con éxito")
+1
View File
@@ -0,0 +1 @@
"""Service layer for RSVP and Config business logic."""
+44
View File
@@ -0,0 +1,44 @@
from datetime import UTC, datetime
from sqlalchemy import select
from sqlalchemy.orm import Session
from ..models import InvitationConfig
from ..schemas import InvitationConfigUpdate
def seed_default_config(db: Session) -> InvitationConfig:
"""Ensure the singleton config row (id=1) exists with default values."""
config = db.execute(
select(InvitationConfig).where(InvitationConfig.id == 1)
).scalar_one_or_none()
if not config:
config = InvitationConfig(id=1)
db.add(config)
db.commit()
db.refresh(config)
return config
def get_config(db: Session) -> InvitationConfig | None:
"""Retrieve the current invitation config."""
return db.execute(
select(InvitationConfig).where(InvitationConfig.id == 1)
).scalar_one_or_none()
def update_config(db: Session, update_in: InvitationConfigUpdate) -> InvitationConfig:
"""Update the invitation config singleton."""
config = get_config(db)
if not config:
config = seed_default_config(db)
for field, value in update_in.model_dump().items():
setattr(config, field, value)
config.updated_at = datetime.now(UTC)
db.commit()
db.refresh(config)
return config
+249
View File
@@ -0,0 +1,249 @@
import io
import math
import re
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
import httpx
from PIL import Image, ImageDraw
from ..config import settings
USER_AGENT = "bdinvite-map-preview/1.0 (contact: admin@roadtotech.me)"
GOOGLE_MAPS_DOMAINS = (
"maps.app.goo.gl",
"goo.gl",
"google.com",
"www.google.com",
"maps.google.com",
)
def is_google_maps_host(host: str) -> bool:
"""Check if the hostname belongs to Google Maps, Google share links, or Goo.gl shortlinks."""
clean_host = host.lower().strip()
if clean_host in ("maps.app.goo.gl", "goo.gl", "share.google"):
return True
if clean_host.startswith("maps.google."):
return True
if clean_host == "google.com" or clean_host.endswith(".google.com") or clean_host.endswith(".google"):
return True
# Regional domains like google.es, google.co, google.com.co
if re.match(r"^(?:www\.)?google\.[a-z.]+$", clean_host):
return True
return False
def validate_google_maps_url_format(url: str) -> None:
"""Validate that the given string is a structurally sound Google Maps URL."""
clean = url.strip()
if not clean:
raise ValueError("La URL de Google Maps no puede estar vacía.")
parsed = urlparse(clean)
if parsed.scheme not in ("http", "https"):
raise ValueError("La URL debe comenzar con http:// o https://")
if not parsed.netloc or not is_google_maps_host(parsed.netloc):
raise ValueError(
"La URL debe ser un enlace de Google Maps válido (ej. maps.app.goo.gl/... o google.com/maps/...)"
)
def extract_coordinates_from_text(text: str) -> tuple[float, float] | None:
"""Extract latitude and longitude from URL fragments, paths, or query strings."""
# Pattern 1: @<lat>,<lng> (e.g. /@34.143245,-118.255132,17z)
match_at = re.search(r"@(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)", text)
if match_at:
lat = float(match_at.group(1))
lng = float(match_at.group(2))
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
return lat, lng
# Pattern 2: !3d<lat>!4d<lng> (Google Maps protobuf data parameter)
match_data = re.search(r"!3d(-?\d+(?:\.\d+)?)(?:!4d|.*?!4d)(-?\d+(?:\.\d+)?)", text)
if match_data:
lat = float(match_data.group(1))
lng = float(match_data.group(2))
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
return lat, lng
# Pattern 3: Query parameters (q=lat,lng, ll=lat,lng, destination=lat,lng)
parsed = urlparse(text)
if parsed.query:
qs = parse_qs(parsed.query)
for param in ("q", "ll", "destination"):
if param in qs and qs[param]:
val = qs[param][0].strip()
m = re.match(r"^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$", val)
if m:
lat = float(m.group(1))
lng = float(m.group(2))
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
return lat, lng
return None
async def resolve_google_maps_coordinates(
map_url: str,
fallback_query: str | None = None,
) -> tuple[float, float, str]:
"""
Validate and resolve a Google Maps URL, following redirects if necessary,
and return (latitude, longitude, resolved_url).
"""
validate_google_maps_url_format(map_url)
clean_url = map_url.strip()
# Try direct extraction before making any network requests
direct_coords = extract_coordinates_from_text(clean_url)
if direct_coords:
return direct_coords[0], direct_coords[1], clean_url
# Follow HTTP redirects to resolve short links (maps.app.goo.gl, share.google, etc.)
resolved_url = clean_url
async with httpx.AsyncClient(
follow_redirects=True,
timeout=10.0,
headers={"User-Agent": USER_AGENT},
) as client:
try:
response = await client.get(clean_url)
resolved_url = str(response.url)
# Check redirect history URLs in case coordinates were in an intermediate hop
for hop in response.history:
hop_coords = extract_coordinates_from_text(str(hop.url))
if hop_coords:
return hop_coords[0], hop_coords[1], resolved_url
except httpx.RequestError as exc:
raise ValueError(f"No se pudo resolver el enlace de Google Maps: {exc}") from exc
# Try extraction on the final resolved destination URL
final_coords = extract_coordinates_from_text(resolved_url)
if final_coords:
return final_coords[0], final_coords[1], resolved_url
# Fallback: check if there is a place search query in the URL or query string
parsed = urlparse(resolved_url)
qs = parse_qs(parsed.query)
query_text = None
if "q" in qs and qs["q"]:
query_text = qs["q"][0]
elif "/place/" in parsed.path:
# e.g. /maps/place/Fresco+Ristorante/...
place_part = parsed.path.split("/place/")[1].split("/")[0]
query_text = unquote(place_part.replace("+", " "))
# Build search candidates for geocoding
candidates: list[str] = []
clean_fallback = fallback_query.strip() if fallback_query else None
if query_text and clean_fallback:
candidates.append(f"{query_text}, {clean_fallback}")
if clean_fallback:
for line in clean_fallback.splitlines():
line_str = line.strip().strip(",")
if line_str and line_str not in candidates:
candidates.append(line_str)
if clean_fallback not in candidates:
candidates.append(clean_fallback)
if query_text and query_text not in candidates:
candidates.append(query_text)
if candidates:
async with httpx.AsyncClient(timeout=8.0, headers={"User-Agent": USER_AGENT}) as client:
for candidate in candidates:
try:
nom_res = await client.get(
"https://nominatim.openstreetmap.org/search",
params={"q": candidate, "format": "json", "limit": 1},
)
if nom_res.status_code == 200:
results = nom_res.json()
if results and isinstance(results, list) and len(results) > 0:
lat = float(results[0]["lat"])
lng = float(results[0]["lon"])
if -90.0 <= lat <= 90.0 and -180.0 <= lng <= 180.0:
return lat, lng, resolved_url
except Exception:
pass
raise ValueError(
"No se pudieron extraer las coordenadas de la URL de Google Maps. "
"Asegúrate de que el enlace dirija a un lugar o coordenadas específicas."
)
def deg2num(lat_deg: float, lon_deg: float, zoom: int) -> tuple[float, float]:
"""Convert latitude and longitude to floating-point Slippy tile coordinates."""
lat_rad = math.radians(lat_deg)
n = 2.0**zoom
xtile = (lon_deg + 180.0) / 360.0 * n
ytile = (1.0 - math.asinh(math.tan(lat_rad)) / math.pi) / 2.0 * n
return xtile, ytile
async def generate_map_preview_image(
lat: float,
lng: float,
zoom: int = 16,
output_path: Path | None = None,
) -> Path:
"""
Download OpenStreetMap tiles surrounding (lat, lng), stitch them into a canvas,
crop a 400x400 square centered on the location, render a golden marker pin,
and save the resulting PNG to output_path (defaulting to settings.map_preview_file).
"""
dest_path = output_path or settings.map_preview_file
dest_path.parent.mkdir(parents=True, exist_ok=True)
xtile, ytile = deg2num(lat, lng, zoom)
x_int, y_int = int(xtile), int(ytile)
dx = xtile - x_int
dy = ytile - y_int
# Canvas of 3x3 tiles = 768x768 pixels
canvas = Image.new("RGB", (768, 768), color=(229, 227, 223))
async with httpx.AsyncClient(timeout=10.0, headers={"User-Agent": USER_AGENT}) as client:
for r_idx, y in enumerate(range(y_int - 1, y_int + 2)):
for c_idx, x in enumerate(range(x_int - 1, x_int + 2)):
tile_url = f"https://tile.openstreetmap.org/{zoom}/{x}/{y}.png"
try:
res = await client.get(tile_url)
if res.status_code == 200:
tile = Image.open(io.BytesIO(res.content)).convert("RGB")
canvas.paste(tile, (c_idx * 256, r_idx * 256))
except Exception:
# Keep neutral background tile if individual tile fails
pass
# Exact target location within the 768x768 canvas
cx = 256 + int(dx * 256)
cy = 256 + int(dy * 256)
# 400x400 crop centered on target coordinates
box = (cx - 200, cy - 200, cx + 200, cy + 200)
cropped = canvas.crop(box)
# Draw marker pin centered at (200, 200)
# The pin tip touches (200, 200)
draw = ImageDraw.Draw(cropped, "RGBA")
# Ground shadow underneath the pin tip
draw.ellipse((192, 198, 208, 204), fill=(40, 40, 40, 140))
# Golden pin pointer (inverted triangle)
draw.polygon([(188, 184), (212, 184), (200, 200)], fill="#d4a843", outline="#1a1a1a")
# Golden pin circular head
draw.ellipse((188, 170, 212, 194), fill="#d4a843", outline="#1a1a1a", width=2)
# Dark center eye
draw.ellipse((197, 179, 203, 185), fill="#1a1a1a")
# Save to disk as PNG
cropped.save(dest_path, "PNG", optimize=True)
return dest_path
+117
View File
@@ -0,0 +1,117 @@
from sqlalchemy import or_, select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from ..models import RSVP
from ..schemas import RSVPCreate, RSVPUpdate, normalize_phone
def create_rsvp(db: Session, rsvp_in: RSVPCreate) -> tuple[str, RSVP | None]:
"""Create an RSVP record.
Returns:
(status, rsvp_obj) where status is 'SUCCESS' or 'DUPLICATE'.
Raises:
ValueError if phone or field normalization fails.
"""
normalized_phone = normalize_phone(rsvp_in.phone)
# Check existence beforehand or rely on DB IntegrityError
existing = db.execute(
select(RSVP).where(RSVP.phone == normalized_phone)
).scalar_one_or_none()
if existing:
return "DUPLICATE", None
new_rsvp = RSVP(
name=rsvp_in.name,
phone=normalized_phone,
email=rsvp_in.email,
)
try:
db.add(new_rsvp)
db.commit()
db.refresh(new_rsvp)
return "SUCCESS", new_rsvp
except IntegrityError:
db.rollback()
return "DUPLICATE", None
except Exception:
db.rollback()
raise
def get_rsvps(db: Session, search: str | None = None) -> list[RSVP]:
"""Retrieve RSVPs, optionally filtered by search term."""
query = select(RSVP).order_by(RSVP.created_at.desc())
if search:
term = f"%{search.strip()}%"
query = query.where(
or_(
RSVP.name.ilike(term),
RSVP.phone.ilike(term),
RSVP.email.ilike(term),
)
)
return list(db.execute(query).scalars().all())
def get_rsvp_count(db: Session) -> int:
"""Get total count of RSVPs."""
query = select(RSVP)
return len(list(db.execute(query).scalars().all()))
def delete_rsvp(db: Session, rsvp_id: int) -> bool:
"""Delete an RSVP record by its ID. Returns True if deleted, False if not found."""
rsvp = db.execute(select(RSVP).where(RSVP.id == rsvp_id)).scalar_one_or_none()
if not rsvp:
return False
db.delete(rsvp)
db.commit()
return True
def update_rsvp(
db: Session,
rsvp_id: int,
update_in: RSVPUpdate,
) -> tuple[str, RSVP | None]:
"""Update an RSVP record using validated RSVPUpdate schema.
Returns:
("SUCCESS", rsvp)
("NOT_FOUND", None)
("DUPLICATE", None)
"""
rsvp = db.execute(select(RSVP).where(RSVP.id == rsvp_id)).scalar_one_or_none()
if not rsvp:
return "NOT_FOUND", None
if update_in.phone is not None:
existing = db.execute(
select(RSVP).where(RSVP.phone == update_in.phone, RSVP.id != rsvp_id)
).scalar_one_or_none()
if existing:
return "DUPLICATE", None
rsvp.phone = update_in.phone
if update_in.name is not None:
rsvp.name = update_in.name
if update_in.email is not None:
rsvp.email = update_in.email
try:
db.commit()
db.refresh(rsvp)
return "SUCCESS", rsvp
except IntegrityError:
db.rollback()
return "DUPLICATE", None
except Exception:
db.rollback()
raise
+28
View File
@@ -0,0 +1,28 @@
[project]
name = "bdinvite"
version = "0.1.0"
description = "Birthday Invitation RSVP Backend"
requires-python = ">=3.11"
dependencies = [
"fastapi[standard]>=0.115.0",
"uvicorn>=0.30.0",
"sqlalchemy>=2.0.0",
"pydantic>=2.0.0",
"pydantic-settings>=2.0.0",
"pillow>=10.0.0",
"httpx>=0.27.0",
"pyjwt[crypto]>=2.8.0",
]
[dependency-groups]
dev = [
"httpx>=0.27.0",
"pytest>=8.0.0",
"pytest-asyncio>=0.23.0",
"pyright>=1.1.0",
]
[tool.pyright]
venvPath = "."
venv = ".venv"
include = ["app", "tests"]
+6
View File
@@ -0,0 +1,6 @@
{
"venvPath": ".",
"venv": ".venv",
"include": ["app", "tests"],
"pythonVersion": "3.11"
}
+1
View File
@@ -0,0 +1 @@
"""Test suite for bdinvite backend."""
+102
View File
@@ -0,0 +1,102 @@
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.database import Base, get_db
from app.main import app
from app.services.config import seed_default_config
# Shared in-memory SQLite for testing via StaticPool
engine = create_engine(
"sqlite://",
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
@pytest.fixture(scope="function")
def db_session():
Base.metadata.create_all(bind=engine)
session = TestingSessionLocal()
seed_default_config(session)
try:
yield session
finally:
session.close()
Base.metadata.drop_all(bind=engine)
@pytest.fixture(scope="function")
def client(db_session):
def override_get_db():
try:
yield db_session
finally:
pass
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as test_client:
yield test_client
app.dependency_overrides.clear()
@pytest.fixture(scope="function")
def admin_identity():
from app.auth import Identity
return Identity(
subject="admin-001",
email="admin@example.com",
name="Admin User",
groups=["bdinvite_admins"],
)
@pytest.fixture(scope="function")
def guest_identity():
from app.auth import Identity
return Identity(
subject="guest-001",
email="guest@example.com",
name="Guest User",
groups=["guests"],
)
@pytest.fixture(scope="function")
def admin_session_cookie(admin_identity):
from app.auth import get_auth_adapter
adapter = get_auth_adapter()
session_id = adapter.establish_session(admin_identity)
return {adapter.session_cookie_name: session_id}
@pytest.fixture(scope="function")
def guest_session_cookie(guest_identity):
from app.auth import get_auth_adapter
adapter = get_auth_adapter()
session_id = adapter.establish_session(guest_identity)
return {adapter.session_cookie_name: session_id}
@pytest.fixture(scope="function")
def admin_client(db_session, admin_session_cookie):
def override_get_db():
try:
yield db_session
finally:
pass
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as test_client:
for k, v in admin_session_cookie.items():
test_client.cookies.set(k, v)
yield test_client
app.dependency_overrides.clear()
+266
View File
@@ -0,0 +1,266 @@
from unittest.mock import ANY, patch
import pytest
from fastapi.testclient import TestClient
from app.auth import Identity, get_auth_adapter
def test_remote_user_header_strictly_ignored(client: TestClient):
"""Negative gate: legacy Remote-User header without authenticated session must return 401."""
res = client.get("/birthday/api/admin/rsvps", headers={"Remote-User": "kiskaadee"})
assert res.status_code == 401
def test_admin_endpoints_require_authentication(client: TestClient):
"""Anonymous requests to admin endpoints must receive HTTP 401 Unauthorized."""
endpoints = [
("GET", "/birthday/api/admin/rsvps"),
("GET", "/birthday/api/admin/export"),
("GET", "/birthday/api/admin/config"),
("PUT", "/birthday/api/admin/config"),
("PATCH", "/birthday/api/admin/config"),
("POST", "/birthday/api/admin/map-preview/generate"),
("DELETE", "/birthday/api/admin/rsvps/1"),
("PATCH", "/birthday/api/admin/rsvps/1"),
]
for method, path in endpoints:
res = client.request(method, path)
assert res.status_code == 401, f"{method} {path} should require authentication"
assert res.headers.get("WWW-Authenticate") == "Bearer"
def test_admin_endpoints_require_remote_user(client: TestClient):
"""Backwards-compatible test: verify anonymous or legacy header calls are rejected with 401."""
endpoints = [
"/birthday/api/admin/rsvps",
"/birthday/api/admin/export",
"/birthday/api/admin/config",
]
for path in endpoints:
res = client.get(path)
assert res.status_code == 401, f"GET {path} should require authentication"
res_legacy = client.get(path, headers={"Remote-User": "kiskaadee"})
assert res_legacy.status_code == 401, f"GET {path} with Remote-User must still be rejected"
def test_admin_endpoints_forbidden_for_non_admin_users(client: TestClient, guest_session_cookie: dict[str, str]):
"""Authenticated non-admin users must receive HTTP 403 Forbidden."""
for k, v in guest_session_cookie.items():
client.cookies.set(k, v)
endpoints = [
("GET", "/birthday/api/admin/rsvps"),
("GET", "/birthday/api/admin/export"),
("GET", "/birthday/api/admin/config"),
("PUT", "/birthday/api/admin/config"),
("PATCH", "/birthday/api/admin/config"),
("POST", "/birthday/api/admin/map-preview/generate"),
("DELETE", "/birthday/api/admin/rsvps/1"),
("PATCH", "/birthday/api/admin/rsvps/1"),
]
for method, path in endpoints:
res = client.request(method, path)
assert res.status_code == 403, f"{method} {path} should be forbidden for guest user"
assert "bdinvite_admins" in res.json().get("detail", "")
# Even if non-admin injects Remote-User header, session identity governs -> 403
res_spoof = client.get("/birthday/api/admin/rsvps", headers={"Remote-User": "admin"})
assert res_spoof.status_code == 403
def test_admin_list_and_search_rsvps(admin_client: TestClient):
"""Authenticated admin user can list and search RSVPs."""
# Initially 0
res = admin_client.get("/birthday/api/admin/rsvps")
assert res.status_code == 200
assert res.json()["count"] == 0
# Add 3 invitees
admin_client.post(
"/birthday/api/rsvp",
json={"name": "Carlos Gomez", "phone": "300 111 2233", "email": "carlos@test.com"},
)
admin_client.post(
"/birthday/api/rsvp",
json={"name": "Maria Perez", "phone": "315 222 3344", "email": "maria@test.com"},
)
admin_client.post(
"/birthday/api/rsvp",
json={"name": "Juan Gomez", "phone": "320 333 4455", "email": None},
)
# List all
res = admin_client.get("/birthday/api/admin/rsvps")
assert res.status_code == 200
data = res.json()
assert data["count"] == 3
# Search by name
res_search = admin_client.get("/birthday/api/admin/rsvps?search=Gomez")
assert res_search.status_code == 200
search_data = res_search.json()
assert search_data["count"] == 2
# Search by phone substring
res_phone = admin_client.get("/birthday/api/admin/rsvps?search=315222")
assert res_phone.status_code == 200
assert res_phone.json()["count"] == 1
assert res_phone.json()["rsvps"][0]["name"] == "Maria Perez"
def test_admin_export_csv(admin_client: TestClient):
"""Authenticated admin user can export RSVPs as CSV."""
admin_client.post(
"/birthday/api/rsvp",
json={"name": "Sofia Vergara", "phone": "301 999 8877", "email": "sofia@hollywood.com"},
)
res = admin_client.get("/birthday/api/admin/export")
assert res.status_code == 200
assert res.headers["content-type"].startswith("text/csv")
assert 'filename="rsvps.csv"' in res.headers["content-disposition"]
content = res.text
lines = content.strip().split("\r\n") if "\r\n" in content else content.strip().split("\n")
assert lines[0] == "name,phone,email,created_at"
assert "Sofia Vergara,3019998877,sofia@hollywood.com" in lines[1]
def test_admin_delete_rsvp(client: TestClient, admin_client: TestClient):
"""Admin can delete RSVPs; anonymous requests are rejected."""
# Unauthorized without session
res_unauth = client.delete("/birthday/api/admin/rsvps/1")
assert res_unauth.status_code == 401
# 404 for non-existent RSVP
res_404 = admin_client.delete("/birthday/api/admin/rsvps/9999")
assert res_404.status_code == 404
# Create an RSVP
admin_client.post(
"/birthday/api/rsvp",
json={"name": "Lucas Silva", "phone": "300 444 5566", "email": "lucas@test.com"},
)
list_res = admin_client.get("/birthday/api/admin/rsvps")
assert list_res.status_code == 200
rsvps = list_res.json()["rsvps"]
assert len(rsvps) == 1
rsvp_id = rsvps[0]["id"]
# Delete successfully
del_res = admin_client.delete(f"/birthday/api/admin/rsvps/{rsvp_id}")
assert del_res.status_code == 204
# Confirm deletion
list_after = admin_client.get("/birthday/api/admin/rsvps")
assert list_after.json()["count"] == 0
def test_admin_update_rsvp(client: TestClient, admin_client: TestClient):
"""Admin can update RSVPs; anonymous requests are rejected."""
# Unauthorized without session
res_unauth = client.patch("/birthday/api/admin/rsvps/1", json={"name": "New Name"})
assert res_unauth.status_code == 401
# 404 for non-existent RSVP
res_404 = admin_client.patch(
"/birthday/api/admin/rsvps/9999",
json={"name": "New Name"},
)
assert res_404.status_code == 404
# Create two RSVPs
admin_client.post(
"/birthday/api/rsvp",
json={"name": "Person One", "phone": "300 111 2222", "email": "one@test.com"},
)
admin_client.post(
"/birthday/api/rsvp",
json={"name": "Person Two", "phone": "300 333 4444", "email": "two@test.com"},
)
list_res = admin_client.get("/birthday/api/admin/rsvps")
rsvps = list_res.json()["rsvps"]
id_one = next(r["id"] for r in rsvps if r["name"] == "Person One")
id_two = next(r["id"] for r in rsvps if r["name"] == "Person Two")
# Update Person One with valid new name and phone
patch_res = admin_client.patch(
f"/birthday/api/admin/rsvps/{id_one}",
json={"name": "Person One Updated", "phone": "+57 300 999 8888", "email": "newone@test.com"},
)
assert patch_res.status_code == 200
updated_data = patch_res.json()
assert updated_data["name"] == "Person One Updated"
assert updated_data["phone"] == "3009998888"
assert updated_data["email"] == "newone@test.com"
# Attempt to update Person One's phone to Person Two's phone -> 409
dup_res = admin_client.patch(
f"/birthday/api/admin/rsvps/{id_one}",
json={"phone": "300 333 4444"},
)
assert dup_res.status_code == 409
# Validation error for invalid phone
val_res = admin_client.patch(
f"/birthday/api/admin/rsvps/{id_one}",
json={"phone": "12345"},
)
assert val_res.status_code in (400, 422)
def test_admin_config_endpoints(admin_client: TestClient, client: TestClient):
"""Admin can retrieve and update config via PUT and PATCH; unauthenticated calls rejected."""
# Anonymous -> 401
assert client.get("/birthday/api/admin/config").status_code == 401
assert client.patch("/birthday/api/admin/config", json={}).status_code == 401
assert client.put("/birthday/api/admin/config", json={}).status_code == 401
# Admin GET config -> 200
res = admin_client.get("/birthday/api/admin/config")
assert res.status_code == 200
current_config = res.json()
assert current_config["honoree_name"] == "Isabelle Snow"
# Admin PATCH config -> 200
update_payload = {**current_config}
update_payload["honoree_name"] = "Isabelle Updated via PATCH"
patch_res = admin_client.patch("/birthday/api/admin/config", json=update_payload)
assert patch_res.status_code == 200
assert patch_res.json()["honoree_name"] == "Isabelle Updated via PATCH"
# Admin PUT config -> 200
update_payload["honoree_name"] = "Isabelle Updated via PUT"
put_res = admin_client.put("/birthday/api/admin/config", json=update_payload)
assert put_res.status_code == 200
assert put_res.json()["honoree_name"] == "Isabelle Updated via PUT"
@patch("app.routes.admin.resolve_google_maps_coordinates")
@patch("app.routes.admin.generate_map_preview_image")
def test_admin_map_preview_generate_endpoint(
mock_generate, mock_resolve, client: TestClient, admin_client: TestClient, tmp_path
):
"""Map preview generation requires admin; verifies successful generation."""
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
mock_generate.return_value = tmp_path / "map_preview.png"
# Anonymous -> 401
res_unauth = client.post(
"/birthday/api/admin/map-preview/generate",
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
)
assert res_unauth.status_code == 401
# Admin -> 200
res_admin = admin_client.post(
"/birthday/api/admin/map-preview/generate",
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
)
assert res_admin.status_code == 200
data = res_admin.json()
assert "/birthday/api/map-preview.png" in data["map_preview_url"]
assert data["lat"] == 34.1432
assert data["lng"] == -118.2551
+178
View File
@@ -0,0 +1,178 @@
import ast
from dataclasses import FrozenInstanceError
from pathlib import Path
from typing import Optional
import pytest
from fastapi import Request, Response
from fastapi.responses import RedirectResponse
from starlette.datastructures import Headers
from app.auth import AuthPort, Identity
class MockAuthAdapter:
"""Mock implementation of AuthPort for testing hexagonal boundary contract."""
def __init__(self, sessions: Optional[dict[str, Identity]] = None):
self.sessions = sessions or {}
def current_identity(self, request: Request) -> Optional[Identity]:
session_id = request.headers.get("X-Session-ID") or request.cookies.get("session_id")
if session_id and session_id in self.sessions:
return self.sessions[session_id]
return None
def login(self, request: Request) -> Response:
return RedirectResponse(url="https://auth.example.com/oauth/authorize", status_code=302)
def logout(self, request: Request) -> Response:
response = Response(content="logged out", status_code=200)
response.delete_cookie("session_id")
return response
class IncompleteAuthAdapter:
"""Incomplete adapter missing logout to test Protocol validation."""
def current_identity(self, request: Request) -> Optional[Identity]:
return None
def login(self, request: Request) -> Response:
return Response(content="login", status_code=200)
def create_mock_request(headers: Optional[dict[str, str]] = None, cookies: Optional[dict[str, str]] = None) -> Request:
"""Helper to build a Starlette/FastAPI Request instance with mock scope."""
header_list = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in (headers or {}).items()]
scope = {
"type": "http",
"method": "GET",
"path": "/test",
"headers": header_list,
"query_string": b"",
}
req = Request(scope)
if cookies:
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
header_list.append((b"cookie", cookie_header.encode("latin-1")))
req.scope["headers"] = header_list
return req
def test_identity_creation_defaults():
identity = Identity(subject="usr_123", email="user@example.com")
assert identity.subject == "usr_123"
assert identity.email == "user@example.com"
assert identity.name is None
assert identity.groups == []
def test_identity_creation_full():
identity = Identity(
subject="usr_456",
email="admin@example.com",
name="Admin User",
groups=["admins", "organizers"],
)
assert identity.subject == "usr_456"
assert identity.email == "admin@example.com"
assert identity.name == "Admin User"
assert identity.groups == ["admins", "organizers"]
def test_identity_none_groups_normalized():
identity = Identity(subject="usr_789", email="test@example.com", groups=None) # type: ignore[arg-type]
assert identity.groups == []
def test_identity_frozen_immutability():
identity = Identity(subject="usr_123", email="user@example.com")
with pytest.raises(FrozenInstanceError):
identity.subject = "usr_999" # type: ignore[misc]
with pytest.raises(FrozenInstanceError):
identity.email = "changed@example.com" # type: ignore[misc]
def test_identity_equality():
id1 = Identity(subject="usr_1", email="a@b.com", name="Alice", groups=["user"])
id2 = Identity(subject="usr_1", email="a@b.com", name="Alice", groups=["user"])
id3 = Identity(subject="usr_2", email="a@b.com", name="Alice", groups=["user"])
assert id1 == id2
assert id1 != id3
def test_auth_port_protocol_conformance():
adapter = MockAuthAdapter()
assert isinstance(adapter, AuthPort)
assert issubclass(MockAuthAdapter, AuthPort)
incomplete = IncompleteAuthAdapter()
assert not isinstance(incomplete, AuthPort)
assert not issubclass(IncompleteAuthAdapter, AuthPort)
def test_auth_port_behavior_with_mock():
expected_identity = Identity(
subject="sub_valid",
email="guest@example.com",
name="Guest User",
groups=["guests"],
)
adapter = MockAuthAdapter(sessions={"valid_token": expected_identity})
# Unauthenticated request
unauth_req = create_mock_request()
assert adapter.current_identity(unauth_req) is None
# Authenticated request via header
auth_req = create_mock_request(headers={"X-Session-ID": "valid_token"})
resolved = adapter.current_identity(auth_req)
assert resolved == expected_identity
assert resolved is not None
assert resolved.email == "guest@example.com"
# Login flow
login_resp = adapter.login(unauth_req)
assert isinstance(login_resp, Response)
assert login_resp.status_code == 302
assert login_resp.headers["location"] == "https://auth.example.com/oauth/authorize"
# Logout flow
logout_resp = adapter.logout(auth_req)
assert isinstance(logout_resp, Response)
assert logout_resp.status_code == 200
def test_architectural_isolation_zero_prohibited_imports():
"""Verify application domain files do not import OIDC, OAuth, JWT, cryptography, or proxy headers."""
backend_app_dir = Path(__file__).resolve().parent.parent / "app"
prohibited_keywords = {"oidc", "oauth", "jwt", "jose", "cryptography"}
# Files to inspect: routes, models, schemas, and auth port
domain_paths = [
backend_app_dir / "models.py",
backend_app_dir / "schemas.py",
backend_app_dir / "auth" / "port.py",
]
domain_paths.extend((backend_app_dir / "routes").glob("*.py"))
for py_file in domain_paths:
assert py_file.exists(), f"Expected domain file {py_file} to exist"
tree = ast.parse(py_file.read_text("utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
name_lower = alias.name.lower()
for prohibited in prohibited_keywords:
assert prohibited not in name_lower, (
f"Prohibited import '{alias.name}' found in {py_file}"
)
elif isinstance(node, ast.ImportFrom):
module_name = (node.module or "").lower()
for prohibited in prohibited_keywords:
assert prohibited not in module_name, (
f"Prohibited import from '{node.module}' found in {py_file}"
)
+156
View File
@@ -0,0 +1,156 @@
"""Automated Browser Acceptance Tests for Single Sign-On (SSO) Flow via Playwright.
Verifies Checkpoint 7 (CP7) requirements:
1. Browser navigates to /birthday/admin -> redirected to OIDC login form.
2. Form submitted with admin@example.com / password123.
3. Browser redirects back through callback -> receives HttpOnly cookie -> arrives on Admin Dashboard.
4. Admin Dashboard renders RSVPs table and authenticated user information.
5. Clicking Logout button revokes session -> returns to unauthenticated state.
"""
import json
import threading
import time
from typing import Generator
import httpx
import pytest
import uvicorn
from playwright.sync_api import BrowserContext, Page, sync_playwright
from app.config import settings
from app.database import Base, SessionLocal, engine
from app.models import RSVP
from app.services.config import seed_default_config
@pytest.fixture(scope="module")
def live_server() -> Generator[str, None, None]:
"""Start uvicorn server running FastAPI application in background daemon thread."""
# Ensure fresh DB tables and seed data
Base.metadata.create_all(bind=engine)
with SessionLocal() as db:
seed_default_config(db)
# Seed an RSVP item to guarantee the table renders records
test_rsvp = db.query(RSVP).filter_by(phone="3009998877").first()
if not test_rsvp:
test_rsvp = RSVP(
name="Invitado de Prueba",
phone="3009998877",
email="invitado@test.com",
)
db.add(test_rsvp)
db.commit()
config = uvicorn.Config(
"app.main:app",
host="127.0.0.1",
port=settings.APP_PORT,
log_level="warning",
)
server = uvicorn.Server(config)
thread = threading.Thread(target=server.run, daemon=True)
thread.start()
base_url = f"http://localhost:{settings.APP_PORT}"
# Poll until server is responding
ready = False
for _ in range(50):
try:
with httpx.Client() as client:
res = client.get(f"{base_url}/birthday/api/config", timeout=1.0)
if res.status_code == 200:
ready = True
break
except Exception:
time.sleep(0.1)
assert ready, f"Live server failed to start on {base_url}"
yield base_url
server.should_exit = True
thread.join(timeout=3.0)
@pytest.fixture(scope="module")
def browser_context():
"""Launch headless Chromium browser and provide an isolated context."""
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context()
yield context
context.close()
browser.close()
def test_browser_sso_complete_flow(live_server: str, browser_context: BrowserContext):
"""Execute complete end-to-end interactive browser authentication flow."""
page: Page = browser_context.new_page()
# 1. Unauthenticated navigation to /birthday/admin initiates login redirect
page.goto(f"{live_server}/birthday/admin")
# 2. Browser is redirected to OIDC provider login page
page.wait_for_url(lambda u: "8088" in u and "/authorize" in u, timeout=10000)
assert "8088" in page.url
# 3. Submit credentials on Mock OAuth2 Server login form
page.wait_for_selector("input[name='username']", timeout=5000)
page.fill("input[name='username']", "admin@example.com")
if page.locator("input[type='password']").count() > 0:
page.fill("input[type='password']", "password123")
if page.locator("textarea[name='claims']").count() > 0:
page.fill(
"textarea[name='claims']",
json.dumps({
"sub": "admin-001",
"email": "admin@example.com",
"name": "Admin User",
"groups": ["bdinvite_admins"],
}),
)
page.click("input[type='submit']")
# 4. Redirects through callback -> receives HttpOnly cookie -> arrives on Admin Dashboard
page.wait_for_url(lambda u: "/birthday/admin" in u and "8088" not in u, timeout=10000)
assert "/birthday/admin" in page.url
# Verify HttpOnly session cookie
cookies = browser_context.cookies("http://localhost:8000")
session_cookies = [c for c in cookies if c.get("name") == settings.SESSION_COOKIE_NAME]
assert len(session_cookies) >= 1, f"Missing {settings.SESSION_COOKIE_NAME} cookie"
session_cookie = session_cookies[0]
assert session_cookie.get("httpOnly") is True, "Session cookie must be HttpOnly"
same_site = session_cookie.get("sameSite")
assert same_site is not None and same_site.lower() in ["lax", "strict"]
# 5. Admin navigation header displays authenticated user info and working Logout button
page.wait_for_selector("[data-testid='user-info']", timeout=5000)
user_info_text = page.locator("[data-testid='user-info']").inner_text()
assert "admin@example.com" in user_info_text or "Admin User" in user_info_text
# 6. Admin Dashboard renders RSVPs table with live data
page.wait_for_selector("table", timeout=5000)
assert page.locator("table").is_visible()
# Confirm seeded attendee appears in the table
page.wait_for_selector("text=Invitado de Prueba", timeout=5000)
assert page.locator("text=Invitado de Prueba").is_visible()
# 7. Clicking "Logout" button revokes session and returns UI to unauthenticated state
logout_btn = page.locator("[data-testid='logout-btn']")
assert logout_btn.is_visible()
logout_btn.click()
# UI displays unauthenticated state
page.wait_for_selector("[data-testid='unauthenticated-state']", timeout=5000)
assert page.locator("[data-testid='unauthenticated-state']").is_visible()
# RSVPs table is no longer displayed
assert page.locator("table").count() == 0
page.close()
+110
View File
@@ -0,0 +1,110 @@
def test_get_config_public(client):
response = client.get("/birthday/api/config")
assert response.status_code == 200
data = response.json()
assert data["title"] == "Birthday Party"
assert data["honoree_name"] == "Isabelle Snow"
assert data["event_date"] == "2026-10-28"
assert data["event_time"] == "19:00"
assert data["event_timezone"] == "America/Bogota"
assert data["countdown_label"] == "NOS VEMOS EN"
def test_get_config_admin(client, admin_client):
res_unauth = client.get("/birthday/api/admin/config")
assert res_unauth.status_code == 401
res_auth = admin_client.get("/birthday/api/admin/config")
assert res_auth.status_code == 200
assert res_auth.json()["honoree_name"] == "Isabelle Snow"
def test_update_config_requires_admin(client, admin_client):
update_payload = {
"title": "Fiesta de Cumpleaños",
"invitation_text": "Estás invitado a la fiesta de",
"honoree_name": "Isabelle",
"event_date": "2026-11-15",
"event_time": "20:00",
"event_timezone": "America/Bogota",
"address_name": "Restaurante Central",
"address_lines": "Cra 7 # 12-34\nBogotá",
"map_preview_url": "https://example.com/map.png",
"map_url": "https://maps.google.com/?q=Bogota",
"rsvp_heading": "¿Nos vemos?",
"rsvp_cta": "CONFIRMAR",
"submit_label": "AHÍ ESTARÉ",
"msg_success": "¡Perfecto!",
"msg_success_greeting": "Gracias, {name}.",
"msg_duplicate": "Ya estás registrado.",
"msg_error": "Error.",
"msg_config_error": "Error al cargar.",
"countdown_label": "FALTAN",
"countdown_in_progress": "EN VIVO",
"countdown_finished": "TERMINADO",
}
# Without session -> 401
res = client.put("/birthday/api/admin/config", json=update_payload)
assert res.status_code == 401
# With admin session -> 200
res_auth = admin_client.put(
"/birthday/api/admin/config",
json=update_payload,
)
assert res_auth.status_code == 200
data = res_auth.json()
assert data["title"] == "Fiesta de Cumpleaños"
assert data["honoree_name"] == "Isabelle"
assert data["event_date"] == "2026-11-15"
# Public endpoint reflects updated config immediately
res_pub = client.get("/birthday/api/config")
assert res_pub.status_code == 200
assert res_pub.json()["title"] == "Fiesta de Cumpleaños"
def test_update_config_invalid_timezone(admin_client):
invalid_payload = {
"title": "Party",
"invitation_text": "Invited",
"honoree_name": "Name",
"event_date": "2026-11-15",
"event_time": "20:00",
"event_timezone": "NonExistent/Invalid_Timezone",
"address_name": "Place",
"address_lines": "Line 1",
"map_preview_url": "https://example.com/map.png",
"map_url": "https://maps.google.com",
"rsvp_heading": "¿Nos vemos?",
"rsvp_cta": "CONFIRMA",
"submit_label": "ENVIAR",
"msg_success": "OK",
"msg_success_greeting": "Hola {name}",
"msg_duplicate": "Dup",
"msg_error": "Err",
"msg_config_error": "CfgErr",
"countdown_label": "FALTAN",
"countdown_in_progress": "CURSO",
"countdown_finished": "FIN",
}
res = admin_client.put(
"/birthday/api/admin/config",
json=invalid_payload,
)
assert res.status_code == 422
def test_spa_catch_all(client):
res = client.get("/birthday", follow_redirects=False)
assert res.status_code == 307
assert res.headers["location"] == "/birthday/"
res_followed = client.get("/birthday", follow_redirects=True)
assert res_followed.status_code == 200
res_subpath = client.get("/birthday/admin")
assert res_subpath.status_code == 200
res_font = client.get("/birthday/fonts/display.woff2")
assert res_font.status_code == 200
+419
View File
@@ -0,0 +1,419 @@
"""Tests for FastAPI dependency injection and authorization policies (Checkpoint 5)."""
from collections.abc import Generator
from typing import Annotated, Optional
import pytest
from fastapi import APIRouter, Depends, FastAPI, HTTPException, status
from fastapi.testclient import TestClient
from starlette.requests import Request
from app.auth import (
AdminUserDep,
AuthenticatedUserDep,
CurrentIdentityDep,
Identity,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
get_auth_adapter,
get_current_identity,
require_admin,
require_authenticated,
require_group,
set_auth_adapter,
)
FIXTURE_ISSUER = "http://localhost:8088/default"
FIXTURE_CLIENT_ID = "bdinvite-client"
FIXTURE_CLIENT_SECRET = "bdinvite-secret"
FIXTURE_REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
@pytest.fixture
def oidc_config() -> OIDCConfig:
return OIDCConfig(
issuer=FIXTURE_ISSUER,
client_id=FIXTURE_CLIENT_ID,
client_secret=FIXTURE_CLIENT_SECRET,
redirect_uri=FIXTURE_REDIRECT_URI,
)
@pytest.fixture
def oidc_client(oidc_config: OIDCConfig) -> OIDCClient:
return OIDCClient(oidc_config)
@pytest.fixture
def auth_adapter(oidc_client: OIDCClient) -> Generator[OIDCAuthAdapter, None, None]:
adapter = OIDCAuthAdapter(
client=oidc_client,
session_cookie_name="bdinvite_session",
cookie_secure=False,
cookie_samesite="lax",
session_lifetime=3600.0,
)
set_auth_adapter(adapter)
yield adapter
set_auth_adapter(None)
def create_request(
headers: dict[str, str] | None = None,
cookies: dict[str, str] | None = None,
) -> Request:
header_list: list[tuple[bytes, bytes]] = []
if headers:
for k, v in headers.items():
header_list.append((k.lower().encode("latin-1"), v.encode("latin-1")))
if cookies:
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
header_list.append((b"cookie", cookie_header.encode("latin-1")))
scope = {
"type": "http",
"method": "GET",
"path": "/test",
"headers": header_list,
"query_string": b"",
}
return Request(scope)
@pytest.fixture
def test_app(auth_adapter: OIDCAuthAdapter) -> FastAPI:
"""Isolated FastAPI test application mounted with test endpoints."""
app = FastAPI(title="Dependency Test App")
router = APIRouter()
@router.get("/me")
def me_endpoint(identity: CurrentIdentityDep):
if identity is None:
return {"authenticated": False, "identity": None}
return {
"authenticated": True,
"identity": {
"subject": identity.subject,
"email": identity.email,
"name": identity.name,
"groups": identity.groups,
},
}
@router.get("/authenticated")
def authenticated_endpoint(user: AuthenticatedUserDep):
return {
"subject": user.subject,
"email": user.email,
"groups": user.groups,
}
@router.get("/admin")
def admin_endpoint(admin: AdminUserDep):
return {
"subject": admin.subject,
"email": admin.email,
"groups": admin.groups,
}
require_staff = require_group("staff")
@router.get("/staff")
def staff_endpoint(user: Annotated[Identity, Depends(require_staff)]):
return {
"subject": user.subject,
"email": user.email,
"groups": user.groups,
}
app.include_router(router)
return app
@pytest.fixture
def client(test_app: FastAPI) -> Generator[TestClient, None, None]:
with TestClient(test_app) as c:
yield c
# ============================================================================
# Unit Tests (Direct Dependency Invocations)
# ============================================================================
def test_get_current_identity_anonymous(auth_adapter: OIDCAuthAdapter):
"""Anonymous request yields None on get_current_identity."""
req_empty = create_request()
assert get_current_identity(req_empty, adapter=auth_adapter) is None
# Default adapter fallback (when adapter argument is omitted)
assert get_current_identity(req_empty) is None
def test_get_current_identity_with_valid_session(auth_adapter: OIDCAuthAdapter):
"""Valid session cookie yields active Identity on get_current_identity."""
admin_id, session_id = auth_adapter.authenticate_and_establish_session(
"admin@example.com", "password123"
)
req = create_request(cookies={auth_adapter.session_cookie_name: session_id})
resolved = get_current_identity(req, adapter=auth_adapter)
assert resolved == admin_id
assert resolved is not None
assert resolved.email == "admin@example.com"
assert "bdinvite_admins" in resolved.groups
def test_get_current_identity_with_valid_bearer_token(
auth_adapter: OIDCAuthAdapter, oidc_client: OIDCClient
):
"""Valid Bearer token yields active Identity on get_current_identity."""
_, tokens = oidc_client.authenticate_user("guest@example.com", "guestpass456")
id_token = tokens["id_token"]
req = create_request(headers={"Authorization": f"Bearer {id_token}"})
resolved = get_current_identity(req, adapter=auth_adapter)
assert resolved is not None
assert resolved.email == "guest@example.com"
assert resolved.groups == ["guests"]
def test_require_authenticated_anonymous_raises_401():
"""Anonymous request (identity=None) raises HTTP 401 on require_authenticated."""
with pytest.raises(HTTPException) as exc_info:
require_authenticated(identity=None)
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED
assert exc_info.value.detail == "Authentication required"
assert exc_info.value.headers is not None
assert exc_info.value.headers.get("WWW-Authenticate") == "Bearer"
def test_require_authenticated_success():
"""Authenticated user returns Identity from require_authenticated."""
identity = Identity(
subject="sub-123",
email="user@example.com",
groups=["guests"],
)
result = require_authenticated(identity=identity)
assert result == identity
def test_require_group_anonymous_raises_401():
"""Anonymous user raises HTTP 401 on require_group."""
group_dep = require_group("staff")
with pytest.raises(HTTPException) as exc_info:
group_dep(identity=None)
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED
def test_require_group_missing_group_raises_403():
"""Authenticated user missing the required group raises HTTP 403 Forbidden."""
group_dep = require_group("staff")
user = Identity(
subject="sub-123",
email="user@example.com",
groups=["guests"],
)
with pytest.raises(HTTPException) as exc_info:
group_dep(identity=user)
assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN
assert "staff" in exc_info.value.detail
def test_require_group_success():
"""Authenticated user possessing the required group returns Identity."""
group_dep = require_group("staff")
user = Identity(
subject="sub-123",
email="user@example.com",
groups=["staff", "guests"],
)
result = group_dep(identity=user)
assert result == user
def test_require_admin_anonymous_raises_401():
"""Anonymous request raises HTTP 401 on require_admin."""
with pytest.raises(HTTPException) as exc_info:
require_admin(identity=None)
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED
def test_require_admin_non_admin_raises_403():
"""Authenticated non-admin user raises HTTP 403 on require_admin."""
guest_user = Identity(
subject="guest-001",
email="guest@example.com",
groups=["guests"],
)
with pytest.raises(HTTPException) as exc_info:
require_admin(identity=guest_user)
assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN
assert "bdinvite_admins" in exc_info.value.detail
def test_require_admin_success():
"""Authenticated admin user successfully yields Identity object on require_admin."""
admin_user = Identity(
subject="admin-001",
email="admin@example.com",
groups=["bdinvite_admins"],
)
result = require_admin(identity=admin_user)
assert result == admin_user
assert result.subject == "admin-001"
assert result.email == "admin@example.com"
assert result.groups == ["bdinvite_admins"]
# ============================================================================
# FastAPI Integration Tests (End-to-End Dependency Injection via TestClient)
# ============================================================================
def test_api_anonymous_get_current_identity(client: TestClient):
"""Anonymous request to /me yields None identity."""
resp = client.get("/me")
assert resp.status_code == 200
data = resp.json()
assert data["authenticated"] is False
assert data["identity"] is None
def test_api_authenticated_user_get_current_identity(
client: TestClient, auth_adapter: OIDCAuthAdapter
):
"""Authenticated user with session cookie resolves Identity on /me."""
guest_id, session_id = auth_adapter.authenticate_and_establish_session(
"guest@example.com", "guestpass456"
)
client.cookies.set(auth_adapter.session_cookie_name, session_id)
resp = client.get("/me")
assert resp.status_code == 200
data = resp.json()
assert data["authenticated"] is True
assert data["identity"]["email"] == "guest@example.com"
assert data["identity"]["groups"] == ["guests"]
def test_api_require_authenticated_anonymous_returns_401(client: TestClient):
"""Anonymous request to /authenticated raises HTTP 401 Unauthorized."""
resp = client.get("/authenticated")
assert resp.status_code == 401
assert resp.headers.get("WWW-Authenticate") == "Bearer"
assert resp.json()["detail"] == "Authentication required"
def test_api_require_authenticated_with_session_returns_200(
client: TestClient, auth_adapter: OIDCAuthAdapter
):
"""Authenticated request to /authenticated returns 200 and Identity."""
_, session_id = auth_adapter.authenticate_and_establish_session(
"guest@example.com", "guestpass456"
)
client.cookies.set(auth_adapter.session_cookie_name, session_id)
resp = client.get("/authenticated")
assert resp.status_code == 200
data = resp.json()
assert data["email"] == "guest@example.com"
def test_api_require_admin_anonymous_returns_401(client: TestClient):
"""Anonymous request to /admin raises HTTP 401 Unauthorized."""
resp = client.get("/admin")
assert resp.status_code == 401
assert resp.headers.get("WWW-Authenticate") == "Bearer"
def test_api_require_admin_non_admin_returns_403(
client: TestClient, auth_adapter: OIDCAuthAdapter
):
"""Authenticated non-admin user (guest) raises HTTP 403 Forbidden on /admin."""
_, session_id = auth_adapter.authenticate_and_establish_session(
"guest@example.com", "guestpass456"
)
client.cookies.set(auth_adapter.session_cookie_name, session_id)
resp = client.get("/admin")
assert resp.status_code == 403
assert "bdinvite_admins" in resp.json()["detail"]
def test_api_require_admin_admin_returns_200(
client: TestClient, auth_adapter: OIDCAuthAdapter
):
"""Authenticated admin user (bdinvite_admins) succeeds with HTTP 200 on /admin."""
admin_id, session_id = auth_adapter.authenticate_and_establish_session(
"admin@example.com", "password123"
)
client.cookies.set(auth_adapter.session_cookie_name, session_id)
resp = client.get("/admin")
assert resp.status_code == 200
data = resp.json()
assert data["email"] == "admin@example.com"
assert data["groups"] == ["bdinvite_admins"]
def test_api_bearer_token_authentication_flow(
client: TestClient, oidc_client: OIDCClient
):
"""Bearer token in Authorization header successfully resolves through dependencies."""
# 1. Guest user Bearer token -> /authenticated succeeds, /admin fails with 403
_, guest_tokens = oidc_client.authenticate_user(
"guest@example.com", "guestpass456"
)
guest_headers = {"Authorization": f"Bearer {guest_tokens['id_token']}"}
resp_guest_auth = client.get("/authenticated", headers=guest_headers)
assert resp_guest_auth.status_code == 200
assert resp_guest_auth.json()["email"] == "guest@example.com"
resp_guest_admin = client.get("/admin", headers=guest_headers)
assert resp_guest_admin.status_code == 403
# 2. Admin user Bearer token -> /admin succeeds with 200
_, admin_tokens = oidc_client.authenticate_user("admin@example.com", "password123")
admin_headers = {"Authorization": f"Bearer {admin_tokens['id_token']}"}
resp_admin = client.get("/admin", headers=admin_headers)
assert resp_admin.status_code == 200
assert resp_admin.json()["email"] == "admin@example.com"
assert resp_admin.json()["groups"] == ["bdinvite_admins"]
def test_api_dependency_overrides(test_app: FastAPI, client: TestClient):
"""FastAPI dependency overrides function cleanly on get_current_identity."""
# 1. Override with mock admin identity
mock_admin = Identity(
subject="mock-admin",
email="mockadmin@example.com",
groups=["bdinvite_admins"],
)
test_app.dependency_overrides[get_current_identity] = lambda: mock_admin
resp = client.get("/admin")
assert resp.status_code == 200
assert resp.json()["email"] == "mockadmin@example.com"
# 2. Override with mock guest identity (missing bdinvite_admins)
mock_guest = Identity(
subject="mock-guest",
email="mockguest@example.com",
groups=["guests"],
)
test_app.dependency_overrides[get_current_identity] = lambda: mock_guest
resp = client.get("/admin")
assert resp.status_code == 403
# 3. Override with anonymous (None)
test_app.dependency_overrides[get_current_identity] = lambda: None
resp = client.get("/admin")
assert resp.status_code == 401
test_app.dependency_overrides.clear()
+388
View File
@@ -0,0 +1,388 @@
"""Tests for OIDC Identity & Group Extraction, Integrity Invariants, and Fixture Users."""
from dataclasses import FrozenInstanceError
import json
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
from starlette.requests import Request
from app.auth import (
Identity,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
TokenValidationError,
claims_to_identity,
extract_identity_from_claims,
resolve_claim_path,
)
FIXTURE_ISSUER = "http://localhost:8088/default"
FIXTURE_CLIENT_ID = "bdinvite-client"
FIXTURE_CLIENT_SECRET = "bdinvite-secret"
FIXTURE_REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
@pytest.fixture
def oidc_config() -> OIDCConfig:
return OIDCConfig(
issuer=FIXTURE_ISSUER,
client_id=FIXTURE_CLIENT_ID,
client_secret=FIXTURE_CLIENT_SECRET,
redirect_uri=FIXTURE_REDIRECT_URI,
)
@pytest.fixture
def oidc_client(oidc_config: OIDCConfig) -> OIDCClient:
return OIDCClient(oidc_config)
def create_request(
headers: dict[str, str] | None = None,
cookies: dict[str, str] | None = None,
) -> Request:
header_list: list[tuple[bytes, bytes]] = []
if headers:
for k, v in headers.items():
header_list.append((k.lower().encode("latin-1"), v.encode("latin-1")))
if cookies:
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
header_list.append((b"cookie", cookie_header.encode("latin-1")))
scope = {
"type": "http",
"method": "GET",
"path": "/birthday/api/admin/rsvps",
"headers": header_list,
"query_string": b"",
}
return Request(scope)
def obtain_auth_code_from_fixture(
authorization_url: str,
username: str,
claims: dict | None = None,
) -> tuple[str, str]:
parsed_url = urlparse(authorization_url)
auth_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"
query_params = parse_qs(parsed_url.query)
flat_params = {k: v[0] for k, v in query_params.items()}
post_data: dict[str, str] = {"username": username}
if claims:
post_data["claims"] = json.dumps(claims)
with httpx.Client() as client:
resp = client.post(
auth_endpoint,
params=flat_params,
data=post_data,
follow_redirects=False,
)
assert resp.status_code == 302
location = resp.headers["location"]
redirect_parsed = urlparse(location)
callback_params = parse_qs(redirect_parsed.query)
return callback_params["code"][0], callback_params["state"][0]
# ============================================================================
# 1. Identity Resolution & Mapping Unit Tests
# ============================================================================
def test_resolve_claim_path():
claims = {
"groups": ["group1", "group2"],
"realm_access": {"roles": ["admin", "editor"]},
"deep": {"nested": {"path": ["value"]}},
}
assert resolve_claim_path(claims, "groups") == ["group1", "group2"]
assert resolve_claim_path(claims, "realm_access.roles") == ["admin", "editor"]
assert resolve_claim_path(claims, "deep.nested.path") == ["value"]
assert resolve_claim_path(claims, "nonexistent") is None
assert resolve_claim_path(claims, "deep.wrong.path") is None
def test_claims_to_identity_standard_mapping():
claims = {
"sub": "user_101",
"email": "user@example.com",
"name": "Normal User",
"groups": ["engineering", "security"],
}
identity = claims_to_identity(claims)
assert isinstance(identity, Identity)
assert identity.subject == "user_101"
assert identity.email == "user@example.com"
assert identity.name == "Normal User"
assert identity.groups == ["engineering", "security"]
def test_claims_to_identity_custom_group_claim_path():
claims = {
"sub": "user_custom",
"email": "custom@example.com",
"roles": ["operator", "auditor"],
}
identity = extract_identity_from_claims(claims, groups_claim="roles")
assert identity.groups == ["operator", "auditor"]
# Nested path
nested_claims = {
"sub": "user_nested",
"email": "nested@example.com",
"resource_access": {"bdinvite": {"roles": ["admin"]}},
}
identity_nested = extract_identity_from_claims(
nested_claims, groups_claim="resource_access.bdinvite.roles"
)
assert identity_nested.groups == ["admin"]
def test_claims_to_identity_normalizes_group_types():
# Single string group
c1 = {"sub": "u1", "email": "u1@e.com", "groups": "only_one_group"}
assert claims_to_identity(c1).groups == ["only_one_group"]
# Comma-separated string
c2 = {"sub": "u2", "email": "u2@e.com", "groups": "admin, billing, support"}
assert claims_to_identity(c2).groups == ["admin", "billing", "support"]
# Non-string elements in list are stringified
c3 = {"sub": "u3", "email": "u3@e.com", "groups": [123, True, "staff"]}
assert claims_to_identity(c3).groups == ["123", "True", "staff"]
def test_claims_to_identity_missing_or_empty_groups_defaults_to_empty_list():
# Absent groups claim
c1 = {"sub": "u1", "email": "u1@e.com", "name": "No Groups"}
id1 = claims_to_identity(c1)
assert id1.groups == []
# groups is None
c2 = {"sub": "u2", "email": "u2@e.com", "groups": None}
id2 = claims_to_identity(c2)
assert id2.groups == []
# groups is empty list
c3 = {"sub": "u3", "email": "u3@e.com", "groups": []}
id3 = claims_to_identity(c3)
assert id3.groups == []
# groups is empty string
c4 = {"sub": "u4", "email": "u4@e.com", "groups": " "}
id4 = claims_to_identity(c4)
assert id4.groups == []
def test_claims_to_identity_requires_sub():
with pytest.raises(TokenValidationError) as exc_info:
claims_to_identity({"email": "nosub@example.com"})
assert "sub" in str(exc_info.value.detail).lower()
with pytest.raises(TokenValidationError) as exc_info:
claims_to_identity({"sub": " ", "email": "blanksub@example.com"})
assert "sub" in str(exc_info.value.detail).lower()
def test_claims_to_identity_email_and_name_fallbacks():
# Fallback to preferred_username
c1 = {"sub": "usr_abc", "preferred_username": "preferred@example.com"}
id1 = claims_to_identity(c1)
assert id1.email == "preferred@example.com"
assert id1.name is None
# Fallback to sub@local
c2 = {"sub": "usr_xyz"}
id2 = claims_to_identity(c2)
assert id2.email == "usr_xyz@local"
assert id2.name is None
# ============================================================================
# 2. Verification Against Seeded Fixture Users
# ============================================================================
def test_fixture_admin_user_password_grant(oidc_client: OIDCClient):
"""Verify authenticating admin@example.com resolves to Identity with bdinvite_admins group."""
identity, tokens = oidc_client.authenticate_user(
username="admin@example.com",
password="password123",
)
assert isinstance(identity, Identity)
assert identity.subject == "admin-001"
assert identity.email == "admin@example.com"
assert identity.name == "Admin User"
assert identity.groups == ["bdinvite_admins"]
assert "access_token" in tokens
assert "id_token" in tokens
def test_fixture_guest_user_password_grant(oidc_client: OIDCClient):
"""Verify authenticating guest@example.com resolves to Identity with guests group."""
identity, tokens = oidc_client.authenticate_user(
username="guest@example.com",
password="password123",
)
assert isinstance(identity, Identity)
assert identity.subject == "guest-001"
assert identity.email == "guest@example.com"
assert identity.name == "Guest User"
assert identity.groups == ["guests"]
assert "access_token" in tokens
assert "id_token" in tokens
@pytest.mark.asyncio
async def test_async_fixture_admin_and_guest_user(oidc_client: OIDCClient):
admin_id, _ = await oidc_client.aauthenticate_user("admin@example.com", "password123")
assert admin_id.subject == "admin-001"
assert admin_id.groups == ["bdinvite_admins"]
guest_id, _ = await oidc_client.aauthenticate_user("guest@example.com", "password123")
assert guest_id.subject == "guest-001"
assert guest_id.groups == ["guests"]
def test_fixture_admin_authorization_code_flow(oidc_client: OIDCClient):
"""Verify complete authorization code flow with admin fixture user."""
auth_url, tx = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="admin@example.com")
identity, tokens = oidc_client.process_callback(
code=code,
state=returned_state,
extra_params={"username": "admin@example.com"},
)
assert identity.subject == "admin-001"
assert identity.email == "admin@example.com"
assert identity.name == "Admin User"
assert identity.groups == ["bdinvite_admins"]
def test_fixture_guest_authorization_code_flow(oidc_client: OIDCClient):
"""Verify complete authorization code flow with guest fixture user."""
auth_url, tx = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="guest@example.com")
identity, tokens = oidc_client.process_callback(
code=code,
state=returned_state,
extra_params={"username": "guest@example.com"},
)
assert identity.subject == "guest-001"
assert identity.email == "guest@example.com"
assert identity.name == "Guest User"
assert identity.groups == ["guests"]
# ============================================================================
# 3. Identity Origin Integrity (Authoritative Provenance) Tests
# ============================================================================
def test_identity_origin_integrity_rejects_unvalidated_request_headers(
oidc_client: OIDCClient,
):
"""Verify that unvalidated request headers (e.g. X-User, X-Email, X-Groups)
CANNOT forge or inject an Identity. Application code must only trust
cryptographically verified authentication artifacts.
"""
adapter = OIDCAuthAdapter(client=oidc_client)
# 1. Attacker attempts to spoof admin identity via custom headers
spoof_req = create_request(
headers={
"X-User": "admin-001",
"X-User-Email": "admin@example.com",
"X-User-Name": "Admin User",
"X-Groups": "bdinvite_admins",
"X-Remote-User": "admin@example.com",
"X-Forwarded-User": "admin-001",
}
)
resolved = adapter.current_identity(spoof_req)
assert resolved is None, "Adapter must NEVER construct an Identity from raw unvalidated headers"
# 2. Attacker attempts to forge session cookie with fake ID
fake_session_req = create_request(cookies={"session_id": "forged_random_session_key"})
assert adapter.current_identity(fake_session_req) is None
# 3. Legitimate session established through verified callback succeeds
legit_identity = Identity(
subject="admin-001",
email="admin@example.com",
name="Admin User",
groups=["bdinvite_admins"],
)
session_id = adapter.establish_session(legit_identity)
valid_session_req = create_request(cookies={"session_id": session_id})
assert adapter.current_identity(valid_session_req) == legit_identity
def test_identity_origin_integrity_bearer_token_validation(oidc_client: OIDCClient):
"""Verify Bearer token in Authorization header is strictly cryptographically validated."""
adapter = OIDCAuthAdapter(client=oidc_client)
# 1. Genuine token from fixture user
_, tokens = oidc_client.authenticate_user("admin@example.com", "password123")
valid_id_token = tokens["id_token"]
req_with_valid_bearer = create_request(
headers={"Authorization": f"Bearer {valid_id_token}"}
)
resolved = adapter.current_identity(req_with_valid_bearer)
assert resolved is not None
assert resolved.subject == "admin-001"
assert resolved.email == "admin@example.com"
assert resolved.groups == ["bdinvite_admins"]
# 2. Tampered token signature fails verification and yields None
parts = valid_id_token.split(".")
tampered_sig = ("X" if parts[2][0] != "X" else "Y") + parts[2][1:]
tampered_token = f"{parts[0]}.{parts[1]}.{tampered_sig}"
req_with_tampered_bearer = create_request(
headers={"Authorization": f"Bearer {tampered_token}"}
)
assert adapter.current_identity(req_with_tampered_bearer) is None
# 3. Forged payload with valid signature prefix fails verification
req_garbage = create_request(headers={"Authorization": "Bearer not.a.valid.jwt"})
assert adapter.current_identity(req_garbage) is None
# ============================================================================
# 4. Identity Immutability Tests
# ============================================================================
def test_identity_frozen_immutability():
"""Verify that domain Identity instances cannot be mutated at runtime."""
identity = Identity(
subject="admin-001",
email="admin@example.com",
name="Admin User",
groups=["bdinvite_admins"],
)
with pytest.raises(FrozenInstanceError):
identity.subject = "hacker" # type: ignore[misc]
with pytest.raises(FrozenInstanceError):
identity.email = "hacker@example.com" # type: ignore[misc]
with pytest.raises(FrozenInstanceError):
identity.name = "Hacker" # type: ignore[misc]
with pytest.raises(FrozenInstanceError):
identity.groups = ["superusers"] # type: ignore[misc]
+148
View File
@@ -0,0 +1,148 @@
from unittest.mock import ANY, patch
import pytest
from app.config import settings
from app.services.map_preview import (
deg2num,
extract_coordinates_from_text,
is_google_maps_host,
validate_google_maps_url_format,
)
def test_is_google_maps_host():
assert is_google_maps_host("maps.app.goo.gl")
assert is_google_maps_host("share.google")
assert is_google_maps_host("goo.gl")
assert is_google_maps_host("maps.google.com")
assert is_google_maps_host("google.com")
assert is_google_maps_host("www.google.com")
assert is_google_maps_host("google.es")
assert is_google_maps_host("maps.google.co.uk")
assert not is_google_maps_host("example.com")
assert not is_google_maps_host("bing.com")
assert not is_google_maps_host("evilgoogle.com")
def test_validate_google_maps_url_format():
validate_google_maps_url_format("https://maps.app.goo.gl/354784424357732")
validate_google_maps_url_format("https://www.google.com/maps/place/Fresco/@34.1,-118.2,17z")
validate_google_maps_url_format("https://maps.google.com/?q=34.1,-118.2")
with pytest.raises(ValueError, match="no puede estar vacía"):
validate_google_maps_url_format("")
with pytest.raises(ValueError, match="comenzar con http"):
validate_google_maps_url_format("ftp://maps.google.com")
with pytest.raises(ValueError, match="enlace de Google Maps válido"):
validate_google_maps_url_format("https://apple.com/maps")
def test_extract_coordinates_from_text():
# 1. @lat,lng
coords = extract_coordinates_from_text("https://google.com/maps/place/Venue/@34.143245,-118.255132,17z")
assert coords == (34.143245, -118.255132)
# 2. !3dlat!4dlng
coords = extract_coordinates_from_text("https://google.com/maps/data=!4m6!3m5!1s0x0!8m2!3d4.6534!4d-74.0564")
assert coords == (4.6534, -74.0564)
# 3. Query params: q=lat,lng
coords = extract_coordinates_from_text("https://maps.google.com/?q=34.1432,-118.2551")
assert coords == (34.1432, -118.2551)
# 4. Query params: ll=lat,lng
coords = extract_coordinates_from_text("https://maps.google.com/maps?ll=34.1432,-118.2551&z=16")
assert coords == (34.1432, -118.2551)
# 5. Non-coordinate text
assert extract_coordinates_from_text("https://maps.google.com/?q=Eiffel+Tower") is None
def test_deg2num():
xtile, ytile = deg2num(34.1432, -118.2551, 16)
assert int(xtile) == 11240
assert int(ytile) == 26148
@patch("app.routes.admin.resolve_google_maps_coordinates")
@patch("app.routes.admin.generate_map_preview_image")
def test_admin_generate_map_preview_endpoint(mock_generate, mock_resolve, client, admin_client, tmp_path):
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
mock_generate.return_value = tmp_path / "map_preview.png"
# Test without auth -> 401
resp = client.post("/birthday/api/admin/map-preview/generate", json={"map_url": "https://maps.google.com/?q=34.1,-118.2"})
assert resp.status_code == 401
# Test with auth -> 200
resp = admin_client.post(
"/birthday/api/admin/map-preview/generate",
json={"map_url": "https://maps.google.com/?q=34.1,-118.2"},
)
assert resp.status_code == 200
data = resp.json()
assert "/birthday/api/map-preview.png" in data["map_preview_url"]
assert data["lat"] == 34.1432
assert data["lng"] == -118.2551
mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1,-118.2", fallback_query=ANY)
mock_generate.assert_called_once_with(34.1432, -118.2551)
@patch("app.routes.admin.resolve_google_maps_coordinates")
@patch("app.routes.admin.generate_map_preview_image")
def test_config_update_triggers_generator_only_when_map_url_changes(mock_generate, mock_resolve, admin_client, tmp_path):
mock_resolve.return_value = (34.1432, -118.2551, "https://resolved.url")
mock_generate.return_value = tmp_path / "map_preview.png"
# Get current config
current = admin_client.get("/birthday/api/admin/config").json()
orig_map_url = current["map_url"]
assert orig_map_url == "https://maps.google.com/?q=Fresco+Ristorante+Glendale+CA"
# 1. Update config WITHOUT changing map_url -> generator NOT called
update_payload = {**current}
update_payload["honoree_name"] = "Updated Honoree"
resp = admin_client.put("/birthday/api/admin/config", json=update_payload)
assert resp.status_code == 200
assert resp.json()["honoree_name"] == "Updated Honoree"
mock_resolve.assert_not_called()
mock_generate.assert_not_called()
# 2. Update config WITH new map_url -> generator CALLED
update_payload["map_url"] = "https://maps.google.com/?q=34.1432,-118.2551"
resp = admin_client.put("/birthday/api/admin/config", json=update_payload)
assert resp.status_code == 200
assert resp.json()["map_url"] == "https://maps.google.com/?q=34.1432,-118.2551"
assert resp.json()["map_preview_url"] == "/birthday/api/map-preview.png"
mock_resolve.assert_called_once_with("https://maps.google.com/?q=34.1432,-118.2551", fallback_query=ANY)
mock_generate.assert_called_once_with(34.1432, -118.2551)
def test_config_update_rejects_invalid_map_url(admin_client):
current = admin_client.get("/birthday/api/admin/config").json()
bad_payload = {**current, "map_url": "https://invalid-non-google-url.com/something"}
resp = admin_client.put("/birthday/api/admin/config", json=bad_payload)
assert resp.status_code == 422
def test_get_map_preview_serving(client, tmp_path, monkeypatch):
# Case 1: file exists
test_img = tmp_path / "map_preview.png"
test_img.write_bytes(b"\x89PNG\r\n\x1a\nfakeimagebytes")
monkeypatch.setattr(settings, "DATA_DIR", str(tmp_path))
resp = client.get("/birthday/api/map-preview.png")
assert resp.status_code == 200
assert resp.headers["content-type"] == "image/png"
assert resp.content == b"\x89PNG\r\n\x1a\nfakeimagebytes"
# Case 2: file does not exist -> redirects to fallback
test_img.unlink()
resp_fallback = client.get("/birthday/api/map-preview.png", follow_redirects=False)
assert resp_fallback.status_code == 307
assert "tile.openstreetmap.org" in resp_fallback.headers["location"]
+325
View File
@@ -0,0 +1,325 @@
"""Comprehensive unit and integration tests for Generic OIDC Client, PKCE & Cryptographic Verification."""
import base64
import json
import time
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
from fastapi import HTTPException
from app.auth import (
AuthPort,
Identity,
InvalidNonceError,
InvalidStateError,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
OIDCTransaction,
TokenValidationError,
generate_code_challenge,
generate_code_verifier,
generate_nonce,
generate_state,
)
FIXTURE_ISSUER = "http://localhost:8088/default"
FIXTURE_CLIENT_ID = "bdinvite-client"
FIXTURE_CLIENT_SECRET = "bdinvite-secret"
FIXTURE_REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
@pytest.fixture
def oidc_config() -> OIDCConfig:
return OIDCConfig(
issuer=FIXTURE_ISSUER,
client_id=FIXTURE_CLIENT_ID,
client_secret=FIXTURE_CLIENT_SECRET,
redirect_uri=FIXTURE_REDIRECT_URI,
)
@pytest.fixture
def oidc_client(oidc_config: OIDCConfig) -> OIDCClient:
return OIDCClient(oidc_config)
def obtain_auth_code_from_fixture(
authorization_url: str,
username: str = "testuser",
claims: dict | None = None,
) -> tuple[str, str]:
"""Helper to simulate user authentication against the Navikt mock-oauth2-server fixture."""
parsed_url = urlparse(authorization_url)
auth_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"
query_params = parse_qs(parsed_url.query)
flat_params = {k: v[0] for k, v in query_params.items()}
post_data: dict[str, str] = {"username": username}
if claims:
post_data["claims"] = json.dumps(claims)
with httpx.Client() as client:
resp = client.post(
auth_endpoint,
params=flat_params,
data=post_data,
follow_redirects=False,
)
assert resp.status_code == 302, f"Expected 302 redirect, got {resp.status_code}: {resp.text}"
location = resp.headers["location"]
redirect_parsed = urlparse(location)
callback_params = parse_qs(redirect_parsed.query)
assert "code" in callback_params, f"No code in callback redirect: {location}"
assert "state" in callback_params, f"No state in callback redirect: {location}"
return callback_params["code"][0], callback_params["state"][0]
def test_pkce_rfc7636_test_vector():
"""Verify that SHA-256 PKCE code_challenge derivation matches RFC 7636 Appendix B."""
rfc_verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
expected_challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
derived_challenge = generate_code_challenge(rfc_verifier)
assert derived_challenge == expected_challenge
def test_pkce_verifier_generation_entropy():
"""Verify generated code_verifier conforms to RFC 7636 unreserved character requirements and length."""
verifier = generate_code_verifier()
assert 43 <= len(verifier) <= 128
allowed_chars = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
assert all(c in allowed_chars for c in verifier)
def test_oidc_discovery_fetching(oidc_client: OIDCClient):
"""Verify dynamic discovery parsing from the live OIDC issuer."""
discovery = oidc_client.fetch_discovery()
assert discovery.issuer == FIXTURE_ISSUER
assert discovery.authorization_endpoint == f"{FIXTURE_ISSUER}/authorize"
assert discovery.token_endpoint == f"{FIXTURE_ISSUER}/token"
assert discovery.jwks_uri == f"{FIXTURE_ISSUER}/jwks"
assert discovery.end_session_endpoint == f"{FIXTURE_ISSUER}/endsession"
def test_authorization_request_contains_pkce_state_and_nonce(oidc_client: OIDCClient):
"""Verify authorization URL properly includes PKCE S256 challenge, state, and nonce."""
auth_url, transaction = oidc_client.create_authorization_url()
parsed = urlparse(auth_url)
assert parsed.scheme == "http"
assert parsed.path == "/default/authorize"
params = parse_qs(parsed.query)
assert params["client_id"] == [FIXTURE_CLIENT_ID]
assert params["response_type"] == ["code"]
assert params["redirect_uri"] == [FIXTURE_REDIRECT_URI]
assert params["scope"] == ["openid profile email"]
# Verify state, nonce, and PKCE parameters
assert params["state"] == [transaction.state]
assert params["nonce"] == [transaction.nonce]
assert params["code_challenge_method"] == ["S256"]
expected_challenge = generate_code_challenge(transaction.code_verifier)
assert params["code_challenge"] == [expected_challenge]
# Verify transaction is stored internally
assert transaction.state in oidc_client._transactions
def test_successful_code_exchange_and_id_token_validation(oidc_client: OIDCClient):
"""Verify complete end-to-end authorization code exchange, cryptographic verification, and Identity extraction."""
auth_url, transaction = oidc_client.create_authorization_url()
expected_claims = {
"email": "alex@roadtotech.me",
"name": "Alex Organizer",
"groups": ["organizers", "vip"],
}
code, returned_state = obtain_auth_code_from_fixture(
auth_url,
username="alex_sub_101",
claims=expected_claims,
)
assert returned_state == transaction.state
# Process callback
identity, tokens = oidc_client.process_callback(code=code, state=returned_state)
# Validate tokens payload
assert "access_token" in tokens
assert "id_token" in tokens
assert tokens["token_type"].lower() == "bearer"
# Validate Identity model creation
assert isinstance(identity, Identity)
assert identity.subject == "alex_sub_101"
assert identity.email == "alex@roadtotech.me"
assert identity.name == "Alex Organizer"
assert identity.groups == ["organizers", "vip"]
def test_rejection_of_invalid_state(oidc_client: OIDCClient):
"""Verify invalid, missing, and replayed states are rejected with HTTP 400 (CSRF protection)."""
# 1. Unrecognized state
with pytest.raises(InvalidStateError) as exc_info:
oidc_client.validate_state("non_existent_state_value")
assert exc_info.value.status_code == 400
# 2. None or empty state
with pytest.raises(InvalidStateError) as exc_info:
oidc_client.validate_state("")
assert exc_info.value.status_code == 400
# 3. Replay attack rejection: state must only be valid once
_, transaction = oidc_client.create_authorization_url()
first_validation = oidc_client.validate_state(transaction.state)
assert first_validation.state == transaction.state
with pytest.raises(InvalidStateError) as exc_info:
oidc_client.validate_state(transaction.state)
assert exc_info.value.status_code == 400
# 4. Expired state rejection
_, exp_transaction = oidc_client.create_authorization_url()
# Artificially expire the transaction
expired_tx = OIDCTransaction(
state=exp_transaction.state,
nonce=exp_transaction.nonce,
code_verifier=exp_transaction.code_verifier,
created_at=time.time() - 700.0,
expires_in=600.0,
)
oidc_client._transactions[expired_tx.state] = expired_tx
with pytest.raises(InvalidStateError) as exc_info:
oidc_client.validate_state(expired_tx.state)
assert exc_info.value.status_code == 400
def test_rejection_of_mismatched_nonce(oidc_client: OIDCClient):
"""Verify mismatched or missing nonce causes rejection with HTTP 401."""
auth_url, transaction = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="nonce_user")
validated_tx = oidc_client.validate_state(returned_state)
tokens = oidc_client.exchange_code(code=code, transaction_or_verifier=validated_tx)
id_token = tokens["id_token"]
# Validate with mismatched nonce
with pytest.raises(InvalidNonceError) as exc_info:
oidc_client.validate_id_token(id_token=id_token, nonce="completely_different_nonce")
assert exc_info.value.status_code == 401
# Validating with correct nonce succeeds
claims = oidc_client.validate_id_token(id_token=id_token, nonce=validated_tx.nonce)
assert claims["nonce"] == validated_tx.nonce
def test_rejection_of_tampered_id_token_signature(oidc_client: OIDCClient):
"""Verify tampered ID token signature or payload causes cryptographic rejection with HTTP 401."""
auth_url, transaction = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="tamper_user")
validated_tx = oidc_client.validate_state(returned_state)
tokens = oidc_client.exchange_code(code=code, transaction_or_verifier=validated_tx)
valid_id_token = tokens["id_token"]
# Valid token passes verification
oidc_client.validate_id_token(id_token=valid_id_token, nonce=validated_tx.nonce)
# 1. Tamper signature segment: change the last few characters of the signature
parts = valid_id_token.split(".")
assert len(parts) == 3
header_b64, payload_b64, sig_b64 = parts
tampered_sig = ("A" if sig_b64[-1] != "A" else "B") + sig_b64[1:]
tampered_token = f"{header_b64}.{payload_b64}.{tampered_sig}"
with pytest.raises(TokenValidationError) as exc_info:
oidc_client.validate_id_token(id_token=tampered_token, nonce=validated_tx.nonce)
assert exc_info.value.status_code == 401
# 2. Tamper payload segment: elevate permissions or change subject
payload_json = json.loads(base64.urlsafe_b64decode(payload_b64 + "==").decode("utf-8"))
payload_json["sub"] = "hacked_admin_user"
new_payload_b64 = (
base64.urlsafe_b64encode(json.dumps(payload_json).encode("utf-8"))
.decode("ascii")
.rstrip("=")
)
tampered_payload_token = f"{header_b64}.{new_payload_b64}.{sig_b64}"
with pytest.raises(TokenValidationError) as exc_info:
oidc_client.validate_id_token(id_token=tampered_payload_token, nonce=validated_tx.nonce)
assert exc_info.value.status_code == 401
def test_rejection_of_issuer_or_audience_mismatch(oidc_client: OIDCClient):
"""Verify tokens with unexpected issuer or audience are rejected with HTTP 401."""
auth_url, transaction = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="mismatch_user")
validated_tx = oidc_client.validate_state(returned_state)
tokens = oidc_client.exchange_code(code=code, transaction_or_verifier=validated_tx)
id_token = tokens["id_token"]
# Wrong client_id / audience expected
client_wrong_aud = OIDCClient(
OIDCConfig(
issuer=FIXTURE_ISSUER,
client_id="attacker-client",
client_secret=FIXTURE_CLIENT_SECRET,
redirect_uri=FIXTURE_REDIRECT_URI,
)
)
with pytest.raises(TokenValidationError) as exc_info:
client_wrong_aud.validate_id_token(id_token=id_token, nonce=validated_tx.nonce)
assert exc_info.value.status_code == 401
# Wrong issuer expected
client_wrong_iss = OIDCClient(
OIDCConfig(
issuer="http://rogue-idp.example.com",
client_id=FIXTURE_CLIENT_ID,
client_secret=FIXTURE_CLIENT_SECRET,
redirect_uri=FIXTURE_REDIRECT_URI,
)
)
# Pre-populate JWKS from fixture so key is available, but issuer check will fail
client_wrong_iss._jwk_set = oidc_client.get_jwks()
with pytest.raises(TokenValidationError) as exc_info:
client_wrong_iss.validate_id_token(id_token=id_token, nonce=validated_tx.nonce)
assert exc_info.value.status_code == 401
@pytest.mark.asyncio
async def test_async_oidc_flow(oidc_client: OIDCClient):
"""Verify asynchronous discovery, code exchange, and token validation."""
discovery = await oidc_client.afetch_discovery()
assert discovery.issuer == FIXTURE_ISSUER
auth_url, transaction = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="async_user")
identity, tokens = await oidc_client.aprocess_callback(code=code, state=returned_state)
assert identity.subject == "async_user"
assert "access_token" in tokens
assert "id_token" in tokens
def test_auth_adapter_protocol_conformance(oidc_client: OIDCClient):
"""Verify OIDCAuthAdapter adheres to the hexagonal AuthPort Protocol."""
adapter = OIDCAuthAdapter(client=oidc_client)
assert isinstance(adapter, AuthPort)
from fastapi import Request
mock_req = Request({"type": "http", "method": "GET", "path": "/test", "headers": []})
login_resp = adapter.login(mock_req)
assert login_resp.status_code == 302
assert "/default/authorize?" in login_resp.headers["location"]
+103
View File
@@ -0,0 +1,103 @@
import pytest
from app.services.rsvp import normalize_phone
def test_normalize_phone_valid_cases():
cases = [
("+57 300 123 4567", "3001234567"),
("300-123-4567", "3001234567"),
("3001234567", "3001234567"),
("(300) 123 4567", "3001234567"),
("57300123 4567", "3001234567"),
("+573159998877", "3159998877"),
("320 000 0000", "3200000000"),
]
for raw, expected in cases:
assert normalize_phone(raw) == expected
def test_normalize_phone_invalid_cases():
invalid_cases = [
"123456", # Too short
"1234567890", # Doesn't start with 3
"+1 555 123 4567", # US format
"30012345678", # Too long
"", # Empty
"abcdefghij", # Non-digits
]
for raw in invalid_cases:
with pytest.raises(ValueError, match="Formato de teléfono inválido"):
normalize_phone(raw)
def test_submit_rsvp_success(client):
payload = {
"name": "Andrés García",
"phone": "+57 300 123 4567",
"email": "andres@example.com",
}
response = client.post("/birthday/api/rsvp", json=payload)
assert response.status_code == 201
data = response.json()
assert data["result"] == "SUCCESS"
assert data["name"] == "Andrés García"
def test_submit_rsvp_duplicate(client):
payload = {
"name": "Andrés García",
"phone": "300 123 4567",
"email": "andres@example.com",
}
# First submission
res1 = client.post("/birthday/api/rsvp", json=payload)
assert res1.status_code == 201
# Second submission with same phone in different format
payload2 = {
"name": "Andrés Felipe García",
"phone": "+57 300-123-4567",
"email": "other@example.com",
}
res2 = client.post("/birthday/api/rsvp", json=payload2)
assert res2.status_code == 409
data = res2.json()
assert data["result"] == "DUPLICATE"
def test_submit_rsvp_validation_error_phone(client):
payload = {
"name": "Camila",
"phone": "999 123 4567", # doesn't start with 3
}
response = client.post("/birthday/api/rsvp", json=payload)
assert response.status_code == 422
data = response.json()
assert data["result"] == "VALIDATION_ERROR"
assert "phone" in data["errors"]
def test_submit_rsvp_validation_error_name(client):
payload = {
"name": " ",
"phone": "300 123 4567",
}
response = client.post("/birthday/api/rsvp", json=payload)
assert response.status_code == 422
data = response.json()
assert data["result"] == "VALIDATION_ERROR"
assert "name" in data["errors"]
def test_submit_rsvp_validation_error_email(client):
payload = {
"name": "Camila",
"phone": "300 123 4567",
"email": "invalid-email-string",
}
response = client.post("/birthday/api/rsvp", json=payload)
assert response.status_code == 422
data = response.json()
assert data["result"] == "VALIDATION_ERROR"
assert "email" in data["errors"]
+511
View File
@@ -0,0 +1,511 @@
"""Security Hardening and Deployment Independence verification tests (Checkpoint 8).
Validates adversarial edge cases:
1. Forged / invalid CSRF state returns HTTP 400 Bad Request.
2. Forged / tampered ID token signature returns HTTP 401 Unauthorized.
3. Mismatched or replayed nonce returns HTTP 401 Unauthorized.
4. Missing or invalid PKCE code_verifier returns HTTP 401 Unauthorized.
5. Expired ID token / expired session cookie returns HTTP 401 Unauthorized.
6. Authenticated non-admin user accessing admin APIs returns HTTP 403 Forbidden.
7. Legacy Remote-User header without a valid authenticated session returns HTTP 401 Unauthorized.
8. Deployment independence: Direct Standalone Mode vs Homelab Production Mode.
"""
import base64
import json
import time
from unittest.mock import MagicMock
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
from fastapi.testclient import TestClient
from app.auth import (
Identity,
InvalidCodeVerifierError,
InvalidNonceError,
InvalidStateError,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
OIDCTransaction,
SessionRecord,
TokenValidationError,
get_auth_adapter,
)
from app.config import Settings
FIXTURE_ISSUER = "http://localhost:8088/default"
FIXTURE_CLIENT_ID = "bdinvite-client"
FIXTURE_CLIENT_SECRET = "bdinvite-secret"
FIXTURE_REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
def _obtain_auth_code(
authorization_url: str,
username: str = "security_test_user",
claims: dict | None = None,
) -> tuple[str, str]:
"""Helper to simulate user authentication against the Navikt mock-oauth2-server fixture."""
parsed_url = urlparse(authorization_url)
auth_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"
query_params = parse_qs(parsed_url.query)
flat_params = {k: v[0] for k, v in query_params.items()}
post_data: dict[str, str] = {"username": username}
if claims:
post_data["claims"] = json.dumps(claims)
with httpx.Client() as http_client:
resp = http_client.post(
auth_endpoint,
params=flat_params,
data=post_data,
follow_redirects=False,
)
assert resp.status_code == 302, f"Expected 302 redirect, got {resp.status_code}: {resp.text}"
location = resp.headers["location"]
redirect_parsed = urlparse(location)
callback_params = parse_qs(redirect_parsed.query)
assert "code" in callback_params
assert "state" in callback_params
return callback_params["code"][0], callback_params["state"][0]
# ==============================================================================
# 1. Adversarial State Rejection (CSRF Mitigation) -> HTTP 400 Bad Request
# ==============================================================================
def test_forged_csrf_state_returns_400(client: TestClient):
"""Forged / unrecognized CSRF state returns HTTP 400 Bad Request."""
adapter = get_auth_adapter()
with pytest.raises(InvalidStateError):
adapter.client.validate_state("forged_state_xyz")
res = client.get(
"/birthday/api/auth/callback",
params={"code": "dummy_auth_code", "state": "forged_malicious_state_xyz"},
)
assert res.status_code == 400
assert "detail" in res.json()
def test_replayed_csrf_state_returns_400(client: TestClient):
"""Replaying an already-consumed CSRF state parameter returns HTTP 400 Bad Request."""
adapter = get_auth_adapter()
auth_url, _ = adapter.client.create_authorization_url()
code, returned_state = _obtain_auth_code(auth_url, username="replay_state_user")
# First callback succeeds and consumes state
res1 = client.get(
"/birthday/api/auth/callback",
params={"code": code, "state": returned_state},
follow_redirects=False,
)
assert res1.status_code == 302
# Second callback replaying the exact same state must return HTTP 400
res2 = client.get(
"/birthday/api/auth/callback",
params={"code": code, "state": returned_state},
)
assert res2.status_code == 400
assert "already consumed" in res2.json()["detail"].lower() or "invalid" in res2.json()["detail"].lower()
def test_expired_csrf_state_returns_400(client: TestClient):
"""Authentication transaction that exceeded its TTL returns HTTP 400 Bad Request."""
adapter = get_auth_adapter()
_, tx = adapter.client.create_authorization_url()
# Artificially expire the transaction
expired_tx = OIDCTransaction(
state=tx.state,
nonce=tx.nonce,
code_verifier=tx.code_verifier,
created_at=time.time() - 900.0,
expires_in=600.0,
)
adapter.client._transactions[tx.state] = expired_tx
res = client.get(
"/birthday/api/auth/callback",
params={"code": "any_code", "state": tx.state},
)
assert res.status_code == 400
assert "expired" in res.json()["detail"].lower()
# ==============================================================================
# 2. Forged / Tampered ID Token Signature -> HTTP 401 Unauthorized
# ==============================================================================
def test_tampered_id_token_signature_returns_401():
"""Tampered ID token signature raises TokenValidationError (HTTP 401)."""
adapter = get_auth_adapter()
auth_url, _ = adapter.client.create_authorization_url()
code, returned_state = _obtain_auth_code(auth_url, username="tamper_sig_user")
validated_tx = adapter.client.validate_state(returned_state)
tokens = adapter.client.exchange_code(code=code, transaction_or_verifier=validated_tx)
valid_id_token = tokens["id_token"]
parts = valid_id_token.split(".")
assert len(parts) == 3
header_b64, payload_b64, sig_b64 = parts
# Invert characters in the signature segment
tampered_sig = ("Z" if sig_b64[-1] != "Z" else "A") + sig_b64[1:]
tampered_token = f"{header_b64}.{payload_b64}.{tampered_sig}"
with pytest.raises(TokenValidationError) as exc_info:
adapter.client.validate_id_token(id_token=tampered_token, nonce=validated_tx.nonce)
assert exc_info.value.status_code == 401
def test_tampered_id_token_bearer_header_returns_401(client: TestClient):
"""Bearer request containing a forged / tampered ID token signature returns HTTP 401."""
adapter = get_auth_adapter()
auth_url, _ = adapter.client.create_authorization_url()
code, returned_state = _obtain_auth_code(auth_url, username="bearer_tamper_user")
validated_tx = adapter.client.validate_state(returned_state)
tokens = adapter.client.exchange_code(code=code, transaction_or_verifier=validated_tx)
valid_id_token = tokens["id_token"]
parts = valid_id_token.split(".")
tampered_token = f"{parts[0]}.{parts[1]}.tampered_signature_bytes_12345"
res = client.get(
"/birthday/api/admin/rsvps",
headers={"Authorization": f"Bearer {tampered_token}"},
)
assert res.status_code == 401
def test_alg_none_id_token_rejected_with_401():
"""ID token with 'alg': 'none' is rejected with HTTP 401."""
adapter = get_auth_adapter()
header = base64.urlsafe_b64encode(json.dumps({"alg": "none"}).encode()).decode().rstrip("=")
payload = base64.urlsafe_b64encode(
json.dumps({
"sub": "admin",
"iss": adapter.client.config.issuer,
"aud": adapter.client.config.client_id,
"exp": time.time() + 3600,
}).encode()
).decode().rstrip("=")
forged_token = f"{header}.{payload}."
with pytest.raises(TokenValidationError) as exc_info:
adapter.client.validate_id_token(forged_token)
assert exc_info.value.status_code == 401
# ==============================================================================
# 3. Mismatched or Replayed Nonce -> HTTP 401 Unauthorized
# ==============================================================================
def test_mismatched_nonce_returns_401():
"""ID token with mismatched nonce claim raises InvalidNonceError (HTTP 401)."""
adapter = get_auth_adapter()
auth_url, _ = adapter.client.create_authorization_url()
code, returned_state = _obtain_auth_code(auth_url, username="nonce_mismatch_user")
validated_tx = adapter.client.validate_state(returned_state)
tokens = adapter.client.exchange_code(code=code, transaction_or_verifier=validated_tx)
id_token = tokens["id_token"]
with pytest.raises(InvalidNonceError) as exc_info:
adapter.client.validate_id_token(id_token=id_token, nonce="completely_different_nonce_val")
assert exc_info.value.status_code == 401
assert "nonce" in exc_info.value.detail.lower()
def test_missing_nonce_when_expected_returns_401(monkeypatch):
"""ID token missing expected nonce claim raises InvalidNonceError (HTTP 401)."""
adapter = get_auth_adapter()
# Mock jwt.decode to return valid claims except missing the required nonce
mock_claims = {
"sub": "user123",
"email": "user@example.com",
"iss": adapter.client.config.issuer,
"aud": adapter.client.config.client_id,
"exp": time.time() + 3600,
}
monkeypatch.setattr("jwt.get_unverified_header", lambda token: {"alg": "RS256", "kid": "mock_kid"})
monkeypatch.setattr("jwt.decode", lambda *args, **kwargs: mock_claims)
mock_jwk = MagicMock()
mock_jwk.key = "mock_key"
mock_keys = MagicMock()
mock_keys.__getitem__.return_value = mock_jwk
monkeypatch.setattr(adapter.client, "get_jwks", lambda *args, **kwargs: mock_keys)
with pytest.raises(InvalidNonceError) as exc_info:
adapter.client.validate_id_token("dummy.jwt.token", nonce="expected_nonce_123")
assert exc_info.value.status_code == 401
assert "nonce" in exc_info.value.detail.lower()
# ==============================================================================
# 4. Missing or Invalid PKCE code_verifier -> HTTP 401 Unauthorized
# ==============================================================================
def test_missing_pkce_code_verifier_returns_401():
"""Missing or empty PKCE code_verifier raises InvalidCodeVerifierError (HTTP 401)."""
adapter = get_auth_adapter()
with pytest.raises(InvalidCodeVerifierError) as exc_info:
adapter.client.exchange_code(code="dummy_code", transaction_or_verifier="")
assert exc_info.value.status_code == 401
assert "code_verifier" in exc_info.value.detail.lower()
def test_invalid_pkce_code_verifier_against_idp_returns_401():
"""Invalid PKCE code_verifier rejected by IdP raises InvalidCodeVerifierError (HTTP 401)."""
adapter = get_auth_adapter()
auth_url, _ = adapter.client.create_authorization_url()
code, _ = _obtain_auth_code(auth_url, username="pkce_invalid_user")
# Mismatched 50-char string that does not hash to the code_challenge
wrong_verifier = "x" * 50
with pytest.raises(InvalidCodeVerifierError) as exc_info:
adapter.client.exchange_code(code=code, transaction_or_verifier=wrong_verifier)
assert exc_info.value.status_code == 401
@pytest.mark.asyncio
async def test_async_invalid_pkce_code_verifier_returns_401():
"""Asynchronous exchange with invalid PKCE code_verifier raises InvalidCodeVerifierError (HTTP 401)."""
adapter = get_auth_adapter()
with pytest.raises(InvalidCodeVerifierError) as exc_info:
await adapter.client.aexchange_code(code="dummy_code", transaction_or_verifier="")
assert exc_info.value.status_code == 401
# ==============================================================================
# 5. Expired ID Token / Expired Session Cookie -> HTTP 401 Unauthorized
# ==============================================================================
def test_expired_id_token_validation_returns_401(monkeypatch):
"""Expired ID token raises TokenValidationError (HTTP 401)."""
adapter = get_auth_adapter()
import jwt as pyjwt
monkeypatch.setattr("jwt.get_unverified_header", lambda token: {"alg": "RS256", "kid": "mock_kid"})
mock_jwk = MagicMock()
mock_jwk.key = "mock_key"
mock_keys = MagicMock()
mock_keys.__getitem__.return_value = mock_jwk
monkeypatch.setattr(adapter.client, "get_jwks", lambda *args, **kwargs: mock_keys)
def mock_decode(*args, **kwargs):
raise pyjwt.ExpiredSignatureError("Signature has expired")
monkeypatch.setattr("jwt.decode", mock_decode)
with pytest.raises(TokenValidationError) as exc_info:
adapter.client.validate_id_token("expired.jwt.token")
assert exc_info.value.status_code == 401
assert "expired" in exc_info.value.detail.lower()
def test_expired_session_cookie_returns_401(client: TestClient):
"""Expired session cookie is rejected with HTTP 401 Unauthorized on admin API."""
adapter = get_auth_adapter()
admin_id = Identity(
subject="admin-exp",
email="admin@example.com",
groups=["bdinvite_admins"],
)
# Establish session expired 100 seconds ago
session_id = "expired_sess_test_123"
past_time = time.time() - 100.0
record = SessionRecord(
session_id=session_id,
identity=admin_id,
created_at=past_time - 3600,
expires_at=past_time,
last_accessed=past_time,
)
adapter.sessions[session_id] = record
client.cookies.set(adapter.session_cookie_name, session_id)
res = client.get("/birthday/api/admin/rsvps")
assert res.status_code == 401
# Session record must be revoked
assert session_id not in adapter.sessions
def test_expired_session_cookie_on_auth_me_returns_unauthenticated(client: TestClient):
"""Expired session cookie returns unauthenticated status on /birthday/api/auth/me."""
adapter = get_auth_adapter()
guest_id = Identity(
subject="guest-exp",
email="guest@example.com",
groups=["guests"],
)
session_id = "expired_me_test_123"
past_time = time.time() - 50.0
adapter.sessions[session_id] = SessionRecord(
session_id=session_id,
identity=guest_id,
created_at=past_time - 3600,
expires_at=past_time,
)
client.cookies.set(adapter.session_cookie_name, session_id)
res = client.get("/birthday/api/auth/me")
assert res.status_code == 200
data = res.json()
assert data["authenticated"] is False
assert data["identity"] is None
# ==============================================================================
# 6. Authenticated Non-Admin User Accessing Admin APIs -> HTTP 403 Forbidden
# ==============================================================================
def test_authenticated_non_admin_returns_403(client: TestClient, guest_session_cookie):
"""Authenticated non-admin user (guest) accessing admin endpoints returns HTTP 403 Forbidden."""
for k, v in guest_session_cookie.items():
client.cookies.set(k, v)
# 1. GET RSVPs
res1 = client.get("/birthday/api/admin/rsvps")
assert res1.status_code == 403
assert "Forbidden" in res1.json()["detail"] or "bdinvite_admins" in res1.json()["detail"]
# 2. GET Config
res2 = client.get("/birthday/api/admin/config")
assert res2.status_code == 403
# 3. PUT Config
res3 = client.put("/birthday/api/admin/config", json={"title": "Hacked Title"})
assert res3.status_code == 403
# 4. Export CSV
res4 = client.get("/birthday/api/admin/export")
assert res4.status_code == 403
# 5. Map preview trigger
res5 = client.post("/birthday/api/admin/map-preview/generate", json={"map_url": "https://maps.google.com"})
assert res5.status_code == 403
# 6. Delete RSVP
res6 = client.delete("/birthday/api/admin/rsvps/1")
assert res6.status_code == 403
# ==============================================================================
# 7. Legacy Remote-User Header Without Valid Session -> HTTP 401 Unauthorized
# ==============================================================================
def test_legacy_remote_user_header_without_session_returns_401(client: TestClient):
"""Negative gate: legacy Remote-User header without valid session returns HTTP 401."""
# Direct Remote-User spoofing attempt
res = client.get(
"/birthday/api/admin/rsvps",
headers={"Remote-User": "admin@example.com"},
)
assert res.status_code == 401
# Alternative headers spoofing attempts
res_alt1 = client.get(
"/birthday/api/admin/config",
headers={"X-Remote-User": "admin", "X-Forwarded-User": "admin"},
)
assert res_alt1.status_code == 401
def test_legacy_remote_user_with_non_admin_session_returns_403(
client: TestClient, guest_session_cookie
):
"""Remote-User header sent alongside non-admin session is ignored; session governs -> 403."""
for k, v in guest_session_cookie.items():
client.cookies.set(k, v)
res = client.get(
"/birthday/api/admin/rsvps",
headers={"Remote-User": "admin@example.com"},
)
assert res.status_code == 403
# ==============================================================================
# 8. Deployment Independence: Standalone vs Homelab Production Mode
# ==============================================================================
def test_standalone_mode_configuration():
"""Verify Direct Standalone Mode environment settings and behavior."""
standalone_settings = Settings(
SERVICE_DOMAIN="localhost",
OIDC_ISSUER="http://localhost:8088/default",
OIDC_REDIRECT_URI="http://localhost:8000/birthday/api/auth/callback",
SESSION_COOKIE_SECURE=False,
SESSION_COOKIE_NAME="bdinvite_session",
)
assert standalone_settings.SESSION_COOKIE_SECURE is False
assert standalone_settings.OIDC_ISSUER == "http://localhost:8088/default"
# Adapter with secure=False should not set Secure flag on cookie
client = OIDCClient(
OIDCConfig(
issuer=standalone_settings.OIDC_ISSUER,
client_id=standalone_settings.OIDC_CLIENT_ID,
redirect_uri=standalone_settings.OIDC_REDIRECT_URI,
)
)
adapter = OIDCAuthAdapter(
client=client,
cookie_secure=standalone_settings.SESSION_COOKIE_SECURE,
session_cookie_name=standalone_settings.SESSION_COOKIE_NAME,
)
mock_resp = MagicMock()
adapter.set_session_cookie(mock_resp, "test_sess_123")
mock_resp.set_cookie.assert_called_once()
_, kwargs = mock_resp.set_cookie.call_args
assert kwargs["secure"] is False
assert kwargs["httponly"] is True
def test_homelab_production_mode_configuration():
"""Verify Homelab Production Mode environment settings and behavior."""
prod_settings = Settings(
SERVICE_DOMAIN="demos.roadtotech.me",
OIDC_ISSUER="https://auth.roadtotech.me",
OIDC_CLIENT_ID="bdinvite-prod",
OIDC_CLIENT_SECRET="secure-prod-secret",
OIDC_REDIRECT_URI="https://demos.roadtotech.me/birthday/api/auth/callback",
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_NAME="bdinvite_session",
SESSION_COOKIE_SAMESITE="lax",
)
assert prod_settings.SESSION_COOKIE_SECURE is True
assert prod_settings.SERVICE_DOMAIN == "demos.roadtotech.me"
assert prod_settings.OIDC_ISSUER == "https://auth.roadtotech.me"
# Adapter with secure=True must set Secure=True and HttpOnly=True
client = OIDCClient(
OIDCConfig(
issuer=prod_settings.OIDC_ISSUER,
client_id=prod_settings.OIDC_CLIENT_ID,
client_secret=prod_settings.OIDC_CLIENT_SECRET,
redirect_uri=prod_settings.OIDC_REDIRECT_URI,
)
)
adapter = OIDCAuthAdapter(
client=client,
cookie_secure=prod_settings.SESSION_COOKIE_SECURE,
session_cookie_name=prod_settings.SESSION_COOKIE_NAME,
)
mock_resp = MagicMock()
adapter.set_session_cookie(mock_resp, "test_prod_sess_456")
mock_resp.set_cookie.assert_called_once()
_, kwargs = mock_resp.set_cookie.call_args
assert kwargs["secure"] is True
assert kwargs["httponly"] is True
assert kwargs["samesite"] == "lax"
+401
View File
@@ -0,0 +1,401 @@
"""Tests for Browser Session Management and Session Fixation Protection (Checkpoint 4)."""
import time
from collections.abc import Generator
from urllib.parse import parse_qs, urlparse
import httpx
import pytest
from fastapi import Response
from fastapi.testclient import TestClient
from starlette.requests import Request
from app.auth import (
Identity,
OIDCAuthAdapter,
OIDCClient,
OIDCConfig,
SessionRecord,
)
from app.routes.auth import get_auth_adapter, set_auth_adapter
FIXTURE_ISSUER = "http://localhost:8088/default"
FIXTURE_CLIENT_ID = "bdinvite-client"
FIXTURE_CLIENT_SECRET = "bdinvite-secret"
FIXTURE_REDIRECT_URI = "http://localhost:8000/birthday/api/auth/callback"
@pytest.fixture
def oidc_config() -> OIDCConfig:
return OIDCConfig(
issuer=FIXTURE_ISSUER,
client_id=FIXTURE_CLIENT_ID,
client_secret=FIXTURE_CLIENT_SECRET,
redirect_uri=FIXTURE_REDIRECT_URI,
)
@pytest.fixture
def oidc_client(oidc_config: OIDCConfig) -> OIDCClient:
return OIDCClient(oidc_config)
@pytest.fixture
def auth_adapter(oidc_client: OIDCClient) -> Generator[OIDCAuthAdapter, None, None]:
adapter = OIDCAuthAdapter(
client=oidc_client,
session_cookie_name="bdinvite_session",
cookie_secure=False,
cookie_samesite="lax",
session_lifetime=3600.0,
)
set_auth_adapter(adapter)
yield adapter
set_auth_adapter(None)
def create_request(
headers: dict[str, str] | None = None,
cookies: dict[str, str] | None = None,
) -> Request:
header_list: list[tuple[bytes, bytes]] = []
if headers:
for k, v in headers.items():
header_list.append((k.lower().encode("latin-1"), v.encode("latin-1")))
if cookies:
cookie_header = "; ".join(f"{k}={v}" for k, v in cookies.items())
header_list.append((b"cookie", cookie_header.encode("latin-1")))
scope = {
"type": "http",
"method": "GET",
"path": "/birthday/api/auth/session",
"headers": header_list,
"query_string": b"",
}
return Request(scope)
def obtain_auth_code_from_fixture(authorization_url: str, username: str) -> tuple[str, str]:
parsed_url = urlparse(authorization_url)
auth_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"
query_params = parse_qs(parsed_url.query)
flat_params = {k: v[0] for k, v in query_params.items()}
with httpx.Client() as client:
resp = client.post(
auth_endpoint,
params=flat_params,
data={"username": username},
follow_redirects=False,
)
assert resp.status_code == 302, f"Failed auth code post: {resp.text}"
location = resp.headers["location"]
redirect_parsed = urlparse(location)
callback_params = parse_qs(redirect_parsed.query)
return callback_params["code"][0], callback_params["state"][0]
# ============================================================================
# 1. Browser Session Contract & Security Invariant Tests
# ============================================================================
def test_session_cookie_issued_with_httponly_and_samesite(auth_adapter: OIDCAuthAdapter):
"""Security Invariant: The session cookie MUST have HttpOnly=True and SameSite.
Client-side JavaScript must never have access to raw tokens or session identifiers.
"""
identity = Identity(
subject="admin-001",
email="admin@example.com",
name="Admin User",
groups=["bdinvite_admins"],
)
response = Response()
session_id = auth_adapter.establish_session(identity)
auth_adapter.set_session_cookie(response, session_id)
set_cookie = response.headers.get("set-cookie", "")
assert auth_adapter.session_cookie_name in set_cookie
assert session_id in set_cookie
assert "HttpOnly" in set_cookie, "Session cookie MUST enforce HttpOnly=True"
assert "SameSite=lax" in set_cookie or "samesite=lax" in set_cookie.lower()
def test_configurable_secure_flag():
"""Verify configurable Secure cookie flag: False in test/dev, True in production."""
# 1. Development/test environment: Secure=False allows HTTP testing
dev_adapter = OIDCAuthAdapter(
client=OIDCClient(OIDCConfig(issuer=FIXTURE_ISSUER, client_id=FIXTURE_CLIENT_ID)),
cookie_secure=False,
)
resp_dev = Response()
s_dev = dev_adapter.establish_session(Identity(subject="dev", email="dev@local"))
dev_adapter.set_session_cookie(resp_dev, s_dev)
assert "secure" not in resp_dev.headers.get("set-cookie", "").lower()
# 2. Production environment: Secure=True enforces HTTPS transmission
prod_adapter = OIDCAuthAdapter(
client=OIDCClient(OIDCConfig(issuer=FIXTURE_ISSUER, client_id=FIXTURE_CLIENT_ID)),
cookie_secure=True,
)
resp_prod = Response()
s_prod = prod_adapter.establish_session(Identity(subject="prod", email="prod@local"))
prod_adapter.set_session_cookie(resp_prod, s_prod)
set_cookie_prod = resp_prod.headers.get("set-cookie", "").lower()
assert "secure" in set_cookie_prod, "Production session cookie MUST enforce Secure=True"
# ============================================================================
# 2. Session Fixation Barrier Tests
# ============================================================================
def test_session_fixation_barrier_rotates_session_id(auth_adapter: OIDCAuthAdapter):
"""Session Fixation Barrier:
Successful authentication MUST generate a fresh, new session identifier.
An existing pre-authentication session identifier must NEVER be promoted into an
authenticated session (pre_auth_session_id != post_auth_session_id).
"""
# 1. Pre-authentication state: client possesses an anonymous or pre-auth session ID
pre_auth_session_id = auth_adapter.create_anonymous_session()
assert pre_auth_session_id is not None
# Pre-auth request resolves to anonymous
req_pre = create_request(cookies={auth_adapter.session_cookie_name: pre_auth_session_id})
assert auth_adapter.current_identity(req_pre) is None
# 2. User successfully authenticates
identity = Identity(
subject="admin-001",
email="admin@example.com",
name="Admin User",
groups=["bdinvite_admins"],
)
post_auth_session_id = auth_adapter.establish_session(
identity=identity,
pre_auth_session_id=pre_auth_session_id,
)
# 3. Assert Session Fixation Barrier guarantees
assert post_auth_session_id != pre_auth_session_id, (
f"Session Fixation violation: pre-auth ID was promoted! "
f"{pre_auth_session_id} == {post_auth_session_id}"
)
# 4. Old pre-auth session ID is strictly invalid and resolves to None
assert auth_adapter.current_identity(req_pre) is None
# 5. New post-auth session ID resolves to the authenticated user
req_post = create_request(cookies={auth_adapter.session_cookie_name: post_auth_session_id})
resolved = auth_adapter.current_identity(req_post)
assert resolved == identity
def test_session_fixation_barrier_via_callback(
auth_adapter: OIDCAuthAdapter,
oidc_client: OIDCClient,
):
"""Verify session fixation barrier through complete callback processing."""
auth_url, _ = oidc_client.create_authorization_url()
code, returned_state = obtain_auth_code_from_fixture(auth_url, username="guest@example.com")
# Attacker sets fixed pre-auth session cookie on victim
pre_auth_session_id = "pre_auth_attacker_fixed_session_key"
req = create_request(cookies={auth_adapter.session_cookie_name: pre_auth_session_id})
resp = Response()
identity, post_auth_session_id = auth_adapter.handle_callback(
code=code,
state=returned_state,
response=resp,
request=req,
extra_params={"username": "guest@example.com"},
)
# Assert fixation barrier
assert post_auth_session_id != pre_auth_session_id
assert identity.subject == "guest-001"
# Attacker's pre-auth session resolves to nothing
assert auth_adapter.current_identity(req) is None
# Authenticated user's new cookie resolves to identity
req_valid = create_request(cookies={auth_adapter.session_cookie_name: post_auth_session_id})
assert auth_adapter.current_identity(req_valid) == identity
# ============================================================================
# 3. Session Lifecycle & Invalidation Tests
# ============================================================================
def test_valid_session_cookie_resolves_to_identity(auth_adapter: OIDCAuthAdapter):
"""Returning requests presenting a valid session cookie must resolve to Identity."""
identity = Identity(
subject="guest-001",
email="guest@example.com",
name="Guest User",
groups=["guests"],
)
session_id = auth_adapter.establish_session(identity)
req = create_request(cookies={auth_adapter.session_cookie_name: session_id})
resolved = auth_adapter.current_identity(req)
assert resolved == identity
def test_anonymous_request_resolves_to_none(auth_adapter: OIDCAuthAdapter):
"""Anonymous requests (no cookie or unknown session) resolve to None."""
# 1. No cookies
req_empty = create_request(cookies={})
assert auth_adapter.current_identity(req_empty) is None
# 2. Unknown session ID
req_unknown = create_request(cookies={auth_adapter.session_cookie_name: "unknown_random_session_token"})
assert auth_adapter.current_identity(req_unknown) is None
def test_expired_session_is_rejected_and_evicted(auth_adapter: OIDCAuthAdapter):
"""Expired sessions are rejected, treated as unauthenticated, and evicted."""
identity = Identity(subject="usr_exp", email="exp@local")
# Establish session with very short TTL
session_id = auth_adapter.establish_session(identity, ttl=0.05)
req = create_request(cookies={auth_adapter.session_cookie_name: session_id})
# Initially valid
assert auth_adapter.current_identity(req) == identity
# Wait for expiration
time.sleep(0.06)
# Now expired: resolves to None and is evicted from memory
assert auth_adapter.current_identity(req) is None
assert session_id not in auth_adapter.sessions
def test_tampered_and_malformed_cookies_safely_rejected(auth_adapter: OIDCAuthAdapter):
"""Requests presenting tampered, malformed, or forged cookies must be safely rejected (not crash)."""
malicious_inputs = [
"tampered!@#$%^&*()",
"valid_part\x00malicious_bytes",
"a" * 1000,
"session\r\nSet-Cookie: evil=1",
"' OR '1'='1",
" \t\n ",
"../../etc/passwd",
"{'session': 'eval'}",
]
for bad_input in malicious_inputs:
req = create_request(cookies={auth_adapter.session_cookie_name: bad_input})
try:
resolved = auth_adapter.current_identity(req)
assert resolved is None, f"Expected None for malicious cookie: {bad_input!r}"
except Exception as exc:
pytest.fail(f"Application crashed on tampered cookie {bad_input!r}: {exc}")
def test_logout_invalidates_session_and_clears_cookie(auth_adapter: OIDCAuthAdapter):
"""Logout invalidates the session on the server and clears the browser cookie (Max-Age=0)."""
identity = Identity(subject="admin-001", email="admin@example.com")
session_id = auth_adapter.establish_session(identity)
req = create_request(cookies={auth_adapter.session_cookie_name: session_id})
assert auth_adapter.current_identity(req) == identity
# Perform logout
logout_resp = auth_adapter.logout(req)
# 1. Server-side session revoked
assert session_id not in auth_adapter.sessions
assert auth_adapter.current_identity(req) is None
# 2. Browser cookie cleared with Max-Age=0
set_cookie = logout_resp.headers.get("set-cookie", "")
assert auth_adapter.session_cookie_name in set_cookie
assert "Max-Age=0" in set_cookie or "max-age=0" in set_cookie
assert "HttpOnly" in set_cookie
# ============================================================================
# 4. FastAPI HTTP Integration Tests (Endpoints & TestClient)
# ============================================================================
def test_http_auth_session_and_logout_endpoints(
client: TestClient,
auth_adapter: OIDCAuthAdapter,
):
"""Integration test: /birthday/api/auth/session, /logout endpoints via HTTP TestClient."""
# 1. Anonymous session check
res_anon = client.get("/birthday/api/auth/session")
assert res_anon.status_code == 200
assert res_anon.json() == {"authenticated": False, "identity": None}
# 2. Establish valid session for fixture admin user
identity = Identity(
subject="admin-001",
email="admin@example.com",
name="Admin User",
groups=["bdinvite_admins"],
)
session_id = auth_adapter.establish_session(identity)
# 3. Present session cookie to /session
client.cookies.set(auth_adapter.session_cookie_name, session_id)
res_auth = client.get("/birthday/api/auth/session")
assert res_auth.status_code == 200
auth_data = res_auth.json()
assert auth_data["authenticated"] is True
assert auth_data["identity"]["subject"] == "admin-001"
assert auth_data["identity"]["email"] == "admin@example.com"
assert auth_data["identity"]["groups"] == ["bdinvite_admins"]
# 4. Admin endpoint accessed via session cookie
res_admin = client.get("/birthday/api/admin/rsvps")
assert res_admin.status_code == 200
# 5. Logout via API POST
res_logout = client.post("/birthday/api/auth/logout")
assert res_logout.status_code == 200
assert res_logout.json()["result"] == "SUCCESS"
assert session_id not in auth_adapter.sessions
# 6. Session cookie cleared on client
set_cookie_header = res_logout.headers.get("set-cookie", "")
assert "Max-Age=0" in set_cookie_header or "max-age=0" in set_cookie_header
# 7. Subsequent request is unauthenticated
res_after = client.get("/birthday/api/auth/session")
assert res_after.json()["authenticated"] is False
def test_fixture_live_users_password_grant_session_flow(auth_adapter: OIDCAuthAdapter):
"""Test full login session lifecycle against pre-seeded fixture users."""
# 1. Admin user authentication and session establishment
admin_id, admin_session_id = auth_adapter.authenticate_and_establish_session(
username="admin@example.com",
password="password123",
)
assert admin_id.subject == "admin-001"
assert "bdinvite_admins" in admin_id.groups
req_admin = create_request(cookies={auth_adapter.session_cookie_name: admin_session_id})
assert auth_adapter.current_identity(req_admin) == admin_id
# 2. Guest user authentication and session establishment
guest_id, guest_session_id = auth_adapter.authenticate_and_establish_session(
username="guest@example.com",
password="password123",
)
assert guest_id.subject == "guest-001"
assert "guests" in guest_id.groups
req_guest = create_request(cookies={auth_adapter.session_cookie_name: guest_session_id})
assert auth_adapter.current_identity(req_guest) == guest_id
# Distinct sessions for distinct users
assert admin_session_id != guest_session_id
+1854
View File
File diff suppressed because it is too large. Load diff
+41
View File
@@ -0,0 +1,41 @@
services:
bdinvite:
build: .
container_name: bdinvite
restart: unless-stopped
volumes:
- ./data:/app/data
environment:
- BASE_PATH=/birthday
networks:
- proxy-net
labels:
- "diun.enable=false"
- "traefik.enable=true"
# Public router (invitation + public API)
- "traefik.http.routers.bdinvite-public.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
- "traefik.http.routers.bdinvite-public.entrypoints=websecure"
- "traefik.http.routers.bdinvite-public.tls=true"
- "traefik.http.routers.bdinvite-public.priority=10"
- "traefik.http.routers.bdinvite-public.service=bdinvite-svc"
# Admin router (Authelia-protected)
- "traefik.http.routers.bdinvite-admin.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && (PathPrefix(`/birthday/admin`) || PathPrefix(`/birthday/api/admin`))"
- "traefik.http.routers.bdinvite-admin.entrypoints=websecure"
- "traefik.http.routers.bdinvite-admin.tls=true"
- "traefik.http.routers.bdinvite-admin.priority=20"
- "traefik.http.routers.bdinvite-admin.middlewares=authelia-auth@docker"
- "traefik.http.routers.bdinvite-admin.service=bdinvite-svc"
# HTTP to HTTPS redirect
- "traefik.http.routers.bdinvite-red.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
- "traefik.http.routers.bdinvite-red.entrypoints=web"
- "traefik.http.routers.bdinvite-red.middlewares=https-redirect@docker"
# Service target
- "traefik.http.services.bdinvite-svc.loadbalancer.server.port=8000"
networks:
proxy-net:
external: true
+34
View File
@@ -0,0 +1,34 @@
{
"$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true,
"root": ".."
},
"files": {
"ignoreUnknown": true,
"includes": ["src/**", "vite.config.ts"]
},
"formatter": {
"enabled": true,
"indentStyle": "space",
"indentWidth": 2,
"lineWidth": 90
},
"linter": {
"enabled": true,
"rules": {
"preset": "recommended",
"correctness": {
"useExhaustiveDependencies": "warn"
}
}
},
"javascript": {
"formatter": {
"quoteStyle": "double",
"semicolons": "always"
}
}
}
+14
View File
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/birthday/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="theme-color" content="#0a0a0a" />
<title>Birthday Party — Invitación</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1834
View File
File diff suppressed because it is too large. Load diff
+26
View File
@@ -0,0 +1,26 @@
{
"name": "bdinvite-frontend",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build && mkdir -p ../backend/static && cp -r dist/* ../backend/static/",
"preview": "vite preview",
"lint": "biome check .",
"lint:fix": "biome check --write .",
"format": "biome format --write ."
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.2"
},
"devDependencies": {
"@types/react": "^18.3.10",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.2",
"typescript": "^5.6.2",
"vite": "^5.4.8"
}
}
Binary file not shown.
+27
View File
@@ -0,0 +1,27 @@
import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import { AdminLayout } from "./admin/AdminLayout";
import { ConfigEditor } from "./admin/ConfigEditor";
import { RsvpTable } from "./admin/RsvpTable";
import { Invitation } from "./invitation/Invitation";
export function App() {
return (
<BrowserRouter basename="/birthday">
<Routes>
{/* Guest Public Route */}
<Route path="/" element={<Invitation />} />
{/* Authelia-Protected Admin Dashboard */}
<Route path="/admin" element={<AdminLayout />}>
<Route index element={<RsvpTable />} />
<Route path="config" element={<ConfigEditor />} />
</Route>
{/* Catch-all fallback */}
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</BrowserRouter>
);
}
export default App;
+310
View File
@@ -0,0 +1,310 @@
import { useCallback, useEffect, useState } from "react";
import { Link, NavLink, Outlet } from "react-router-dom";
import { type AuthUser, fetchSession, logoutUser } from "../api/client";
export function AdminLayout() {
const [loading, setLoading] = useState<boolean>(true);
const [identity, setIdentity] = useState<AuthUser | null>(null);
const [loggedOut, setLoggedOut] = useState<boolean>(false);
useEffect(() => {
const params = new URLSearchParams(window.location.search);
if (params.get("logged_out") === "1") {
setLoading(false);
setLoggedOut(true);
return;
}
let isMounted = true;
fetchSession()
.then((session) => {
if (!isMounted) return;
if (session.authenticated && session.identity) {
setIdentity(session.identity);
setLoading(false);
} else {
// Unauthenticated user navigating to /birthday/admin initiates login flow
window.location.href = "/birthday/api/auth/login";
}
})
.catch(() => {
if (!isMounted) return;
window.location.href = "/birthday/api/auth/login";
});
return () => {
isMounted = false;
};
}, []);
const handleLogout = useCallback(async () => {
try {
await logoutUser();
} catch (err) {
console.error("Logout error:", err);
}
setIdentity(null);
setLoggedOut(true);
window.history.replaceState(null, "", "/birthday/admin?logged_out=1");
}, []);
if (loading) {
return (
<div
style={{
minHeight: "100vh",
backgroundColor: "#0f0f10",
color: "#f0f0f0",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontFamily: "var(--font-body)",
}}
>
<span style={{ fontSize: "1.1rem", color: "rgba(255, 255, 255, 0.7)" }}>
Cargando panel de control...
</span>
</div>
);
}
if (loggedOut || !identity) {
return (
<div
style={{
minHeight: "100vh",
backgroundColor: "#0f0f10",
color: "#f0f0f0",
fontFamily: "var(--font-body)",
}}
>
<header
style={{
borderBottom: "1px solid rgba(255, 255, 255, 0.1)",
backgroundColor: "#161618",
padding: "1rem 1.8rem",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
<div style={{ display: "flex", alignItems: "center", gap: "0.8rem" }}>
<span style={{ fontSize: "1.4rem" }}>🎂</span>
<h1
style={{
fontSize: "1.1rem",
fontWeight: 600,
letterSpacing: "0.08em",
color: "#ffffff",
textTransform: "uppercase",
}}
>
Panel de Control · Invitación
</h1>
</div>
<a
href="/birthday/api/auth/login"
data-testid="login-link"
style={{
color: "var(--color-gold-light)",
textDecoration: "none",
fontSize: "0.88rem",
fontWeight: 500,
}}
>
Iniciar Sesión
</a>
</header>
<div
data-testid="unauthenticated-state"
style={{
maxWidth: "480px",
margin: "4rem auto",
textAlign: "center",
padding: "2.5rem 1.5rem",
backgroundColor: "#161618",
borderRadius: "8px",
border: "1px solid rgba(255, 255, 255, 0.1)",
}}
>
<div style={{ fontSize: "2.5rem", marginBottom: "1rem" }}>🔒</div>
<h2 style={{ fontSize: "1.3rem", fontWeight: 600, color: "#fff", marginBottom: "0.6rem" }}>
Sesión Finalizada
</h2>
<p style={{ color: "rgba(255, 255, 255, 0.65)", fontSize: "0.9rem", marginBottom: "1.8rem" }}>
Has cerrado sesión correctamente. No hay sesión autenticada activa.
</p>
<a
href="/birthday/api/auth/login"
data-testid="login-btn"
style={{
display: "inline-block",
padding: "0.65rem 1.5rem",
backgroundColor: "var(--color-gold)",
color: "#0a0a0a",
fontWeight: 600,
borderRadius: "4px",
textDecoration: "none",
fontSize: "0.9rem",
}}
>
Iniciar Sesión
</a>
</div>
</div>
);
}
return (
<div
style={{
minHeight: "100vh",
backgroundColor: "#0f0f10",
color: "#f0f0f0",
fontFamily: "var(--font-body)",
}}
>
{/* Admin Navigation Bar */}
<header
style={{
borderBottom: "1px solid rgba(255, 255, 255, 0.1)",
backgroundColor: "#161618",
padding: "1rem 1.8rem",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
flexWrap: "wrap",
gap: "1rem",
}}
>
<div style={{ display: "flex", alignItems: "center", gap: "0.8rem" }}>
<span style={{ fontSize: "1.4rem" }}>🎂</span>
<h1
style={{
fontSize: "1.1rem",
fontWeight: 600,
letterSpacing: "0.08em",
color: "#ffffff",
textTransform: "uppercase",
}}
>
Panel de Control · Invitación
</h1>
</div>
<nav style={{ display: "flex", alignItems: "center", gap: "1.4rem", flexWrap: "wrap" }}>
<NavLink
to="/admin"
end
style={({ isActive }) => ({
color: isActive ? "var(--color-gold-light)" : "rgba(255, 255, 255, 0.7)",
textDecoration: "none",
fontSize: "0.88rem",
fontWeight: 500,
borderBottom: isActive
? "2px solid var(--color-gold)"
: "2px solid transparent",
paddingBottom: "0.25rem",
transition: "all 0.2s ease",
})}
>
Respuestas
</NavLink>
<NavLink
to="/admin/config"
style={({ isActive }) => ({
color: isActive ? "var(--color-gold-light)" : "rgba(255, 255, 255, 0.7)",
textDecoration: "none",
fontSize: "0.88rem",
fontWeight: 500,
borderBottom: isActive
? "2px solid var(--color-gold)"
: "2px solid transparent",
paddingBottom: "0.25rem",
transition: "all 0.2s ease",
})}
>
Configuración
</NavLink>
<Link
to="/"
target="_blank"
rel="noopener noreferrer"
style={{
color: "rgba(255, 255, 255, 0.5)",
textDecoration: "none",
fontSize: "0.82rem",
display: "inline-flex",
alignItems: "center",
gap: "0.3rem",
}}
>
<span>Ver Pública</span>
<span>↗</span>
</Link>
{/* Authenticated User Info & Logout Button */}
<div
style={{
display: "flex",
alignItems: "center",
gap: "0.9rem",
borderLeft: "1px solid rgba(255, 255, 255, 0.15)",
paddingLeft: "1.2rem",
marginLeft: "0.5rem",
}}
>
<span
data-testid="user-info"
style={{
fontSize: "0.84rem",
color: "rgba(255, 255, 255, 0.85)",
fontWeight: 500,
}}
>
👤 {identity.name ? `${identity.name} (${identity.email})` : identity.email}
</span>
<button
type="button"
data-testid="logout-btn"
aria-label="Logout"
onClick={handleLogout}
style={{
backgroundColor: "transparent",
color: "rgba(255, 255, 255, 0.8)",
border: "1px solid rgba(255, 255, 255, 0.25)",
borderRadius: "4px",
padding: "0.3rem 0.75rem",
fontSize: "0.8rem",
cursor: "pointer",
transition: "all 0.2s ease",
}}
onMouseEnter={(e) => {
e.currentTarget.style.borderColor = "var(--color-gold)";
e.currentTarget.style.color = "var(--color-gold-light)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.borderColor = "rgba(255, 255, 255, 0.25)";
e.currentTarget.style.color = "rgba(255, 255, 255, 0.8)";
}}
>
Logout
</button>
</div>
</nav>
</header>
{/* Main Admin Content Container */}
<div
style={{
maxWidth: "1000px",
margin: "0 auto",
padding: "2rem 1.5rem",
}}
>
<Outlet />
</div>
</div>
);
}
+505
View File
@@ -0,0 +1,505 @@
import { type FormEvent, useEffect, useState } from "react";
import { fetchAdminConfig, regenerateMapPreview, updateAdminConfig } from "../api/client";
import { Button } from "../components/Button";
import { Field } from "../components/Field";
import { Spinner } from "../components/Spinner";
import type { InvitationConfig } from "../types/config";
export function ConfigEditor() {
const [formData, setFormData] = useState<InvitationConfig | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [regeneratingMap, setRegeneratingMap] = useState(false);
const [mapNotice, setMapNotice] = useState<{
type: "success" | "error";
msg: string;
} | null>(null);
const [feedback, setFeedback] = useState<{
type: "success" | "error";
msg: string;
} | null>(null);
useEffect(() => {
async function load() {
try {
const data = await fetchAdminConfig();
setFormData(data);
} catch (err) {
setFeedback({
type: "error",
msg: err instanceof Error ? err.message : "Error al cargar la configuración.",
});
} finally {
setLoading(false);
}
}
load();
}, []);
function handleChange(field: keyof InvitationConfig, value: string) {
if (!formData) return;
setFormData({ ...formData, [field]: value });
}
async function handleSubmit(e: FormEvent) {
e.preventDefault();
if (!formData || saving) return;
setSaving(true);
setFeedback(null);
try {
const { id, updated_at, ...cleanPayload } = formData;
const updated = await updateAdminConfig(cleanPayload);
setFormData(updated);
setFeedback({ type: "success", msg: "¡Configuración guardada exitosamente!" });
} catch (err) {
setFeedback({
type: "error",
msg: err instanceof Error ? err.message : "Error al guardar.",
});
} finally {
setSaving(false);
}
}
async function handleRegenerateMap() {
if (!formData?.map_url || regeneratingMap) return;
setRegeneratingMap(true);
setMapNotice(null);
try {
const res = await regenerateMapPreview(formData.map_url);
setFormData({ ...formData, map_preview_url: res.map_preview_url });
setMapNotice({
type: "success",
msg: `¡Vista previa regenerada con éxito! (Coordenadas: ${res.lat.toFixed(4)}, ${res.lng.toFixed(4)})`,
});
} catch (err) {
setMapNotice({
type: "error",
msg: err instanceof Error ? err.message : "Error al regenerar el mapa.",
});
} finally {
setRegeneratingMap(false);
}
}
if (loading) {
return (
<div style={{ padding: "4rem", textAlign: "center" }}>
<Spinner size={32} />
</div>
);
}
if (!formData) {
return (
<div style={{ color: "var(--color-error)", padding: "2rem" }}>
{feedback?.msg || "No se pudo cargar la configuración."}
</div>
);
}
return (
<div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "2.5rem" }}>
<div>
<h2
style={{
fontSize: "1.4rem",
fontWeight: 600,
color: "#ffffff",
marginBottom: "0.4rem",
}}
>
Editar Contenido de la Invitación
</h2>
<p
style={{
fontSize: "0.88rem",
color: "rgba(255, 255, 255, 0.6)",
marginBottom: "1.8rem",
}}
>
Los cambios guardados se reflejan inmediatamente en la invitación pública.
</p>
{feedback && (
<div
style={{
padding: "0.9rem 1.2rem",
borderRadius: "4px",
marginBottom: "1.8rem",
backgroundColor:
feedback.type === "success"
? "rgba(46, 204, 113, 0.15)"
: "var(--color-error-bg)",
border: `1px solid ${feedback.type === "success" ? "#2ecc71" : "var(--color-error)"}`,
color: feedback.type === "success" ? "#2ecc71" : "#ff8b80",
fontSize: "0.88rem",
}}
>
{feedback.msg}
</div>
)}
<form onSubmit={handleSubmit}>
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))",
gap: "1rem",
}}
>
<Field
label="Título Principal"
value={formData.title}
onChange={(e) => handleChange("title", e.target.value)}
required
/>
<Field
label="Nombre del Homenajeado(a)"
value={formData.honoree_name}
onChange={(e) => handleChange("honoree_name", e.target.value)}
required
/>
</div>
<Field
label="Texto de Invitación"
value={formData.invitation_text}
onChange={(e) => handleChange("invitation_text", e.target.value)}
required
/>
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fit, minmax(180px, 1fr))",
gap: "1rem",
}}
>
<Field
label="Fecha del Evento (YYYY-MM-DD)"
value={formData.event_date}
onChange={(e) => handleChange("event_date", e.target.value)}
required
/>
<Field
label="Hora del Evento (HH:MM)"
value={formData.event_time}
onChange={(e) => handleChange("event_time", e.target.value)}
required
/>
<Field
label="Zona Horaria IANA"
value={formData.event_timezone}
onChange={(e) => handleChange("event_timezone", e.target.value)}
required
/>
</div>
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))",
gap: "1rem",
}}
>
<Field
label="Nombre del Lugar"
value={formData.address_name}
onChange={(e) => handleChange("address_name", e.target.value)}
required
/>
<Field
label="Enlace a Google Maps (map_url)"
value={formData.map_url}
onChange={(e) => handleChange("map_url", e.target.value)}
required
/>
</div>
<div style={{ marginBottom: "1.4rem" }}>
<label
htmlFor="address_lines"
style={{
display: "block",
fontSize: "0.72rem",
fontWeight: 500,
letterSpacing: "0.15em",
textTransform: "uppercase",
color: "var(--color-text-muted)",
marginBottom: "0.45rem",
}}
>
Dirección (una línea por renglón)
</label>
<textarea
id="address_lines"
rows={3}
value={formData.address_lines}
onChange={(e) => handleChange("address_lines", e.target.value)}
style={{
width: "100%",
padding: "0.85rem 1rem",
backgroundColor: "rgba(255, 255, 255, 0.05)",
border: "1px solid var(--color-gold-border)",
borderRadius: "4px",
color: "var(--color-text)",
fontSize: "0.95rem",
outline: "none",
}}
/>
</div>
<div
style={{
backgroundColor: "rgba(255, 255, 255, 0.03)",
border: "1px solid rgba(212, 168, 67, 0.2)",
borderRadius: "6px",
padding: "1.2rem",
marginBottom: "1.4rem",
display: "flex",
flexWrap: "wrap",
gap: "1.5rem",
alignItems: "center",
}}
>
{/* Visual circular thumbnail preview */}
<div
style={{
width: "80px",
height: "80px",
borderRadius: "50%",
overflow: "hidden",
border: "1.5px solid var(--color-gold)",
backgroundColor: "#151515",
flexShrink: 0,
boxShadow: "0 2px 10px rgba(0,0,0,0.5)",
}}
>
{formData.map_preview_url ? (
<img
src={formData.map_preview_url}
alt="Vista previa mapa"
style={{
width: "100%",
height: "100%",
objectFit: "cover",
display: "block",
}}
/>
) : (
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
height: "100%",
fontSize: "0.7rem",
color: "var(--color-text-muted)",
}}
>
Sin mapa
</div>
)}
</div>
<div style={{ flex: 1, minWidth: "240px" }}>
<Field
label="URL de Imagen Previa del Mapa (map_preview_url)"
value={formData.map_preview_url}
onChange={(e) => handleChange("map_preview_url", e.target.value)}
required
/>
<div
style={{
marginTop: "0.8rem",
display: "flex",
alignItems: "center",
gap: "1rem",
flexWrap: "wrap",
}}
>
<Button
type="button"
variant="outline"
disabled={regeneratingMap || !formData.map_url}
onClick={handleRegenerateMap}
style={{ padding: "0.55rem 1.1rem", fontSize: "0.75rem" }}
>
{regeneratingMap ? (
<>
<Spinner size={14} />
<span style={{ marginLeft: "0.5rem" }}>Generando...</span>
</>
) : (
"🗺️ Regenerar Mapa"
)}
</Button>
<span
style={{
fontSize: "0.75rem",
color: "var(--color-text-muted)",
}}
>
Genera la imagen en disco sin guardar aún en la BD.
</span>
</div>
{mapNotice && (
<div
style={{
marginTop: "0.6rem",
fontSize: "0.8rem",
color:
mapNotice.type === "success"
? "var(--color-gold)"
: "var(--color-error)",
}}
>
{mapNotice.msg}
</div>
)}
</div>
</div>
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))",
gap: "1rem",
}}
>
<Field
label="Encabezado del Formulario"
value={formData.rsvp_heading}
onChange={(e) => handleChange("rsvp_heading", e.target.value)}
required
/>
<Field
label="Texto del Botón CTA Inicial"
value={formData.rsvp_cta}
onChange={(e) => handleChange("rsvp_cta", e.target.value)}
required
/>
<Field
label="Texto del Botón de Envío"
value={formData.submit_label}
onChange={(e) => handleChange("submit_label", e.target.value)}
required
/>
</div>
<div
style={{
display: "grid",
gridTemplateColumns: "repeat(auto-fit, minmax(250px, 1fr))",
gap: "1rem",
}}
>
<Field
label="Mensaje de Confirmación Éxito"
value={formData.msg_success}
onChange={(e) => handleChange("msg_success", e.target.value)}
required
/>
<Field
label="Saludo de Éxito ({name})"
value={formData.msg_success_greeting}
onChange={(e) => handleChange("msg_success_greeting", e.target.value)}
required
/>
</div>
<Field
label="Mensaje para Teléfono Duplicado"
value={formData.msg_duplicate}
onChange={(e) => handleChange("msg_duplicate", e.target.value)}
required
/>
<div style={{ marginTop: "2rem" }}>
<Button type="submit" variant="primary" disabled={saving}>
{saving ? "Guardando..." : "Guardar Cambios"}
</Button>
</div>
</form>
</div>
{/* Live Plain-Text Preview Section */}
<div
style={{
borderTop: "1px solid rgba(255, 255, 255, 0.1)",
paddingTop: "2rem",
}}
>
<h3
style={{
fontSize: "1.1rem",
fontWeight: 600,
color: "var(--color-gold-light)",
textTransform: "uppercase",
letterSpacing: "0.1em",
marginBottom: "1rem",
}}
>
Vista Previa de Composición (Texto)
</h3>
<div
style={{
backgroundColor: "#161618",
border: "1px solid rgba(255, 255, 255, 0.08)",
borderRadius: "6px",
padding: "1.8rem",
lineHeight: 1.8,
fontSize: "0.92rem",
maxWidth: "500px",
}}
>
<p style={{ fontSize: "1.5rem", fontWeight: 700, color: "#ffffff" }}>
{formData.title}
</p>
<p
style={{
letterSpacing: "0.15em",
textTransform: "uppercase",
color: "rgba(255, 255, 255, 0.6)",
}}
>
{formData.invitation_text}
</p>
<p
style={{
fontSize: "1.3rem",
color: "var(--color-gold-light)",
margin: "0.6rem 0",
}}
>
{formData.honoree_name}
</p>
<p style={{ color: "#ffffff" }}>
📅 {formData.event_date} · ⏰ {formData.event_time} ({formData.event_timezone}
)
</p>
<p style={{ color: "#ffffff", marginTop: "0.4rem" }}>
📍 {formData.address_name} — {formData.address_lines.replace(/\n/g, ", ")}
</p>
<div
style={{
marginTop: "1rem",
paddingTop: "0.8rem",
borderTop: "1px dashed rgba(255, 255, 255, 0.15)",
}}
>
<p style={{ color: "var(--color-gold)" }}>CTA: {formData.rsvp_cta}</p>
<p style={{ color: "var(--color-text-dim)", fontSize: "0.82rem" }}>
Éxito: "{formData.msg_success}"{" "}
{formData.msg_success_greeting.replace("{name}", "[Nombre]")}
</p>
</div>
</div>
</div>
</div>
);
}
+619
View File
@@ -0,0 +1,619 @@
import { useCallback, useEffect, useState } from "react";
import {
deleteAdminRsvp,
fetchAdminRsvps,
getExportCsvUrl,
updateAdminRsvp,
} from "../api/client";
import { Button } from "../components/Button";
import { Spinner } from "../components/Spinner";
import { useConfig } from "../hooks/useConfig";
import type { RSVPAdminItem } from "../types/config";
export function RsvpTable() {
const { config } = useConfig();
const [rsvps, setRsvps] = useState<RSVPAdminItem[]>([]);
const [count, setCount] = useState<number>(0);
const [search, setSearch] = useState<string>("");
const [loading, setLoading] = useState<boolean>(true);
const [deletingId, setDeletingId] = useState<number | null>(null);
const [editingId, setEditingId] = useState<number | null>(null);
const [editForm, setEditForm] = useState<{ name: string; phone: string; email: string }>({
name: "",
phone: "",
email: "",
});
const [savingId, setSavingId] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
const loadData = useCallback(async (searchTerm = "") => {
setLoading(true);
setError(null);
try {
const data = await fetchAdminRsvps(searchTerm);
setRsvps(data.rsvps);
setCount(data.count);
} catch (err) {
setError(err instanceof Error ? err.message : "Error al cargar las respuestas.");
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
loadData(search);
}, [search, loadData]);
function formatDate(isoStr: string) {
if (!isoStr) return "—";
try {
// Ensure ISO string without an explicit offset is treated as UTC
const normalizedIso =
!isoStr.endsWith("Z") && !isoStr.includes("+") && !isoStr.includes("-", 10)
? `${isoStr}Z`
: isoStr;
const d = new Date(normalizedIso);
return d.toLocaleDateString("es-CO", {
timeZone: config?.event_timezone || "America/Bogota",
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
} catch {
return isoStr;
}
}
function formatPhone(phone: string) {
if (phone.length === 10) {
return `${phone.slice(0, 3)} ${phone.slice(3, 6)} ${phone.slice(6)}`;
}
return phone;
}
async function handleDelete(id: number, name: string) {
const confirmed = window.confirm(
`¿Estás seguro de que deseas eliminar la confirmación de "${name}"? Esta acción no se puede deshacer.`,
);
if (!confirmed) return;
setDeletingId(id);
setError(null);
try {
await deleteAdminRsvp(id);
setRsvps((prev) => prev.filter((r) => r.id !== id));
setCount((prev) => Math.max(0, prev - 1));
} catch (err) {
setError(
err instanceof Error ? err.message : "Error al eliminar el asistente.",
);
} finally {
setDeletingId(null);
}
}
function startEditing(row: RSVPAdminItem) {
setEditingId(row.id);
setEditForm({
name: row.name,
phone: row.phone,
email: row.email || "",
});
setError(null);
}
function cancelEditing() {
setEditingId(null);
setError(null);
}
async function handleSaveEdit(id: number) {
if (!editForm.name.trim()) {
setError("El nombre no puede estar vacío.");
return;
}
if (!editForm.phone.trim()) {
setError("El teléfono no puede estar vacío.");
return;
}
setSavingId(id);
setError(null);
try {
const updated = await updateAdminRsvp(id, {
name: editForm.name.trim(),
phone: editForm.phone.trim(),
email: editForm.email.trim() || null,
});
setRsvps((prev) => prev.map((r) => (r.id === id ? updated : r)));
setEditingId(null);
} catch (err) {
setError(
err instanceof Error ? err.message : "Error al actualizar el asistente.",
);
} finally {
setSavingId(null);
}
}
return (
<div>
{/* Top action bar: Count, Search, Export */}
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
flexWrap: "wrap",
gap: "1.2rem",
marginBottom: "1.8rem",
}}
>
<div>
<h2 style={{ fontSize: "1.4rem", fontWeight: 600, color: "#ffffff" }}>
Asistentes Confirmados
</h2>
<p
style={{
fontSize: "0.88rem",
color: "rgba(255, 255, 255, 0.6)",
marginTop: "0.2rem",
}}
>
Total de registros:{" "}
<strong style={{ color: "var(--color-gold-light)" }}>{count}</strong>
</p>
</div>
<div
style={{ display: "flex", alignItems: "center", gap: "1rem", flexWrap: "wrap" }}
>
<input
type="search"
placeholder="Buscar por nombre, tel..."
value={search}
onChange={(e) => setSearch(e.target.value)}
style={{
padding: "0.6rem 1rem",
borderRadius: "4px",
backgroundColor: "rgba(255, 255, 255, 0.08)",
border: "1px solid rgba(255, 255, 255, 0.2)",
color: "#ffffff",
fontSize: "0.88rem",
outline: "none",
minWidth: "220px",
}}
/>
<a
href={getExportCsvUrl()}
download="rsvps.csv"
style={{ textDecoration: "none" }}
>
<Button
variant="outline"
style={{ padding: "0.6rem 1.2rem", fontSize: "0.75rem" }}
>
Descargar CSV ⤓
</Button>
</a>
</div>
</div>
{error && (
<div
style={{
padding: "1rem",
backgroundColor: "var(--color-error-bg)",
border: "1px solid var(--color-error)",
borderRadius: "4px",
color: "#ff8b80",
marginBottom: "1.5rem",
fontSize: "0.88rem",
}}
>
{error}
</div>
)}
{/* Table container */}
<div
style={{
backgroundColor: "#161618",
borderRadius: "6px",
border: "1px solid rgba(255, 255, 255, 0.08)",
overflowX: "auto",
}}
>
<table
style={{
width: "100%",
borderCollapse: "collapse",
textAlign: "left",
fontSize: "0.88rem",
}}
>
<thead>
<tr
style={{
borderBottom: "1px solid rgba(255, 255, 255, 0.12)",
backgroundColor: "rgba(255, 255, 255, 0.03)",
color: "rgba(255, 255, 255, 0.6)",
fontSize: "0.75rem",
letterSpacing: "0.1em",
textTransform: "uppercase",
}}
>
<th style={{ padding: "0.9rem 1.2rem" }}>Nombre</th>
<th style={{ padding: "0.9rem 1.2rem" }}>Teléfono</th>
<th style={{ padding: "0.9rem 1.2rem" }}>Correo</th>
<th style={{ padding: "0.9rem 1.2rem" }}>Fecha de Registro</th>
<th style={{ padding: "0.9rem 1.2rem", textAlign: "right" }}>Acciones</th>
</tr>
</thead>
<tbody>
{loading ? (
<tr>
<td colSpan={5} style={{ padding: "3rem", textAlign: "center" }}>
<Spinner size={28} />
</td>
</tr>
) : rsvps.length === 0 ? (
<tr>
<td
colSpan={5}
style={{
padding: "3rem",
textAlign: "center",
color: "rgba(255, 255, 255, 0.5)",
}}
>
{search
? "No se encontraron coincidencias."
: "Aún no hay confirmaciones registradas."}
</td>
</tr>
) : (
rsvps.map((row) => (
<tr
key={row.id}
style={{
borderBottom: "1px solid rgba(255, 255, 255, 0.06)",
backgroundColor:
editingId === row.id
? "rgba(212, 168, 67, 0.08)"
: "transparent",
transition: "background-color 0.15s ease",
}}
onMouseEnter={(e) => {
if (editingId !== row.id) {
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.04)";
}
}}
onMouseLeave={(e) => {
if (editingId !== row.id) {
e.currentTarget.style.backgroundColor = "transparent";
}
}}
>
<td
style={{
padding: editingId === row.id ? "0.5rem 0.8rem" : "0.9rem 1.2rem",
fontWeight: 500,
color: "#ffffff",
}}
>
{editingId === row.id ? (
<input
type="text"
value={editForm.name}
onChange={(e) =>
setEditForm((prev) => ({ ...prev, name: e.target.value }))
}
disabled={savingId === row.id}
placeholder="Nombre completo"
style={{
width: "100%",
minWidth: "120px",
backgroundColor: "rgba(0, 0, 0, 0.5)",
border: "1px solid var(--color-gold)",
borderRadius: "4px",
color: "#ffffff",
padding: "0.4rem 0.6rem",
fontSize: "0.85rem",
boxSizing: "border-box",
}}
/>
) : (
row.name
)}
</td>
<td
style={{
padding: editingId === row.id ? "0.5rem 0.8rem" : "0.9rem 1.2rem",
color: "var(--color-gold-light)",
}}
>
{editingId === row.id ? (
<input
type="tel"
value={editForm.phone}
onChange={(e) =>
setEditForm((prev) => ({ ...prev, phone: e.target.value }))
}
disabled={savingId === row.id}
placeholder="300 123 4567"
style={{
width: "100%",
minWidth: "110px",
backgroundColor: "rgba(0, 0, 0, 0.5)",
border: "1px solid var(--color-gold)",
borderRadius: "4px",
color: "var(--color-gold-light)",
padding: "0.4rem 0.6rem",
fontSize: "0.85rem",
boxSizing: "border-box",
}}
/>
) : (
formatPhone(row.phone)
)}
</td>
<td
style={{
padding: editingId === row.id ? "0.5rem 0.8rem" : "0.9rem 1.2rem",
color: "rgba(255, 255, 255, 0.7)",
}}
>
{editingId === row.id ? (
<input
type="email"
value={editForm.email}
onChange={(e) =>
setEditForm((prev) => ({ ...prev, email: e.target.value }))
}
disabled={savingId === row.id}
placeholder="Opcional"
style={{
width: "100%",
minWidth: "120px",
backgroundColor: "rgba(0, 0, 0, 0.5)",
border: "1px solid var(--color-gold)",
borderRadius: "4px",
color: "rgba(255, 255, 255, 0.9)",
padding: "0.4rem 0.6rem",
fontSize: "0.85rem",
boxSizing: "border-box",
}}
/>
) : (
row.email || "—"
)}
</td>
<td
style={{
padding: "0.9rem 1.2rem",
color: "rgba(255, 255, 255, 0.5)",
fontSize: "0.8rem",
}}
>
{formatDate(row.created_at)}
</td>
<td style={{ padding: "0.9rem 1.2rem", textAlign: "right", whiteSpace: "nowrap" }}>
{editingId === row.id ? (
<div style={{ display: "inline-flex", alignItems: "center", gap: "0.4rem" }}>
<button
type="button"
disabled={savingId === row.id}
onClick={() => handleSaveEdit(row.id)}
style={{
background: "rgba(76, 175, 80, 0.15)",
border: "1px solid rgba(76, 175, 80, 0.4)",
borderRadius: "4px",
color: "#81c784",
padding: "0.45rem 0.65rem",
cursor: savingId === row.id ? "not-allowed" : "pointer",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
transition: "all 0.15s ease",
outline: "none",
}}
onMouseEnter={(e) => {
if (savingId !== row.id) {
e.currentTarget.style.backgroundColor = "rgba(76, 175, 80, 0.3)";
e.currentTarget.style.borderColor = "#81c784";
}
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "rgba(76, 175, 80, 0.15)";
e.currentTarget.style.borderColor = "rgba(76, 175, 80, 0.4)";
}}
title="Guardar cambios"
aria-label="Guardar cambios"
>
{savingId === row.id ? (
<Spinner size={14} />
) : (
<svg
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.5"
strokeLinecap="round"
strokeLinejoin="round"
role="img"
aria-label="Guardar"
>
<polyline points="20 6 9 17 4 12" />
</svg>
)}
</button>
<button
type="button"
disabled={savingId === row.id}
onClick={cancelEditing}
style={{
background: "rgba(255, 255, 255, 0.08)",
border: "1px solid rgba(255, 255, 255, 0.2)",
borderRadius: "4px",
color: "rgba(255, 255, 255, 0.7)",
padding: "0.45rem 0.65rem",
cursor: savingId === row.id ? "not-allowed" : "pointer",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
transition: "all 0.15s ease",
outline: "none",
}}
onMouseEnter={(e) => {
if (savingId !== row.id) {
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.18)";
e.currentTarget.style.color = "#ffffff";
}
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "rgba(255, 255, 255, 0.08)";
e.currentTarget.style.color = "rgba(255, 255, 255, 0.7)";
}}
title="Cancelar edición"
aria-label="Cancelar edición"
>
<svg
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.5"
strokeLinecap="round"
strokeLinejoin="round"
role="img"
aria-label="Cancelar"
>
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
</div>
) : (
<div style={{ display: "inline-flex", alignItems: "center", gap: "0.4rem" }}>
<button
type="button"
disabled={deletingId === row.id || editingId !== null}
onClick={() => startEditing(row)}
style={{
background: "rgba(212, 168, 67, 0.1)",
border: "1px solid rgba(212, 168, 67, 0.35)",
borderRadius: "4px",
color: "var(--color-gold)",
padding: "0.45rem 0.65rem",
cursor:
deletingId === row.id || editingId !== null ? "not-allowed" : "pointer",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
transition: "all 0.15s ease",
outline: "none",
opacity: editingId !== null && editingId !== row.id ? 0.35 : 1,
}}
onMouseEnter={(e) => {
if (deletingId !== row.id && editingId === null) {
e.currentTarget.style.backgroundColor = "rgba(212, 168, 67, 0.25)";
e.currentTarget.style.borderColor = "var(--color-gold-light)";
}
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "rgba(212, 168, 67, 0.1)";
e.currentTarget.style.borderColor = "rgba(212, 168, 67, 0.35)";
}}
title={`Editar confirmación de ${row.name}`}
aria-label={`Editar confirmación de ${row.name}`}
>
<svg
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
role="img"
aria-label="Editar"
>
<path d="M12 20h9" />
<path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" />
</svg>
</button>
<button
type="button"
disabled={deletingId === row.id || editingId !== null}
onClick={() => handleDelete(row.id, row.name)}
style={{
background: "rgba(255, 82, 82, 0.1)",
border: "1px solid rgba(255, 82, 82, 0.35)",
borderRadius: "4px",
color: "#ff5252",
padding: "0.45rem 0.65rem",
cursor:
deletingId === row.id || editingId !== null ? "not-allowed" : "pointer",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
transition: "all 0.15s ease",
outline: "none",
opacity: editingId !== null && editingId !== row.id ? 0.35 : 1,
}}
onMouseEnter={(e) => {
if (deletingId !== row.id && editingId === null) {
e.currentTarget.style.backgroundColor = "rgba(255, 82, 82, 0.25)";
e.currentTarget.style.borderColor = "#ff5252";
}
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "rgba(255, 82, 82, 0.1)";
e.currentTarget.style.borderColor = "rgba(255, 82, 82, 0.35)";
}}
title={`Eliminar confirmación de ${row.name}`}
aria-label={`Eliminar confirmación de ${row.name}`}
>
{deletingId === row.id ? (
<Spinner size={14} />
) : (
<svg
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
role="img"
aria-label="Eliminar"
>
<polyline points="3 6 5 6 21 6" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
<line x1="10" y1="11" x2="10" y2="17" />
<line x1="14" y1="11" x2="14" y2="17" />
</svg>
)}
</button>
</div>
)}
</td>
</tr>
))
)}
</tbody>
</table>
</div>
</div>
);
}
+203
View File
@@ -0,0 +1,203 @@
import type {
InvitationConfig,
RSVPApiResult,
RSVPAdminItem,
RSVPListResponse,
RSVPRequest,
RSVPUpdateRequest,
} from "../types/config";
const BASE_API = "/birthday/api";
export async function fetchConfig(): Promise<InvitationConfig> {
const res = await fetch(`${BASE_API}/config`, {
headers: { Accept: "application/json" },
});
if (!res.ok) {
throw new Error(`Failed to load config: HTTP ${res.status}`);
}
return res.json();
}
export async function submitRsvp(data: RSVPRequest): Promise<RSVPApiResult> {
try {
const res = await fetch(`${BASE_API}/rsvp`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(data),
});
const json = await res.json();
return json as RSVPApiResult;
} catch {
return { result: "ERROR" };
}
}
export async function fetchAdminRsvps(search?: string): Promise<RSVPListResponse> {
const url = new URL(`${BASE_API}/admin/rsvps`, window.location.origin);
if (search?.trim()) {
url.searchParams.set("search", search.trim());
}
const res = await fetch(url.toString(), {
headers: { Accept: "application/json" },
});
if (!res.ok) {
throw new Error(`Error fetching admin RSVPs: HTTP ${res.status}`);
}
return res.json();
}
export async function fetchAdminConfig(): Promise<InvitationConfig> {
const res = await fetch(`${BASE_API}/admin/config`, {
headers: { Accept: "application/json" },
});
if (!res.ok) {
throw new Error(`Error fetching admin config: HTTP ${res.status}`);
}
return res.json();
}
export async function updateAdminConfig(
config: Omit<InvitationConfig, "id" | "updated_at">,
): Promise<InvitationConfig> {
const res = await fetch(`${BASE_API}/admin/config`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(config),
});
if (!res.ok) {
const errorJson = await res.json().catch(() => null);
const msg = errorJson?.errors
? Object.values(errorJson.errors).join(", ")
: `HTTP ${res.status}`;
throw new Error(`Error saving configuration: ${msg}`);
}
return res.json();
}
export function getExportCsvUrl(): string {
return `${BASE_API}/admin/export`;
}
export interface GenerateMapPreviewResponse {
map_preview_url: string;
lat: number;
lng: number;
message: string;
}
export async function regenerateMapPreview(
mapUrl?: string,
): Promise<GenerateMapPreviewResponse> {
const res = await fetch(`${BASE_API}/admin/map-preview/generate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({ map_url: mapUrl }),
});
if (!res.ok) {
const errorJson = await res.json().catch(() => null);
const msg =
errorJson?.detail ||
(errorJson?.errors
? Object.values(errorJson.errors).join(", ")
: `HTTP ${res.status}`);
throw new Error(msg || "Error al regenerar vista previa del mapa.");
}
return res.json();
}
export async function deleteAdminRsvp(rsvpId: number): Promise<void> {
const res = await fetch(`${BASE_API}/admin/rsvps/${rsvpId}`, {
method: "DELETE",
headers: { Accept: "application/json" },
});
if (!res.ok && res.status !== 204) {
const errorJson = await res.json().catch(() => null);
const msg = errorJson?.detail || `HTTP ${res.status}`;
throw new Error(`Error al eliminar asistente: ${msg}`);
}
}
export async function updateAdminRsvp(
rsvpId: number,
data: RSVPUpdateRequest,
): Promise<RSVPAdminItem> {
const res = await fetch(`${BASE_API}/admin/rsvps/${rsvpId}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(data),
});
if (!res.ok) {
const errorJson = await res.json().catch(() => null);
const msg =
errorJson?.detail ||
(errorJson?.errors
? Object.values(errorJson.errors).join(", ")
: `HTTP ${res.status}`);
throw new Error(msg || "Error al actualizar asistente.");
}
return res.json();
}
export interface AuthUser {
subject: string;
email: string;
name: string | null;
groups: string[];
}
export interface SessionResponse {
authenticated: boolean;
identity: AuthUser | null;
}
export async function fetchSession(): Promise<SessionResponse> {
try {
const res = await fetch(`${BASE_API}/auth/me`, {
headers: { Accept: "application/json" },
});
if (!res.ok) {
return { authenticated: false, identity: null };
}
const data = await res.json();
if ("authenticated" in data) {
return data as SessionResponse;
}
if (data && (data.subject || data.email)) {
return {
authenticated: true,
identity: data as AuthUser,
};
}
return { authenticated: false, identity: null };
} catch {
return { authenticated: false, identity: null };
}
}
export async function logoutUser(): Promise<void> {
await fetch(`${BASE_API}/auth/logout`, {
method: "POST",
headers: { Accept: "application/json" },
});
}
+54
View File
@@ -0,0 +1,54 @@
import type { ButtonHTMLAttributes } from "react";
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: "primary" | "secondary" | "outline";
fullWidth?: boolean;
}
export function Button({
children,
variant = "primary",
fullWidth = false,
disabled,
style,
...props
}: ButtonProps) {
const isPrimary = variant === "primary";
const isOutline = variant === "outline";
return (
<button
disabled={disabled}
style={{
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
padding: "0.85rem 1.8rem",
fontSize: "0.85rem",
fontWeight: 600,
letterSpacing: "0.18em",
textTransform: "uppercase",
borderRadius: "4px",
border: isOutline
? "1px solid var(--color-gold)"
: isPrimary
? "1px solid var(--color-gold)"
: "1px solid rgba(255, 255, 255, 0.2)",
backgroundColor: isPrimary
? "var(--color-gold)"
: isOutline
? "transparent"
: "rgba(255, 255, 255, 0.08)",
color: isPrimary ? "#0a0a0a" : "var(--color-text)",
opacity: disabled ? 0.6 : 1,
cursor: disabled ? "not-allowed" : "pointer",
transition: "all 0.2s ease",
width: fullWidth ? "100%" : "auto",
...style,
}}
{...props}
>
{children}
</button>
);
}
+92
View File
@@ -0,0 +1,92 @@
import type { InputHTMLAttributes } from "react";
interface FieldProps extends InputHTMLAttributes<HTMLInputElement> {
label: string;
error?: string;
hint?: string;
}
export function Field({ label, id, error, hint, disabled, style, ...props }: FieldProps) {
const inputId = id || `field-${label.toLowerCase().replace(/\s+/g, "-")}`;
const errorId = `${inputId}-error`;
const hintId = `${inputId}-hint`;
return (
<div style={{ marginBottom: "1.4rem", width: "100%", textAlign: "left" }}>
<label
htmlFor={inputId}
style={{
display: "block",
fontSize: "0.72rem",
fontWeight: 500,
letterSpacing: "0.15em",
textTransform: "uppercase",
color: "var(--color-text-muted)",
marginBottom: "0.45rem",
}}
>
{label}
</label>
<input
id={inputId}
disabled={disabled}
aria-invalid={Boolean(error)}
aria-describedby={error ? errorId : hint ? hintId : undefined}
style={{
width: "100%",
padding: "0.85rem 1rem",
backgroundColor: "rgba(255, 255, 255, 0.05)",
border: error
? "1px solid var(--color-error)"
: "1px solid var(--color-gold-border)",
borderRadius: "4px",
color: "var(--color-text)",
fontSize: "0.95rem",
outline: "none",
transition: "border-color 0.2s ease, box-shadow 0.2s ease",
...style,
}}
onFocus={(e) => {
if (!error) {
e.currentTarget.style.borderColor = "var(--color-gold-border-focus)";
e.currentTarget.style.boxShadow = "0 0 0 2px rgba(212, 168, 67, 0.15)";
}
}}
onBlur={(e) => {
if (!error) {
e.currentTarget.style.borderColor = "var(--color-gold-border)";
e.currentTarget.style.boxShadow = "none";
}
}}
{...props}
/>
{hint && !error && (
<span
id={hintId}
style={{
display: "block",
fontSize: "0.72rem",
color: "var(--color-text-dim)",
marginTop: "0.3rem",
}}
>
{hint}
</span>
)}
{error && (
<span
id={errorId}
role="alert"
style={{
display: "block",
fontSize: "0.75rem",
color: "var(--color-error)",
marginTop: "0.35rem",
}}
>
{error}
</span>
)}
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
export function Spinner({ size = 24 }: { size?: number }) {
return (
<div
style={{
display: "inline-block",
width: size,
height: size,
border: "2px solid rgba(212, 168, 67, 0.25)",
borderTopColor: "var(--color-gold)",
borderRadius: "50%",
animation: "spin 0.8s linear infinite",
}}
aria-label="Cargando..."
role="status"
>
<style>{`
@keyframes spin {
to { transform: rotate(360deg); }
}
`}</style>
</div>
);
}
+30
View File
@@ -0,0 +1,30 @@
import { useCallback, useEffect, useState } from "react";
import { fetchConfig } from "../api/client";
import type { InvitationConfig } from "../types/config";
export type ConfigStatus = "loading" | "success" | "error";
export function useConfig() {
const [config, setConfig] = useState<InvitationConfig | null>(null);
const [status, setStatus] = useState<ConfigStatus>("loading");
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
setStatus("loading");
setError(null);
try {
const data = await fetchConfig();
setConfig(data);
setStatus("success");
} catch (err) {
setError(err instanceof Error ? err.message : "Error al cargar la configuración");
setStatus("error");
}
}, []);
useEffect(() => {
load();
}, [load]);
return { config, status, error, reload: load };
}
+127
View File
@@ -0,0 +1,127 @@
import { useEffect, useState } from "react";
export type CountdownState = "counting" | "in_progress" | "finished";
export interface CountdownResult {
days: string;
hours: string;
minutes: string;
seconds: string;
state: CountdownState;
}
/**
* Calculates UTC epoch milliseconds for a local datetime in a specified IANA timezone.
*/
function getTargetUtcMillis(dateStr: string, timeStr: string, timeZone: string): number {
try {
const [year, month, day] = dateStr.split("-").map(Number);
const [hours, minutes] = timeStr.split(":").map(Number);
// Initial guess as UTC
const utcGuess = new Date(Date.UTC(year, month - 1, day, hours, minutes, 0));
const dtf = new Intl.DateTimeFormat("en-US", {
timeZone,
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: false,
});
const parts = dtf.formatToParts(utcGuess);
const p: Record<string, number> = {};
for (const part of parts) {
if (part.type !== "literal") {
p[part.type] = Number(part.value);
}
}
const asLocalInTz = Date.UTC(
p.year,
p.month - 1,
p.day,
p.hour === 24 ? 0 : p.hour,
p.minute,
p.second,
);
const offset = asLocalInTz - utcGuess.getTime();
return utcGuess.getTime() - offset;
} catch {
// Fallback if timezone is unparseable
return new Date(`${dateStr}T${timeStr}:00`).getTime();
}
}
export function useCountdown(
eventDate: string,
eventTime: string,
eventTimezone: string,
): CountdownResult {
const [result, setResult] = useState<CountdownResult>({
days: "00",
hours: "00",
minutes: "00",
seconds: "00",
state: "counting",
});
useEffect(() => {
if (!eventDate || !eventTime) return;
const targetTime = getTargetUtcMillis(
eventDate,
eventTime,
eventTimezone || "America/Bogota",
);
// Typical party duration window: 6 hours
const eventDurationMs = 6 * 60 * 60 * 1000;
function update() {
const now = Date.now();
const diff = targetTime - now;
if (diff > 0) {
const totalSeconds = Math.floor(diff / 1000);
const days = Math.floor(totalSeconds / (3600 * 24));
const hours = Math.floor((totalSeconds % (3600 * 24)) / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
setResult({
days: String(days).padStart(2, "0"),
hours: String(hours).padStart(2, "0"),
minutes: String(minutes).padStart(2, "0"),
seconds: String(seconds).padStart(2, "0"),
state: "counting",
});
} else if (Math.abs(diff) < eventDurationMs) {
setResult({
days: "00",
hours: "00",
minutes: "00",
seconds: "00",
state: "in_progress",
});
} else {
setResult({
days: "00",
hours: "00",
minutes: "00",
seconds: "00",
state: "finished",
});
}
}
update();
const interval = setInterval(update, 1000);
return () => clearInterval(interval);
}, [eventDate, eventTime, eventTimezone]);
return result;
}
+127
View File
@@ -0,0 +1,127 @@
import { useEffect, useState } from "react";
import { submitRsvp } from "../api/client";
const SESSION_STORAGE_KEY = "bdinvite:rsvp-submitted";
export type RsvpFormState = "idle" | "submitting" | "success" | "duplicate" | "error";
export interface FormErrors {
name?: string;
phone?: string;
email?: string;
}
export function useRsvpForm() {
const [name, setName] = useState("");
const [phone, setPhone] = useState("");
const [email, setEmail] = useState("");
const [confirmedName, setConfirmedName] = useState("");
const [formState, setFormState] = useState<RsvpFormState>("idle");
const [errors, setErrors] = useState<FormErrors>({});
// Check sessionStorage on mount for existing submission in this session
useEffect(() => {
try {
const stored = sessionStorage.getItem(SESSION_STORAGE_KEY);
if (stored) {
const parsed = JSON.parse(stored);
if (parsed?.name) {
setConfirmedName(parsed.name);
setFormState("success");
}
}
} catch {
// Ignore sessionStorage read errors
}
}, []);
function validate(): boolean {
const newErrors: FormErrors = {};
const cleanName = name.trim();
if (!cleanName) {
newErrors.name = "Por favor, ingresa tu nombre completo.";
}
// Colombian mobile format: 10 digits starting with 3, optionally +57
const digits = phone.replace(/\D/g, "");
let normalized = digits;
if (normalized.startsWith("57") && normalized.length === 12) {
normalized = normalized.slice(2);
}
if (normalized.length !== 10 || !normalized.startsWith("3")) {
newErrors.phone =
"Ingresa un número móvil válido de 10 dígitos (ej: 300 123 4567).";
}
if (email?.trim()) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email.trim())) {
newErrors.email = "Ingresa un correo electrónico válido.";
}
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
}
async function submit() {
if (!validate()) return;
setFormState("submitting");
// Clean phone
let digits = phone.replace(/\D/g, "");
if (digits.startsWith("57") && digits.length === 12) {
digits = digits.slice(2);
}
const payload = {
name: name.trim(),
phone: digits,
email: email.trim() || null,
};
const result = await submitRsvp(payload);
if (result.result === "SUCCESS") {
setConfirmedName(result.name);
setFormState("success");
try {
sessionStorage.setItem(
SESSION_STORAGE_KEY,
JSON.stringify({ name: result.name, timestamp: Date.now() }),
);
} catch {
// Ignore storage write issues
}
} else if (result.result === "DUPLICATE") {
setFormState("duplicate");
} else if (result.result === "VALIDATION_ERROR") {
setFormState("idle");
setErrors(result.errors);
} else {
setFormState("error");
}
}
function retry() {
setFormState("idle");
}
return {
name,
setName,
phone,
setPhone,
email,
setEmail,
confirmedName,
formState,
errors,
submit,
retry,
};
}
+155
View File
@@ -0,0 +1,155 @@
import type { CountdownState } from "../hooks/useCountdown";
interface CountdownProps {
days: string;
hours: string;
minutes: string;
seconds: string;
state: CountdownState;
label?: string;
inProgressLabel?: string;
finishedLabel?: string;
}
export function Countdown({
days,
hours,
minutes,
seconds,
state,
label = "NOS VEMOS EN",
inProgressLabel = "EVENTO EN CURSO",
finishedLabel = "EVENTO FINALIZADO",
}: CountdownProps) {
if (state === "in_progress") {
return (
<div style={{ textAlign: "center", margin: "1.8rem 0" }}>
<p
style={{
fontSize: "1.1rem",
fontWeight: 600,
letterSpacing: "0.2em",
color: "var(--color-gold-light)",
textTransform: "uppercase",
}}
>
{inProgressLabel}
</p>
</div>
);
}
if (state === "finished") {
return (
<div style={{ textAlign: "center", margin: "1.8rem 0" }}>
<p
style={{
fontSize: "0.95rem",
fontWeight: 500,
letterSpacing: "0.18em",
color: "var(--color-text-dim)",
textTransform: "uppercase",
}}
>
{finishedLabel}
</p>
</div>
);
}
return (
<div style={{ textAlign: "center", margin: "1.8rem 0" }}>
<p
style={{
fontSize: "0.78rem",
fontWeight: 600,
letterSpacing: "0.25em",
color: "var(--color-gold-light)",
textTransform: "uppercase",
marginBottom: "0.75rem",
}}
>
{label}
</p>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: "0.6rem",
fontSize: "1.8rem",
fontWeight: 300,
letterSpacing: "0.08em",
fontVariantNumeric: "tabular-nums",
color: "var(--color-text)",
}}
>
<div style={{ textAlign: "center" }}>
<span>{days}</span>
<span
style={{
display: "block",
fontSize: "0.58rem",
letterSpacing: "0.15em",
color: "var(--color-text-dim)",
marginTop: "0.2rem",
}}
>
DÍAS
</span>
</div>
<span style={{ color: "var(--color-gold)", opacity: 0.7, marginTop: "-0.8rem" }}>
:
</span>
<div style={{ textAlign: "center" }}>
<span>{hours}</span>
<span
style={{
display: "block",
fontSize: "0.58rem",
letterSpacing: "0.15em",
color: "var(--color-text-dim)",
marginTop: "0.2rem",
}}
>
HORAS
</span>
</div>
<span style={{ color: "var(--color-gold)", opacity: 0.7, marginTop: "-0.8rem" }}>
:
</span>
<div style={{ textAlign: "center" }}>
<span>{minutes}</span>
<span
style={{
display: "block",
fontSize: "0.58rem",
letterSpacing: "0.15em",
color: "var(--color-text-dim)",
marginTop: "0.2rem",
}}
>
MIN
</span>
</div>
<span style={{ color: "var(--color-gold)", opacity: 0.7, marginTop: "-0.8rem" }}>
:
</span>
<div style={{ textAlign: "center" }}>
<span>{seconds}</span>
<span
style={{
display: "block",
fontSize: "0.58rem",
letterSpacing: "0.15em",
color: "var(--color-text-dim)",
marginTop: "0.2rem",
}}
>
SEG
</span>
</div>
</div>
</div>
);
}
+178
View File
@@ -0,0 +1,178 @@
import { useRef, useState } from "react";
import { Button } from "../components/Button";
import { Spinner } from "../components/Spinner";
import { useConfig } from "../hooks/useConfig";
import { useRsvpForm } from "../hooks/useRsvpForm";
import { InvitationHero } from "./InvitationHero";
import { ParticleBackground } from "./ParticleBackground";
import { RsvpForm } from "./RsvpForm";
import { RsvpResult } from "./RsvpResult";
export function Invitation() {
const { config, status, error, reload } = useConfig();
const rsvpForm = useRsvpForm();
const [showDetailsOnly, setShowDetailsOnly] = useState(false);
const rsvpSectionRef = useRef<HTMLDivElement | null>(null);
function scrollToRsvp() {
if (rsvpSectionRef.current) {
rsvpSectionRef.current.scrollIntoView({ behavior: "smooth" });
}
}
// 1. Loading Configuration State
if (status === "loading") {
return (
<main
style={{
minHeight: "100vh",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: "1.2rem",
backgroundColor: "var(--color-bg)",
}}
>
<Spinner size={36} />
<p
style={{
fontSize: "0.82rem",
letterSpacing: "0.2em",
color: "var(--color-text-muted)",
textTransform: "uppercase",
}}
>
Cargando invitación...
</p>
</main>
);
}
// 2. Configuration Error State
if (status === "error" || !config) {
return (
<main
style={{
minHeight: "100vh",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
padding: "2rem",
textAlign: "center",
backgroundColor: "var(--color-bg)",
}}
>
<h2
style={{
fontSize: "1.3rem",
fontWeight: 600,
letterSpacing: "0.15em",
color: "var(--color-gold-light)",
textTransform: "uppercase",
marginBottom: "1rem",
}}
>
No pudimos cargar la invitación
</h2>
<p
style={{
fontSize: "0.92rem",
color: "var(--color-text-muted)",
marginBottom: "2rem",
maxWidth: "360px",
lineHeight: 1.6,
}}
>
{error || "Por favor, verifica tu conexión e inténtalo nuevamente."}
</p>
<Button variant="primary" onClick={reload}>
REINTENTAR
</Button>
</main>
);
}
// 3. Loaded Invitation Page Flow
return (
<div style={{ position: "relative", minHeight: "100vh" }}>
{/* Background ambient particle canvas */}
<ParticleBackground />
<main
style={{
position: "relative",
zIndex: 1,
width: "100%",
maxWidth: "480px",
margin: "0 auto",
boxShadow: "0 0 50px rgba(0, 0, 0, 0.8)",
backgroundColor: "rgba(10, 10, 10, 0.85)",
backdropFilter: "blur(2px)",
}}
>
{/* Section 1: Invitation Hero */}
<InvitationHero
config={config}
onCtaClick={() => {
setShowDetailsOnly(false);
scrollToRsvp();
}}
onShowDetailsClick={() => {
setShowDetailsOnly(true);
scrollToRsvp();
}}
/>
{/* Section 2: RSVP / Confirmation Flow */}
<div
id="rsvp-section"
ref={rsvpSectionRef}
style={{
minHeight: "80vh",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
padding: "2.5rem 1.8rem 4rem 1.8rem",
borderTop: "1px solid var(--color-gold-border)",
position: "relative",
}}
>
{showDetailsOnly ? (
<RsvpResult
formState="idle"
confirmedName=""
config={config}
onRetry={() => setShowDetailsOnly(false)}
isDetailsOnly={true}
onBackToForm={() => setShowDetailsOnly(false)}
/>
) : rsvpForm.formState === "idle" || rsvpForm.formState === "submitting" ? (
<RsvpForm
config={config}
name={rsvpForm.name}
setName={rsvpForm.setName}
phone={rsvpForm.phone}
setPhone={rsvpForm.setPhone}
email={rsvpForm.email}
setEmail={rsvpForm.setEmail}
formState={rsvpForm.formState}
errors={rsvpForm.errors}
onSubmit={rsvpForm.submit}
onShowDetails={() => setShowDetailsOnly(true)}
/>
) : (
<RsvpResult
formState={rsvpForm.formState}
confirmedName={rsvpForm.confirmedName}
config={config}
onRetry={rsvpForm.retry}
/>
)}
</div>
</main>
</div>
);
}
+218
View File
@@ -0,0 +1,218 @@
import type { InvitationConfig } from "../types/config";
import { RsvpCta } from "./RsvpCta";
interface InvitationHeroProps {
config: InvitationConfig;
onCtaClick: () => void;
onShowDetailsClick?: () => void;
}
export function InvitationHero({
config,
onCtaClick,
onShowDetailsClick,
}: InvitationHeroProps) {
// Parse date into Month, Day, and Day of Week
const [year, monthNum, dayNum] = config.event_date.split("-").map(Number);
const dateObj = new Date(year, (monthNum || 1) - 1, dayNum || 1);
const monthsEs = [
"ENE",
"FEB",
"MAR",
"ABR",
"MAY",
"JUN",
"JUL",
"AGO",
"SEP",
"OCT",
"NOV",
"DIC",
];
const daysEs = [
"DOMINGO",
"LUNES",
"MARTES",
"MIÉRCOLES",
"JUEVES",
"VIERNES",
"SÁBADO",
];
const monthStr = monthsEs[(monthNum || 1) - 1] || "OCT";
const dayNameStr = daysEs[dateObj.getDay()] || "VIERNES";
const dayStr = String(dayNum || 28);
// Format 24h time to 12h AM/PM if applicable
const [hStr, mStr] = config.event_time.split(":");
let formattedTime = config.event_time;
if (hStr) {
const h = parseInt(hStr, 10);
const m = mStr || "00";
const ampm = h >= 12 ? "PM" : "AM";
const h12 = h % 12 || 12;
formattedTime = `${h12}:${m} ${ampm}`;
}
return (
<section
style={{
width: "100%",
maxWidth: "480px",
minHeight: "100vh",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "space-between",
padding: "3.5rem 1.8rem 2.5rem 1.8rem",
textAlign: "center",
margin: "0 auto",
position: "relative",
zIndex: 1,
}}
>
{/* 1. Header: Script Birthday Party */}
<div style={{ marginTop: "1rem" }}>
<h1
style={{
fontFamily: "var(--font-display)",
fontSize: "clamp(3.2rem, 12vw, 4.4rem)",
fontWeight: 400,
lineHeight: 1.15,
color: "var(--color-text)",
textShadow: "0 2px 20px rgba(212, 168, 67, 0.35)",
}}
>
{config.title || "Birthday Party"}
</h1>
</div>
{/* 2. Invitation wording & Honoree name */}
<div style={{ margin: "2rem 0" }}>
<p
style={{
fontSize: "0.78rem",
fontWeight: 400,
letterSpacing: "0.24em",
textTransform: "uppercase",
color: "var(--color-text-muted)",
lineHeight: 1.8,
maxWidth: "320px",
margin: "0 auto",
}}
>
{config.invitation_text}
</p>
<h2
style={{
fontFamily: "var(--font-display)",
fontSize: "clamp(2.6rem, 10vw, 3.6rem)",
fontWeight: 400,
color: "var(--color-gold-light)",
marginTop: "1.4rem",
textShadow: "0 2px 18px rgba(212, 168, 67, 0.4)",
}}
>
{config.honoree_name}
</h2>
</div>
{/* 3. Event metadata date block */}
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: "1.2rem",
margin: "1.5rem 0",
fontSize: "0.88rem",
letterSpacing: "0.18em",
color: "var(--color-text)",
textTransform: "uppercase",
}}
>
<span style={{ fontWeight: 500, minWidth: "75px" }}>{dayNameStr}</span>
{/* Divider & Day Box */}
<div
style={{
borderLeft: "1px solid rgba(255, 255, 255, 0.25)",
borderRight: "1px solid rgba(255, 255, 255, 0.25)",
padding: "0 1.2rem",
textAlign: "center",
}}
>
<span
style={{
display: "block",
fontSize: "0.68rem",
letterSpacing: "0.2em",
color: "var(--color-text-muted)",
marginBottom: "0.15rem",
}}
>
{monthStr}
</span>
<span
style={{
display: "block",
fontSize: "1.7rem",
fontWeight: 700,
lineHeight: 1,
letterSpacing: "0.05em",
}}
>
{dayStr}
</span>
</div>
<span style={{ fontWeight: 500, minWidth: "75px" }}>{formattedTime}</span>
</div>
{/* 4. RSVP Call to action */}
<div
style={{
marginBottom: "1rem",
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: "0.8rem",
}}
>
<RsvpCta label={config.rsvp_cta} onClick={onCtaClick} />
{onShowDetailsClick && (
<button
type="button"
onClick={onShowDetailsClick}
style={{
background: "none",
border: "none",
color: "var(--color-text-muted)",
fontSize: "0.74rem",
letterSpacing: "0.14em",
textTransform: "uppercase",
cursor: "pointer",
padding: "0.3rem 0.6rem",
textDecoration: "underline",
textUnderlineOffset: "3px",
opacity: 0.8,
transition: "opacity 0.2s ease, color 0.2s ease",
}}
onMouseEnter={(e) => {
e.currentTarget.style.opacity = "1";
e.currentTarget.style.color = "var(--color-gold)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.opacity = "0.8";
e.currentTarget.style.color = "var(--color-text-muted)";
}}
>
¿Ya confirmaste? Ver ubicación y mapa
</button>
)}
</div>
</section>
);
}
+123
View File
@@ -0,0 +1,123 @@
import { useState } from "react";
interface MapPreviewProps {
previewUrl: string;
mapUrl: string;
venueName: string;
}
export function MapPreview({ previewUrl, mapUrl, venueName }: MapPreviewProps) {
const [imgError, setImgError] = useState(false);
const [isHovered, setIsHovered] = useState(false);
return (
<div style={{ textAlign: "center", margin: "1.6rem 0" }}>
<a
href={mapUrl}
target="_blank"
rel="noopener noreferrer"
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
onFocus={() => setIsHovered(true)}
onBlur={() => setIsHovered(false)}
style={{
display: "inline-block",
textDecoration: "none",
color: "inherit",
outline: "none",
}}
aria-label={`Ver ubicación de ${venueName} en Google Maps`}
>
<div
style={{
width: "140px",
height: "140px",
margin: "0 auto",
borderRadius: "50%",
overflow: "hidden",
border: `1.5px solid ${isHovered ? "var(--color-gold-border-focus)" : "var(--color-gold-border)"}`,
boxShadow: isHovered
? "0 6px 24px rgba(0, 0, 0, 0.7), 0 0 20px rgba(212, 168, 67, 0.3)"
: "0 4px 20px rgba(0, 0, 0, 0.5), 0 0 15px rgba(212, 168, 67, 0.15)",
transform: isHovered ? "scale(1.06)" : "scale(1)",
transition:
"transform 0.25s ease, border-color 0.25s ease, box-shadow 0.25s ease",
position: "relative",
backgroundColor: "#1a1a1a",
}}
>
{!imgError && previewUrl ? (
<img
src={previewUrl}
alt={`Mapa de ${venueName}`}
onError={() => setImgError(true)}
style={{
width: "100%",
height: "100%",
objectFit: "cover",
display: "block",
filter: "contrast(1.1) brightness(0.9)",
}}
/>
) : (
<div
style={{
width: "100%",
height: "100%",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
color: "var(--color-gold)",
backgroundColor: "#151515",
padding: "0.5rem",
}}
>
<svg
width="28"
height="28"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
role="img"
aria-label="Icono de mapa"
>
<title>Icono de mapa</title>
<path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" />
<circle cx="12" cy="10" r="3" />
</svg>
<span
style={{
fontSize: "0.65rem",
letterSpacing: "0.1em",
marginTop: "0.3rem",
color: "var(--color-text-muted)",
}}
>
MAPA
</span>
</div>
)}
</div>
<span
style={{
display: "inline-block",
fontSize: "0.74rem",
fontWeight: 600,
letterSpacing: "0.22em",
color: "var(--color-gold-light)",
textTransform: "uppercase",
marginTop: "0.9rem",
transition: "color 0.2s ease",
}}
>
VER UBICACIÓN ↗
</span>
</a>
</div>
);
}
@@ -0,0 +1,166 @@
import { useEffect, useRef } from "react";
interface Particle {
x: number;
y: number;
radius: number;
baseOpacity: number;
blur: number;
goldR: number;
goldG: number;
goldB: number;
vx: number;
vy: number;
twinkleSpeed: number;
twinklePhase: number;
}
export function ParticleBackground() {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
let animationFrameId: number;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let width = canvas.width;
let height = canvas.height;
const prefersReducedMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)",
).matches;
const particleCount = width > 768 ? 120 : 80;
const particles: Particle[] = [];
function createParticle(): Particle {
const bias = Math.random();
let x = 0;
let y = 0;
if (bias < 0.4) {
// Upper-left quadrant
x = Math.random() * width * 0.55;
y = Math.random() * height * 0.45;
} else if (bias < 0.8) {
// Lower-right quadrant
x = width * 0.45 + Math.random() * width * 0.55;
y = height * 0.55 + Math.random() * height * 0.45;
} else {
// Sparse center
x = Math.random() * width;
y = Math.random() * height;
}
// Golden hues: amber, champagne, warm gold
const goldPalette = [
{ r: 212, g: 168, b: 67 }, // Classic gold #d4a843
{ r: 240, g: 214, b: 138 }, // Light gold #f0d68a
{ r: 255, g: 223, b: 140 }, // Bright champagne
{ r: 180, g: 140, b: 50 }, // Deep amber
];
const color = goldPalette[Math.floor(Math.random() * goldPalette.length)];
return {
x,
y,
radius: 1.5 + Math.random() * 5.5,
baseOpacity: 0.15 + Math.random() * 0.55,
blur: 2 + Math.random() * 8,
goldR: color.r,
goldG: color.g,
goldB: color.b,
vx: (Math.random() - 0.5) * 0.25,
vy: (Math.random() - 0.5) * 0.25,
twinkleSpeed: 0.006 + Math.random() * 0.018,
twinklePhase: Math.random() * Math.PI * 2,
};
}
for (let i = 0; i < particleCount; i++) {
particles.push(createParticle());
}
function renderFrame() {
if (!ctx) return;
ctx.clearRect(0, 0, width, height);
for (const p of particles) {
p.twinklePhase += p.twinkleSpeed;
const currentOpacity = Math.max(
0.05,
p.baseOpacity + Math.sin(p.twinklePhase) * 0.25,
);
ctx.save();
ctx.beginPath();
ctx.arc(p.x, p.y, p.radius, 0, Math.PI * 2);
// Soft bokeh glow
ctx.shadowBlur = p.blur;
ctx.shadowColor = `rgba(${p.goldR}, ${p.goldG}, ${p.goldB}, ${currentOpacity})`;
ctx.fillStyle = `rgba(${p.goldR}, ${p.goldG}, ${p.goldB}, ${currentOpacity})`;
ctx.fill();
ctx.restore();
if (!prefersReducedMotion) {
p.x += p.vx;
p.y += p.vy;
// Wrap edges
if (p.x < -10) p.x = width + 10;
if (p.x > width + 10) p.x = -10;
if (p.y < -10) p.y = height + 10;
if (p.y > height + 10) p.y = -10;
}
}
if (!prefersReducedMotion) {
animationFrameId = requestAnimationFrame(renderFrame);
}
}
// Initial render
renderFrame();
function handleResize() {
if (!canvas) return;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
width = canvas.width;
height = canvas.height;
if (prefersReducedMotion) {
renderFrame();
}
}
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
};
}, []);
return (
<canvas
ref={canvasRef}
style={{
position: "fixed",
top: 0,
left: 0,
width: "100%",
height: "100%",
pointerEvents: "none",
zIndex: 0,
}}
/>
);
}
+66
View File
@@ -0,0 +1,66 @@
interface RsvpCtaProps {
label: string;
onClick: () => void;
}
export function RsvpCta({ label, onClick }: RsvpCtaProps) {
return (
<button
type="button"
onClick={onClick}
style={{
display: "inline-flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
background: "none",
border: "none",
color: "var(--color-gold-light)",
cursor: "pointer",
padding: "0.8rem 1.4rem",
borderRadius: "8px",
outline: "none",
transition: "all 0.25s ease",
}}
onFocus={(e) => {
e.currentTarget.style.boxShadow = "0 0 0 2px var(--color-gold-border-focus)";
}}
onBlur={(e) => {
e.currentTarget.style.boxShadow = "none";
}}
aria-label={`${label} — Desplazarse al formulario de confirmación`}
>
<span
style={{
fontSize: "0.75rem",
fontWeight: 600,
letterSpacing: "0.26em",
textTransform: "uppercase",
marginBottom: "0.5rem",
transition: "letter-spacing 0.2s ease, color 0.2s ease",
}}
>
{label}
</span>
<span
style={{
fontSize: "1.2rem",
lineHeight: 1,
animation: "bounceSoft 2s infinite ease-in-out",
}}
aria-hidden="true"
>
↓
</span>
<style>{`
@keyframes bounceSoft {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(5px); }
}
@media (prefers-reduced-motion: reduce) {
span { animation: none !important; }
}
`}</style>
</button>
);
}
+149
View File
@@ -0,0 +1,149 @@
import type { FormEvent } from "react";
import { Button } from "../components/Button";
import { Field } from "../components/Field";
import { Spinner } from "../components/Spinner";
import type { FormErrors, RsvpFormState } from "../hooks/useRsvpForm";
import type { InvitationConfig } from "../types/config";
interface RsvpFormProps {
config: InvitationConfig;
name: string;
setName: (v: string) => void;
phone: string;
setPhone: (v: string) => void;
email: string;
setEmail: (v: string) => void;
formState: RsvpFormState;
errors: FormErrors;
onSubmit: () => void;
onShowDetails?: () => void;
}
export function RsvpForm({
config,
name,
setName,
phone,
setPhone,
email,
setEmail,
formState,
errors,
onSubmit,
onShowDetails,
}: RsvpFormProps) {
const isSubmitting = formState === "submitting";
function handleSubmit(e: FormEvent) {
e.preventDefault();
if (!isSubmitting) {
onSubmit();
}
}
return (
<form
onSubmit={handleSubmit}
style={{
width: "100%",
maxWidth: "400px",
margin: "0 auto",
padding: "1.5rem 0",
}}
noValidate
>
<h3
style={{
fontFamily: "var(--font-display)",
fontSize: "2.8rem",
fontWeight: 400,
color: "var(--color-gold-light)",
textAlign: "center",
marginBottom: "2rem",
textShadow: "0 2px 14px rgba(212, 168, 67, 0.3)",
}}
>
{config.rsvp_heading || "¿Nos vemos?"}
</h3>
<Field
label="Nombre Completo"
placeholder="Tu nombre y apellido"
value={name}
onChange={(e) => setName(e.target.value)}
disabled={isSubmitting}
error={errors.name}
required
/>
<Field
label="Teléfono (Móvil)"
placeholder="300 123 4567"
type="tel"
value={phone}
onChange={(e) => setPhone(e.target.value)}
disabled={isSubmitting}
hint="Número colombiano de 10 dígitos (ej: 300 123 4567)"
error={errors.phone}
required
/>
<Field
label="Correo Electrónico (Opcional)"
placeholder="ejemplo@correo.com"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={isSubmitting}
error={errors.email}
/>
<div style={{ marginTop: "2rem", textAlign: "center" }}>
<Button type="submit" variant="primary" fullWidth disabled={isSubmitting}>
{isSubmitting ? (
<span style={{ display: "inline-flex", alignItems: "center", gap: "0.6rem" }}>
<Spinner size={16} />
<span>ENVIANDO...</span>
</span>
) : (
config.submit_label || "TE VEO AHÍ"
)}
</Button>
{onShowDetails && (
<div style={{ marginTop: "1.4rem" }}>
<button
type="button"
onClick={onShowDetails}
style={{
background: "none",
border: "none",
color: "var(--color-gold)",
fontSize: "0.78rem",
letterSpacing: "0.14em",
textTransform: "uppercase",
cursor: "pointer",
padding: "0.4rem 0.8rem",
borderRadius: "4px",
textDecoration: "underline",
textUnderlineOffset: "4px",
opacity: 0.85,
transition: "opacity 0.2s ease, color 0.2s ease",
}}
onMouseEnter={(e) => {
e.currentTarget.style.opacity = "1";
e.currentTarget.style.color = "var(--color-gold-light)";
}}
onMouseLeave={(e) => {
e.currentTarget.style.opacity = "0.85";
e.currentTarget.style.color = "var(--color-gold)";
}}
>
¿Ya confirmaste? Ver ubicación y mapa ↓
</button>
</div>
)}
</div>
</form>
);
}
+355
View File
@@ -0,0 +1,355 @@
import { Button } from "../components/Button";
import { useCountdown } from "../hooks/useCountdown";
import type { RsvpFormState } from "../hooks/useRsvpForm";
import type { InvitationConfig } from "../types/config";
import { Countdown } from "./Countdown";
import { MapPreview } from "./MapPreview";
import { VenueInfo } from "./VenueInfo";
interface RsvpResultProps {
formState: RsvpFormState;
confirmedName: string;
config: InvitationConfig;
onRetry: () => void;
isDetailsOnly?: boolean;
onBackToForm?: () => void;
}
export function RsvpResult({
formState,
confirmedName,
config,
onRetry,
isDetailsOnly = false,
onBackToForm,
}: RsvpResultProps) {
const countdown = useCountdown(
config.event_date,
config.event_time,
config.event_timezone,
);
if (isDetailsOnly) {
return (
<div
style={{
width: "100%",
maxWidth: "440px",
margin: "0 auto",
padding: "1.5rem 1.5rem 3.5rem 1.5rem",
textAlign: "center",
}}
aria-live="polite"
>
<h3
style={{
fontFamily: "var(--font-display)",
fontSize: "clamp(2.8rem, 9vw, 3.6rem)",
fontWeight: 400,
color: "var(--color-gold-light)",
lineHeight: 1.15,
marginBottom: "0.4rem",
textShadow: "0 2px 20px rgba(212, 168, 67, 0.4)",
}}
>
Ubicación del Evento
</h3>
<p
style={{
fontSize: "0.85rem",
fontWeight: 600,
letterSpacing: "0.18em",
color: "var(--color-gold)",
textTransform: "uppercase",
marginBottom: "1.5rem",
}}
>
{config.address_name}
</p>
{/* Live Countdown */}
<Countdown
days={countdown.days}
hours={countdown.hours}
minutes={countdown.minutes}
seconds={countdown.seconds}
state={countdown.state}
label={config.countdown_label}
inProgressLabel={config.countdown_in_progress}
finishedLabel={config.countdown_finished}
/>
{/* Decorative divider dot */}
<div
style={{
display: "flex",
justifyContent: "center",
gap: "0.4rem",
margin: "1.5rem 0",
color: "var(--color-gold)",
opacity: 0.5,
fontSize: "1.2rem",
}}
aria-hidden="true"
>
<span>·</span>
<span>·</span>
<span>·</span>
</div>
{/* Circular Map Preview and Venue Logistics */}
<MapPreview
previewUrl={config.map_preview_url}
mapUrl={config.map_url}
venueName={config.address_name}
/>
<VenueInfo venueName={config.address_name} addressLines={config.address_lines} />
{onBackToForm && (
<div style={{ marginTop: "2.5rem" }}>
<Button
type="button"
variant="outline"
onClick={onBackToForm}
style={{ fontSize: "0.75rem", padding: "0.6rem 1.4rem" }}
>
« VOLVER AL FORMULARIO DE ASISTENCIA
</Button>
</div>
)}
</div>
);
}
if (formState === "duplicate") {
return (
<div
style={{
width: "100%",
maxWidth: "440px",
margin: "0 auto",
padding: "1.5rem 1.5rem 3.5rem 1.5rem",
textAlign: "center",
}}
role="alert"
>
<h3
style={{
fontFamily: "var(--font-display)",
fontSize: "clamp(2.8rem, 9vw, 3.6rem)",
fontWeight: 400,
color: "var(--color-gold-light)",
marginBottom: "0.8rem",
textShadow: "0 2px 14px rgba(212, 168, 67, 0.3)",
}}
>
¡Ya estás registrado!
</h3>
<p
style={{
fontSize: "0.92rem",
lineHeight: 1.7,
color: "var(--color-text-muted)",
marginBottom: "1.8rem",
}}
>
{config.msg_duplicate ||
"Parece que ya tenemos tus datos registrados. ¡Te esperamos!"}
</p>
{/* Live Countdown */}
<Countdown
days={countdown.days}
hours={countdown.hours}
minutes={countdown.minutes}
seconds={countdown.seconds}
state={countdown.state}
label={config.countdown_label}
inProgressLabel={config.countdown_in_progress}
finishedLabel={config.countdown_finished}
/>
{/* Circular Map Preview and Venue Logistics */}
<MapPreview
previewUrl={config.map_preview_url}
mapUrl={config.map_url}
venueName={config.address_name}
/>
<VenueInfo venueName={config.address_name} addressLines={config.address_lines} />
<div style={{ marginTop: "2rem" }}>
<Button
type="button"
variant="outline"
onClick={onRetry}
style={{ fontSize: "0.75rem", padding: "0.6rem 1.4rem" }}
>
VOLVER AL FORMULARIO
</Button>
</div>
</div>
);
}
if (formState === "error") {
return (
<div
style={{
width: "100%",
maxWidth: "420px",
margin: "0 auto",
padding: "2.5rem 1.5rem",
textAlign: "center",
}}
role="alert"
>
<h3
style={{
fontSize: "1.2rem",
fontWeight: 600,
letterSpacing: "0.15em",
color: "var(--color-error)",
marginBottom: "1rem",
textTransform: "uppercase",
}}
>
Algo salió mal
</h3>
<p
style={{
fontSize: "0.92rem",
lineHeight: 1.7,
color: "var(--color-text-muted)",
marginBottom: "2rem",
}}
>
{config.msg_error ||
"No pudimos registrar tu asistencia. Inténtalo nuevamente."}
</p>
<Button variant="primary" onClick={onRetry}>
INTENTAR DE NUEVO
</Button>
</div>
);
}
// Success Confirmation State
const greeting = (config.msg_success_greeting || "Gracias, {name}.").replace(
"{name}",
confirmedName || "",
);
return (
<div
style={{
width: "100%",
maxWidth: "440px",
margin: "0 auto",
padding: "2.5rem 1.5rem 4rem 1.5rem",
textAlign: "center",
}}
aria-live="polite"
>
<h3
style={{
fontFamily: "var(--font-display)",
fontSize: "clamp(3.2rem, 10vw, 4rem)",
fontWeight: 400,
color: "var(--color-gold-light)",
lineHeight: 1.15,
marginBottom: "0.8rem",
textShadow: "0 2px 20px rgba(212, 168, 67, 0.4)",
}}
>
¡Perfecto!
</h3>
<p
style={{
fontSize: "0.92rem",
fontWeight: 400,
letterSpacing: "0.12em",
color: "var(--color-text)",
lineHeight: 1.6,
marginBottom: "0.4rem",
}}
>
{config.msg_success || "Tu asistencia ha sido confirmada."}
</p>
{confirmedName && (
<p
style={{
fontSize: "1.05rem",
fontWeight: 600,
letterSpacing: "0.08em",
color: "var(--color-gold-light)",
marginBottom: "2rem",
}}
>
{greeting}
</p>
)}
{/* Decorative divider dot */}
<div
style={{
display: "flex",
justifyContent: "center",
gap: "0.4rem",
margin: "1.5rem 0",
color: "var(--color-gold)",
opacity: 0.5,
fontSize: "1.2rem",
}}
aria-hidden="true"
>
<span>·</span>
<span>·</span>
<span>·</span>
</div>
{/* Live Countdown */}
<Countdown
days={countdown.days}
hours={countdown.hours}
minutes={countdown.minutes}
seconds={countdown.seconds}
state={countdown.state}
label={config.countdown_label}
inProgressLabel={config.countdown_in_progress}
finishedLabel={config.countdown_finished}
/>
{/* Decorative divider dot */}
<div
style={{
display: "flex",
justifyContent: "center",
gap: "0.4rem",
margin: "1.5rem 0",
color: "var(--color-gold)",
opacity: 0.5,
fontSize: "1.2rem",
}}
aria-hidden="true"
>
<span>·</span>
<span>·</span>
<span>·</span>
</div>
{/* Circular Map Preview and Venue Logistics */}
<MapPreview
previewUrl={config.map_preview_url}
mapUrl={config.map_url}
venueName={config.address_name}
/>
<VenueInfo venueName={config.address_name} addressLines={config.address_lines} />
</div>
);
}
+41
View File
@@ -0,0 +1,41 @@
interface VenueInfoProps {
venueName: string;
addressLines: string;
}
export function VenueInfo({ venueName, addressLines }: VenueInfoProps) {
const lines = addressLines
? addressLines.split("\n").filter((line) => line.trim().length > 0)
: [];
return (
<div style={{ textAlign: "center", margin: "1rem 0" }}>
<h3
style={{
fontSize: "0.95rem",
fontWeight: 600,
letterSpacing: "0.18em",
textTransform: "uppercase",
color: "var(--color-text)",
marginBottom: "0.4rem",
}}
>
{venueName}
</h3>
{lines.map((line) => (
<p
key={line}
style={{
fontSize: "0.82rem",
color: "var(--color-text-muted)",
letterSpacing: "0.12em",
textTransform: "uppercase",
lineHeight: 1.5,
}}
>
{line}
</p>
))}
</div>
);
}
+13
View File
@@ -0,0 +1,13 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { App } from "./App";
import "./styles/global.css";
const rootElement = document.getElementById("root");
if (rootElement) {
ReactDOM.createRoot(rootElement).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
}
+77
View File
@@ -0,0 +1,77 @@
/* Self-hosted fonts */
@font-face {
font-family: "InviteDisplay";
src: url("/birthday/fonts/display.woff2") format("woff2");
font-weight: 400;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "Montserrat";
src: url("/birthday/fonts/montserrat/montserrat-latin.woff2") format("woff2");
font-weight: 300 700;
font-style: normal;
font-display: swap;
}
:root {
--color-bg: #0a0a0a;
--color-card-bg: #121212;
--color-gold: #d4a843;
--color-gold-light: #f0d68a;
--color-gold-dark: #8b7332;
--color-gold-border: rgba(212, 168, 67, 0.25);
--color-gold-border-focus: rgba(212, 168, 67, 0.65);
--color-text: #ffffff;
--color-text-muted: rgba(255, 255, 255, 0.72);
--color-text-dim: rgba(255, 255, 255, 0.45);
--color-error: #e74c3c;
--color-error-bg: rgba(231, 76, 60, 0.12);
--font-display: "InviteDisplay", cursive, "Great Vibes", serif;
--font-body: "Montserrat", -apple-system, BlinkMacSystemFont, sans-serif;
--max-content-width: 480px;
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
font-family: var(--font-body);
background-color: var(--color-bg);
color: var(--color-text);
scroll-behavior: smooth;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
}
body {
min-height: 100vh;
background-color: var(--color-bg);
color: var(--color-text);
overflow-x: hidden;
position: relative;
}
button {
font-family: inherit;
cursor: pointer;
}
input,
textarea {
font-family: inherit;
}
+57
View File
@@ -0,0 +1,57 @@
export interface InvitationConfig {
id: number;
title: string;
invitation_text: string;
honoree_name: string;
event_date: string; // "YYYY-MM-DD"
event_time: string; // "HH:MM"
event_timezone: string; // "America/Bogota"
address_name: string;
address_lines: string;
map_preview_url: string;
map_url: string;
rsvp_heading: string;
rsvp_cta: string;
submit_label: string;
msg_success: string;
msg_success_greeting: string;
msg_duplicate: string;
msg_error: string;
msg_config_error: string;
countdown_label: string;
countdown_in_progress: string;
countdown_finished: string;
updated_at?: string;
}
export interface RSVPRequest {
name: string;
phone: string;
email?: string | null;
}
export interface RSVPUpdateRequest {
name?: string;
phone?: string;
email?: string | null;
}
export type RSVPApiResult =
| { result: "SUCCESS"; name: string }
| { result: "DUPLICATE" }
| { result: "VALIDATION_ERROR"; errors: Record<string, string> }
| { result: "ERROR" };
export interface RSVPAdminItem {
id: number;
name: string;
phone: string;
email: string | null;
created_at: string;
}
export interface RSVPListResponse {
count: number;
rsvps: RSVPAdminItem[];
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": false,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": false,
"isolatedModules": true,
"noEmit": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
+37
View File
@@ -0,0 +1,37 @@
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [
react(),
{
name: "trailing-slash-redirect",
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (req.url === "/birthday") {
res.writeHead(301, { Location: "/birthday/" });
res.end();
return;
}
next();
});
},
},
],
base: "/birthday/",
build: {
outDir: "dist",
assetsDir: "assets",
},
server: {
proxy: {
"/birthday/api": {
target: "http://localhost:8000",
changeOrigin: true,
headers: {
"Remote-User": "kiskaadee", // mock Authelia ForwardAuth locally
},
},
},
},
});
+19
View File
@@ -0,0 +1,19 @@
{ pkgs ? import <nixpkgs> {} }:
pkgs.mkShell {
name = "bdinvite-dev";
buildInputs = with pkgs; [
nodejs
biome
uv
python311
];
shellHook = ''
echo "🎂 bdinvite development shell loaded"
echo " Node: $(node --version 2>/dev/null || echo 'not found')"
echo " Biome: $(biome --version 2>/dev/null || echo 'not found')"
echo " uv: $(uv --version 2>/dev/null || echo 'not found')"
'';
}
+466
View File
@@ -0,0 +1,466 @@
# Digital Invitation — Backend Specification
> **Status:** Frozen · **Version:** 1.0 · **Date:** 2026-10-01
---
## 1. Purpose
This document is the authoritative backend specification for **bdinvite** — an interactive digital birthday invitation with RSVP functionality. Implementation follows this spec. All API contracts, data models, authentication boundaries, and runtime behaviors described herein are normative.
---
## 2. Architecture
| Concern | Technology |
|---|---|
| Application Framework | FastAPI with Uvicorn |
| Runtime | Python 3.11+ |
| Database | SQLite with WAL mode |
| ORM | SQLAlchemy 2.0 |
| Validation & Settings | Pydantic v2 / pydantic-settings |
| Dependency Management | uv |
| Base Image | `ghcr.io/astral-sh/uv:python3.11-bookworm-slim` |
The application runs as a **single container**. FastAPI serves both the API routes and the built React SPA as static files. There is no separate web server, no reverse-proxy sidecar, and no background worker process within the container.
```mermaid
flowchart LR
subgraph Container
FastAPI["FastAPI + Uvicorn"]
SQLite["SQLite (WAL)"]
SPA["React SPA (static)"]
FastAPI --> SQLite
FastAPI --> SPA
end
Client["Browser"] --> FastAPI
```
---
## 3. Directory Structure
```
backend/
├── pyproject.toml
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI app, lifespan, static file mount, SPA catch-all
│ ├── config.py # Pydantic Settings (env-based)
│ ├── database.py # SQLite WAL engine, session factory, Base
│ ├── models.py # SQLAlchemy models
│ ├── schemas.py # Pydantic request/response schemas
│ ├── routes/
│ │ ├── __init__.py
│ │ ├── rsvp.py # POST /birthday/api/rsvp
│ │ ├── config.py # GET /birthday/api/config
│ │ └── admin.py # Admin endpoints
│ └── services/
│ ├── __init__.py
│ ├── rsvp.py # RSVP business logic + phone normalization
│ └── config.py # Config CRUD + seed defaults
└── tests/
├── __init__.py
├── test_rsvp.py
└── test_config.py
```
---
## 4. Database
### 4.1 Engine Configuration
- **Database file:** `/app/data/bdinvite.db`
- **Volume mount:** `./data:/app/data`
- **Connection string:** `sqlite:///./data/bdinvite.db`
- **WAL mode:** Enabled at engine creation via `PRAGMA journal_mode=WAL;`
- **Threading:** `check_same_thread=False` (required for SQLite with FastAPI's async/threaded model)
- **Table creation:** `metadata.create_all()` runs on application startup via FastAPI's lifespan handler
### 4.2 RSVP Table (`rsvps`)
| Column | Type | Constraints |
|---|---|---|
| `id` | INTEGER | PRIMARY KEY, autoincrement |
| `name` | TEXT | NOT NULL |
| `phone` | TEXT | NOT NULL, UNIQUE |
| `email` | TEXT | nullable |
| `created_at` | DATETIME | NOT NULL, default = `utcnow` |
The `phone` column stores the **normalized 10-digit Colombian number** (digits only, no country code). The `UNIQUE` constraint on `phone` enforces duplicate detection at the storage level.
### 4.3 InvitationConfig Table (`invitation_config`)
This table holds exactly **one row** (`id = 1`). The row is seeded with defaults on first startup if no row exists.
| Column | Type | Default |
|---|---|---|
| `id` | INTEGER | PRIMARY KEY (always `1`) |
| `title` | TEXT | `"Birthday Party"` |
| `invitation_text` | TEXT | `"You're invited to the birthday party honoring"` |
| `honoree_name` | TEXT | `"Isabelle Snow"` |
| `event_date` | TEXT | `"2026-10-28"` (ISO 8601 date) |
| `event_time` | TEXT | `"19:00"` (HH:MM, 24-hour) |
| `event_timezone` | TEXT | `"America/Bogota"` (IANA timezone identifier) |
| `address_name` | TEXT | `"Fresco Ristorante"` |
| `address_lines` | TEXT | `"514 S Brand Blvd\nGlendale, CA 91204"` (newline-separated) |
| `map_preview_url` | TEXT | URL to static map preview image |
| `map_url` | TEXT | Google Maps (or other map service) link |
| `rsvp_heading` | TEXT | `"¿Nos vemos?"` |
| `rsvp_cta` | TEXT | `"CONFIRMA TU ASISTENCIA"` |
| `submit_label` | TEXT | `"TE VEO AHÍ"` |
| `msg_success` | TEXT | `"¡Perfecto! Tu asistencia ha sido confirmada."` |
| `msg_success_greeting` | TEXT | `"Gracias, {name}."` (`{name}` is replaced client-side) |
| `msg_duplicate` | TEXT | `"Parece que ya tenemos tus datos registrados."` |
| `msg_error` | TEXT | `"No pudimos registrar tu asistencia. Inténtalo nuevamente."` |
| `msg_config_error` | TEXT | `"No pudimos cargar la invitación. Inténtalo nuevamente."` |
| `countdown_label` | TEXT | `"NOS VEMOS EN"` |
| `countdown_in_progress` | TEXT | `"EVENTO EN CURSO"` |
| `countdown_finished` | TEXT | `"EVENTO FINALIZADO"` |
| `updated_at` | DATETIME | UTC |
---
## 5. API Contract
All API routes are mounted under `/birthday/api/`. Admin routes are mounted under `/birthday/api/admin/`.
```mermaid
flowchart LR
subgraph Public
A["GET /birthday/api/config"]
B["POST /birthday/api/rsvp"]
G["GET /birthday/api/map-preview.png"]
end
subgraph Admin["Admin (Remote-User required)"]
C["GET /birthday/api/admin/rsvps"]
D["GET /birthday/api/admin/export"]
E["GET /birthday/api/admin/config"]
F["PUT /birthday/api/admin/config"]
H["POST /birthday/api/admin/map-preview/generate"]
end
```
### 5.1 Public Endpoints
#### `GET /birthday/api/config`
Serves the invitation configuration to the guest frontend.
- **Auth:** None (public)
- **Response `200`:** Full `InvitationConfig` object — all fields from the config table.
- **Response `500`:** `{"result": "ERROR"}` (if no config row exists — should not happen after seeding)
#### `GET /birthday/api/map-preview.png`
Serves the locally generated OpenStreetMap static crop image centered on the event venue.
- **Auth:** None (public)
- **Response `200`:** `image/png` static file with caching headers (`Cache-Control: public, max-age=300`).
- **Fallback:** 307 Redirect to default OSM tile if the image file has not yet been generated.
#### `POST /birthday/api/rsvp`
Submit an RSVP.
- **Auth:** None (public)
**Request body:**
```json
{
"name": "Andrés García",
"phone": "300 123 4567",
"email": "andres@example.com"
}
```
**Field validation:**
| Field | Required | Rules |
|---|---|---|
| `name` | Yes | Non-empty, max 100 characters, whitespace-normalized |
| `phone` | Yes | Validated as Colombian format (see §7 Phone Normalization) |
| `email` | No | Validated as email format if provided |
**Responses:**
- **`201` — Success:**
```json
{ "result": "SUCCESS", "name": "Andrés García" }
```
- **`409` — Duplicate phone:**
```json
{ "result": "DUPLICATE" }
```
- **`422` — Validation error:**
```json
{ "result": "VALIDATION_ERROR", "errors": { "phone": "Formato de teléfono inválido" } }
```
- **`500` — Server error:**
```json
{ "result": "ERROR" }
```
The `result` field is a string discriminator. The frontend switches on this value.
### 5.2 Admin Endpoints
All admin endpoints require the `Remote-User` header (injected by Authelia ForwardAuth). A missing header produces a `401` response.
#### `GET /birthday/api/admin/rsvps`
List all RSVPs.
- **Query params:** `?search=<term>` (optional) — filters by name, phone, or email substring match
- **Response `200`:**
```json
{
"count": 37,
"rsvps": [
{
"id": 1,
"name": "Ana García",
"phone": "3001234567",
"email": "ana@example.com",
"created_at": "2026-09-30T12:00:00Z"
}
]
}
```
#### `GET /birthday/api/admin/export`
Download all RSVPs as CSV.
- **Response:** `text/csv` with `Content-Disposition: attachment; filename="rsvps.csv"`
- **Columns:** `name`, `phone`, `email`, `created_at`
- **`created_at` format:** ISO 8601 UTC
#### `GET /birthday/api/admin/config`
Get full configuration. Same shape as the public `GET /birthday/api/config`.
#### `PUT /birthday/api/admin/config`
Update configuration (full object replacement).
- **Request body:** Full config object (Pydantic-validated)
- **Response `200`:** Updated config object
- **Validation rules:**
- `event_date` is a valid ISO 8601 date
- `event_time` is a valid `HH:MM` (24-hour) string
- `event_timezone` is a valid IANA timezone identifier
- `map_url` is a valid Google Maps URL format (`maps.app.goo.gl`, `goo.gl`, or `google.com/maps`)
- Text fields are non-empty where required
- **Conditional Map Regeneration:**
- If `map_url` changed compared to the stored singleton, the backend automatically resolves destination coordinates, generates a fresh OpenStreetMap stitched preview PNG on disk, and points `map_preview_url` to `/birthday/api/map-preview.png`.
- If `map_url` did not change, no external network calls or image generation occur.
#### `POST /birthday/api/admin/map-preview/generate`
Regenerates the venue map preview image on disk without requiring full configuration updates or database writes.
- **Request body:** Optional JSON `{"map_url": "..."}`. If omitted, uses the currently persisted `map_url`.
- **Response `200`:**
```json
{
"map_preview_url": "/birthday/api/map-preview.png?t=1759338600",
"lat": 34.1432,
"lng": -118.2551,
"message": "Vista previa del mapa generada con éxito."
}
```
- **Error `422`:** If the provided URL cannot be parsed into valid geographic coordinates.
- **Side Effect:** Writes `data/map_preview.png` directly to disk, cache-busting via the returned timestamp.
---
## 6. Error Handling
The backend never exposes raw exceptions, SQL errors, or stack traces to the client. A global exception handler catches unhandled exceptions and returns the generic `ERROR` response.
| Scenario | HTTP Status | Response Body |
|---|---|---|
| Successful RSVP | `201` | `{"result": "SUCCESS", "name": "..."}` |
| Duplicate phone | `409` | `{"result": "DUPLICATE"}` |
| Validation failure | `422` | `{"result": "VALIDATION_ERROR", "errors": {...}}` |
| Unexpected error | `500` | `{"result": "ERROR"}` |
| Unauthenticated admin | `401` | `{"detail": "Not authenticated"}` |
---
## 7. Phone Normalization
All phone numbers are normalized to **10-digit Colombian mobile format** before storage and uniqueness checks.
**Algorithm:**
1. Strip all non-digit characters (spaces, dashes, parentheses, plus sign).
2. If the resulting digit string starts with `"57"` **and** has exactly 12 digits, remove the `"57"` prefix (country code).
3. The result must be exactly **10 digits** AND start with `"3"`.
4. If either condition fails: return validation error with message `"Formato de teléfono inválido"`.
**Examples:**
| Input | Normalized | Valid |
|---|---|---|
| `"+57 300 123 4567"` | `3001234567` | ✓ |
| `"300-123-4567"` | `3001234567` | ✓ |
| `"3001234567"` | `3001234567` | ✓ |
| `"(300) 123 4567"` | `3001234567` | ✓ |
| `"57300123 4567"` | `3001234567` | ✓ |
| `"123456"` | — | ✗ (not 10 digits) |
| `"1234567890"` | — | ✗ (doesn't start with `3`) |
| `"+1 555 123 4567"` | — | ✗ (not Colombian format) |
---
## 8. Duplicate Detection
A submission is a duplicate if the **normalized phone number** matches an existing RSVP record. Phone is the unique identifier because:
- Phone is **required** — every RSVP has one.
- Email is **optional** — cannot be relied on for deduplication.
- Name alone is **insufficient** — common names exist.
The `UNIQUE` constraint on the `phone` column enforces this at the storage level. The service layer catches the `IntegrityError` from SQLAlchemy and returns the `DUPLICATE` result.
---
## 9. Config Management
- The invitation configuration is a **singleton row** (`id = 1`) in the `invitation_config` table.
- On application startup (FastAPI lifespan), if no config row exists, seed it with defaults.
- `GET /birthday/api/config` returns the current config for the guest frontend.
- `PUT /birthday/api/admin/config` replaces the config (full object replacement, Pydantic-validated).
- The frontend fetches config on page load and renders the invitation from it.
- Changes via the admin dashboard take effect **immediately** — no cache, no restart required.
---
## 10. Admin Authentication
There is **no** app-level login page, JWT, session management, or password handling.
Authentication is delegated entirely to **Authelia** at the Traefik reverse proxy level:
1. Authelia's ForwardAuth middleware intercepts requests to `/birthday/admin/*`.
2. After successful authentication, Authelia injects headers: `Remote-User`, `Remote-Email`, `Remote-Groups`, `Remote-Name`.
3. The backend reads and verifies these headers on every admin request.
> **Security Invariant:** Every admin API endpoint independently verifies the `Remote-User` header. No admin endpoint relies on React routing, URL obscurity, or browser-side authorization for security.
**Implementation:**
```python
from fastapi import Depends, Header, HTTPException
def require_admin(remote_user: str | None = Header(None, alias="Remote-User")):
if not remote_user:
raise HTTPException(status_code=401, detail="Not authenticated")
return remote_user
# Usage: every admin route depends on this
@router.get("/rsvps")
def list_rsvps(admin: str = Depends(require_admin), db: Session = Depends(get_db)):
...
```
---
## 11. Timestamp Policy
Two distinct timestamp domains exist in this application:
### 11.1 Persistence Timestamps
`created_at` and `updated_at` are **always UTC**. Stored as UTC in the database. The backend uses `datetime.utcnow()` or equivalent. The frontend/admin converts to display timezone as needed.
### 11.2 Event Date/Time
`event_date`, `event_time`, and `event_timezone` are stored as **separate fields** representing a locale-specific instant:
| Field | Format | Example |
|---|---|---|
| `event_date` | ISO 8601 date | `"2026-10-28"` |
| `event_time` | HH:MM (24-hour) | `"19:00"` |
| `event_timezone` | IANA timezone | `"America/Bogota"` |
The frontend constructs a timezone-aware instant from these three fields for countdown calculation.
These are **separate concerns**. Persistence timestamps are infrastructure; event time is business data.
---
## 12. SPA Serving
FastAPI serves the built React application. **Registration order matters:**
1. API routes are registered first (prefix `/birthday/api/` and `/birthday/api/admin/`).
2. Static assets are mounted at `/birthday/assets/` (Vite build output directory).
3. A catch-all route serves `static/index.html` for any `/birthday/{path}` not matching API or asset routes.
This enables React Router client-side routing under `/birthday/`.
```python
# Order matters:
app.include_router(rsvp_router, prefix="/birthday/api")
app.include_router(config_router, prefix="/birthday/api")
app.include_router(admin_router, prefix="/birthday/api/admin")
app.mount("/birthday/assets", StaticFiles(directory="static/assets"), name="assets")
@app.get("/birthday/{full_path:path}")
async def spa_catch_all(full_path: str):
return FileResponse("static/index.html")
```
---
## 13. Application Settings
Environment-based configuration via Pydantic Settings. Values are overridable via environment variables or a `.env` file.
```python
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
SERVICE_NAME: str = "bdinvite"
SERVICE_DOMAIN: str = "demos.roadtotech.me"
BASE_PATH: str = "/birthday"
APP_PORT: int = 8000
DATABASE_URL: str = "sqlite:///./data/bdinvite.db"
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
```
---
## 14. Dependencies
```toml
[project]
name = "bdinvite"
version = "0.1.0"
description = "Birthday Invitation RSVP Backend"
requires-python = ">=3.11"
dependencies = [
"fastapi>=0.115.0",
"uvicorn>=0.30.0",
"sqlalchemy>=2.0.0",
"pydantic>=2.0.0",
"pydantic-settings>=2.0.0",
]
[dependency-groups]
dev = [
"httpx>=0.27.0",
"pytest>=8.0.0",
"pytest-asyncio>=0.23.0",
]
```
+448
View File
@@ -0,0 +1,448 @@
# Digital Invitation — Frontend Specification
## 1. Purpose
A responsive, mobile-first digital birthday invitation that reproduces the visual character of a physical invitation while adding an interactive RSVP flow.
The application has two distinct experiences:
### Guest Experience
A highly designed invitation served publicly at `/birthday/`, consisting of:
1. **Invitation hero**: Fixed-aspect-ratio vertical composition with animated golden bokeh particles, title, honoree, date/time, and RSVP call-to-action
2. **RSVP form**: Name, phone, and optional email fields matching the invitation's visual world
3. **Submission feedback**: Explicit semantic feedback (Success, Duplicate, Error)
4. **Event reminder & logistics**: Countdown timer to the event, circular map preview, venue details, and navigation link
### Admin Experience
A simple dashboard served at `/birthday/admin` (Authelia-protected) allowing the event organizer to:
1. View invitee responses in a searchable table
2. Monitor response count
3. Export responses as CSV
4. Edit invitation copy and event logistics via a form with live text preview
The guest experience is the primary design focus. The admin dashboard deliberately does **not** use the invitation's visual effects.
---
## 2. Design Principles
### 2.1 The Invitation is a Physical Object (Section-Based Composition)
The invitation hero maintains a fixed vertical aspect ratio (9:16) regardless of viewport width. The browser provides a responsive **stage** around it on wider screens.
The page itself is a scrollable viewport composed of discrete sections:
```text
PAGE (Scrollable Viewport)
│
├── Invitation Hero Section (Fixed vertical aspect ratio, desktop stage)
│
├── RSVP Section (Revealed via CTA click, matching visual world)
│
└── Confirmation Section (Replaces RSVP on success; countdown + logistics)
```
The invitation hero itself is **not** an overflow-scrolling container. The page scrolls smoothly across these visual sections, maintaining balanced compositions within each viewport.
```text
Desktop Stage
┌────────────────────────────────────────────┐
│ │
│ ┌──────────────────┐ │
│ │ │ │
│ │ INVITATION │ (9:16 card) │
│ │ HERO │ │
│ │ │ │
│ └──────────────────┘ │
│ │
└────────────────────────────────────────────┘
```
On mobile, the section expands to occupy the available width while preserving vertical proportions.
---
### 2.2 One Visual Composition
There are not separate mobile and desktop invitation designs. The visual card scales responsively within the viewport. Desktop provides surrounding staging; mobile provides full viewport width to the invitation.
---
### 2.3 Decoration Must Not Interfere with Information
The animated particle background is subordinate to content:
- Particles concentrate toward upper-left and lower-right corners
- The central content area remains substantially darker and sparse
- Movement is extremely slow (ambient life, not spectacle)
- Particles vary in radius, opacity, and soft golden blur
- Never compromises text readability
---
### 2.4 The RSVP Interaction is Part of the Invitation
The RSVP form and confirmation states inherit the invitation's visual identity:
- Dark background (`#0a0a0a`)
- Golden accents (`#d4a843`, `#f0d68a`)
- Typography system
- Ambient particle canvas spanning the entire page behind all sections
---
### 2.5 Content is Configuration, Not Code
Event-specific copy is never hardcoded in presentation components:
- Fetched on load from `GET /birthday/api/config`
- Admin can modify event details dynamically without rebuilding the frontend
---
### 2.6 Explicit Configuration Loading & Error States
Before rendering the invitation, the frontend manages configuration lifecycle explicitly:
```text
CONFIG_LOADING
│
├── success ──────→ INVITATION
│
└── failure/error ─→ CONFIG_ERROR
```
If the API fails to load or returns invalid data:
- Renders a graceful fallback:
> **No pudimos cargar la invitación.**
> Inténtalo nuevamente.
- Includes a retry button
- Never exposes broken components or undefined text values to the guest
---
### 2.7 Typography System (Self-Hosted)
The design contrasts an organic handwritten script with a clean geometric sans-serif:
- **Display Script**: Configurable script font (candidates: Great Vibes, Alex Brush, Sacramento, Allison, Whisper) used for "Birthday Party" and the honoree name
- **Body & Metadata**: Montserrat (weights 300, 400, 500, 600, 700) with generous letter-spacing for dates, labels, and copy
- **Self-Hosted Invariant**: All web fonts are bundled and served from `/birthday/fonts/` (WOFF2 format) to ensure deterministic rendering and zero third-party CDN dependencies
---
## 3. Guest Experience Lifecycle
```text
PAGE LOAD
│
▼
CONFIG_LOADING
│ │
fail │ │ success
▼ ▼
CONFIG_ERROR INVITATION HERO
│
CTA click (smooth scroll)
│
▼
RSVP FORM
│
submit
│
▼
SUBMITTING
│
┌───────────────┼───────────────┐
│ │ │
▼ ▼ ▼
SUCCESS DUPLICATE ERROR
│ │ │
▼ ▼ ▼
CONFIRMATION "¡UPS!" "ALGO SALIÓ
& COUNTDOWN (duplicate) MAL"
│ │
▼ ▼
MAP & LOGISTICS (retry)
```
---
## 4. State 1 — Invitation Hero
Displays the invitation cover in a centered 9:16 stage:
```text
┌─────────────────────────────┐
│ │
│ Birthday Party │ ← Display Script
│ │
│ YOU'RE INVITED TO THE │ ← Montserrat, tracked
│ BIRTHDAY PARTY HONORING │
│ │
│ Isabelle Snow │ ← Display Script
│ │
│ OCT 7:00 PM │ ← Montserrat, 500
│ 28 FRIDAY │
│ │
│ │
│ CONFIRMA TU ASISTENCIA │ ← CTA Button
│ ↓ │
│ │
└─────────────────────────────┘
```
The address is intentionally omitted from the hero to focus attention on the RSVP action.
---
## 5. RSVP Call-To-Action (CTA)
Default copy:
> **CONFIRMA TU ASISTENCIA**
> ↓
Interaction:
- Click or keyboard activation smoothly scrolls the viewport to the RSVP section
- Focus is moved to the first input field
- Fully keyboard accessible (`<button>` with visible `:focus-visible` gold ring)
- Supports `prefers-reduced-motion` (instant jump instead of smooth scroll)
---
## 6. State 2 — RSVP Form
Appears below the invitation hero section:
```text
┌─────────────────────────────┐
│ │
│ ¿NOS VEMOS? │
│ │
│ NOMBRE COMPLETO │
│ [_______________________] │
│ │
│ TELÉFONO (MÓVIL) │
│ [_______________________] │
│ │
│ CORREO · OPCIONAL │
│ [_______________________] │
│ │
│ TE VEO AHÍ │
│ │
└─────────────────────────────┘
```
### Form Fields & Validation
1. **Full Name (`name`)**:
- Required, trimmed, max 100 characters
- Inline error: *"Por favor, ingresa tu nombre completo."*
2. **Phone Number (`phone`)**:
- Required
- Validated against Colombian mobile format: 10 digits starting with `3` (e.g. `300 123 4567` or `+57 300 123 4567`)
- Normalization removes non-digits and leading `57` country code before submission
- Inline error: *"Ingresa un número móvil válido (10 dígitos)."*
3. **Email (`email`)**:
- Optional
- If provided, validated against standard email format
- Inline error: *"Ingresa un correo electrónico válido."*
4. **Submit Button (`submit_label`)**:
- Default: *"TE VEO AHÍ"* (configurable)
- Disables during submission to prevent double submits
---
## 7. Submission State
When submitted:
1. Inputs are disabled
2. Submit button shows loading spinner or text: *"ENVIANDO..."*
3. Form dispatches `POST /birthday/api/rsvp`
4. Evaluates the semantic response discriminator
---
## 8. State 3 — Submission Responses
### 8.1 Successful Submission & Confirmation
When backend returns `{ "result": "SUCCESS", "name": "..." }`:
- Viewport smoothly transitions into the **Confirmation Section**
- Saves a session marker in browser storage:
```ts
sessionStorage.setItem('bdinvite:rsvp-submitted', JSON.stringify({
name: data.name,
timestamp: Date.now()
}));
```
- If the guest refreshes the page during the session, the confirmation section is displayed immediately, avoiding duplicate prompt friction.
#### Visual Hierarchy & Layout:
```text
┌─────────────────────────────┐
│ │
│ │
│ ¡PERFECTO! │
│ │
│ Tu asistencia ha sido │
│ confirmada. │
│ │
│ Gracias, Andrés. │
│ │
│ · │
│ · │
│ NOS VEMOS EN │
│ 12 : 04 : 37 : 22 │
│ │
│ · │
│ │
│ ╭──────╮ │
│ ╭─┤ ├─╮ │
│ │ │ MAP │ │ │
│ ╰─┤ ├─╯ │
│ ╰──────╯ │
│ │
│ FRESCO RISTORANTE │
│ 514 S Brand Blvd │
│ Glendale, CA 91204 │
│ │
│ VER UBICACIÓN ↗ │
│ │
└─────────────────────────────┘
```
---
## 9. Countdown Component
The countdown calculates remaining time against the event's **absolute instant** using its configured IANA timezone (`America/Bogota`):
```ts
interface EventTimeConfig {
event_date: string; // "2026-10-28"
event_time: string; // "19:00"
event_timezone: string; // "America/Bogota"
}
```
The countdown does **not** assume hardcoded UTC offsets. It computes the target instant in UTC using browser timezone utilities (`Intl.DateTimeFormat`):
```text
targetInstant = parseInTimezone(event_date, event_time, event_timezone)
remainingMs = targetInstant - Date.now()
```
### Countdown Display States:
1. **Before Event** (`remainingMs > 0`):
```text
NOS VEMOS EN
12 : 04 : 37 : 22
(Días : Horas : Min : Seg)
```
2. **Event Day / In Progress** (within event duration window):
```text
EVENTO EN CURSO
```
3. **Event Concluded**:
```text
EVENTO FINALIZADO
```
---
## 10. Map Preview & Location Details
The map is rendered as a clean, circular preview widget linked to the external navigation destination:
- **Treatment**: Circular crop (~140px diameter), subtle golden border `1px solid rgba(212, 168, 67, 0.3)`
- **Hover/Active**: Scales smoothly (`transform: scale(1.05)`), border brightens
- **Venue Copy**: Clean text block listing venue name and address
- **External Link**: Text link `VER UBICACIÓN ↗` opening `map_url` in a new tab (`target="_blank" rel="noopener noreferrer"`)
- **Asset**: Uses `map_preview_url` (v1 configurable URL, architected for future self-hosted static asset)
---
## 11. Duplicate Submission State
When backend returns `{ "result": "DUPLICATE" }`:
- Form presents the duplicate feedback message:
> **¡UPS!**
> Parece que ya tenemos tus datos registrados.
> Si necesitas modificar tu información, ponte en contacto con nosotros.
- Does not expose existing database records or personal details
- Offers a button to return to the invitation or edit fields
---
## 12. Unexpected Error & Network Failure
When backend returns `{ "result": "ERROR" }` or fetch throws a network exception:
- Message:
> **ALGO SALIÓ MAL**
> No pudimos registrar tu asistencia. Inténtalo nuevamente.
- Button: **INTENTAR DE NUEVO**
- Preserves user input values so the user does not have to retype their details
---
## 13. Particle Background Engine
Implemented on an HTML5 `<canvas>` element:
- Positioned fixed behind all page sections (`z-index: 0`, `pointer-events: none`)
- Canvas dimensions dynamically track `window.innerWidth` and `window.innerHeight`
### Particle Attributes
```ts
interface Particle {
x: number;
y: number;
radius: number; // 2px - 10px
opacity: number; // 0.15 - 0.7
blur: number; // 2px - 12px
goldHue: number; // Warm gold to soft amber
vx: number; // -0.15 to +0.15 px/frame
vy: number; // -0.15 to +0.15 px/frame
twinkleSpeed: number; // 0.005 - 0.02
twinklePhase: number; // 0 to 2π
}
```
### Spatial Distribution
- Weighted random distribution:
- 40% probability: Upper-left quadrant
- 40% probability: Lower-right quadrant
- 20% probability: Uniformly sparse across center
- Particle density: ~120 on viewport > 768px; ~80 on mobile viewports
### Accessibility / Reduced Motion
- If `@media (prefers-reduced-motion: reduce)` is detected:
- Renders a single static frame of particles
- Animation loop is halted immediately
- Smooth scroll behavior reverts to immediate jump
---
## 14. Admin Experience
Served under route `/birthday/admin` and protected at the reverse-proxy level by Authelia ForwardAuth.
### 14.1 RSVP Table View
- **Total Count**: Live tally of confirmed invitees
- **Search Bar**: Substring filtering by name, phone, or email
- **Table Columns**:
- Name
- Phone (formatted Colombian mobile)
- Email (or em-dash if omitted)
- Submission Date/Time (converted from UTC to browser-local)
- **CSV Export**: *"Descargar CSV"* button triggering `GET /birthday/api/admin/export`
### 14.2 Configuration Editor
A flat form allowing the host to edit dynamic invitation data:
- Honoree Name
- Event Date, Event Time, Event Timezone
- Invitation Title & Intro Copy
- Venue Name & Address Lines
- Map Preview URL & External Map URL
- RSVP Button Copy & Feedback Messages
Includes a **Text Preview** block showing the hierarchical composition of the text fields before saving.
---
## 15. Routing & URL Structure
The application operates with base path `/birthday/` via React Router:
- `/birthday/` → Guest experience (Invitation hero, RSVP flow, Confirmation)
- `/birthday/admin` → Admin dashboard (RSVP table, CSV export)
- `/birthday/admin/config` → Invitation configuration editor
- `*` → Redirects to `/birthday/`
+369
View File
@@ -0,0 +1,369 @@
# Digital Invitation — Infrastructure Specification
> **Status**: Frozen · **Workload**: `bdinvite` · **Host**: `roadtotech.me` (NixOS homelab)
---
## 1. Platform Context
The application runs on the `roadtotech.me` homelab appliance — a NixOS server providing:
| Component | Role |
|---|---|
| **Traefik v3.6** | Reverse proxy with wildcard DNS/TLS for `*.roadtotech.me` (ACME DNS-01 via Dynu) |
| **Authelia** | SSO with LLDAP backend; session cookies valid across `*.roadtotech.me` |
| **`appctl`** | Orchestration tool for Sites workloads (reads `app.yaml` manifests, injects env, controls Docker Compose) |
| **Docker Compose** | Container lifecycle management |
| **`proxy-net`** | External Docker network shared between Traefik and workload containers |
The application lives at `~/Sites/bdinvite` on the server.
---
## 2. Container Architecture
A **single container** produced by a multi-stage Docker build:
- **Stage 1** (`node:20-alpine`): Builds the React frontend (`npm ci` → `npm run build`)
- **Stage 2** (`ghcr.io/astral-sh/uv:python3.11-bookworm-slim`): Runs FastAPI with uvicorn; frontend build output (`dist/`) is copied in as `./static`
| Property | Value |
|---|---|
| Container name | `bdinvite` |
| Internal port | `8000` |
| Volume mount | `./data:/app/data` (SQLite persistence) |
| Restart policy | `unless-stopped` |
---
## 3. Dockerfile
```dockerfile
# Stage 1: Build React frontend
FROM node:20-alpine AS frontend-build
WORKDIR /build
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY frontend/ ./
RUN npm run build
# Stage 2: Python runtime
FROM ghcr.io/astral-sh/uv:python3.11-bookworm-slim
WORKDIR /app
ENV UV_COMPILE_BYTECODE=1
COPY backend/pyproject.toml backend/uv.lock* ./
RUN uv sync --frozen --no-install-project --no-dev
COPY backend/ .
COPY --from=frontend-build /build/dist ./static
CMD ["uv", "run", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
```
---
## 4. Traefik Routing
This application uses **path-based routing** on `demos.roadtotech.me`. Three Traefik routers are defined on the same container, all targeting a single service (`bdinvite-svc`) on container port 8000.
`demos.roadtotech.me` is covered by the existing wildcard DNS (`*.roadtotech.me`) and wildcard TLS certificate. No Core/NixOS changes are required.
### 4.1 Public Router — `bdinvite-public` (priority 10)
| Property | Value |
|---|---|
| Rule | ``Host(`demos.roadtotech.me`) && PathPrefix(`/birthday`)`` |
| Entrypoint | `websecure` (port 443) |
| TLS | Enabled (wildcard cert from ACME DNS-01) |
| Middleware | *None* — **public access** |
| Priority | 10 |
Catches all `/birthday/*` traffic that does not match a higher-priority router.
### 4.2 Admin Router — `bdinvite-admin` (priority 20)
| Property | Value |
|---|---|
| Rule | ``Host(`demos.roadtotech.me`) && (PathPrefix(`/birthday/admin`) || PathPrefix(`/birthday/api/admin`))`` |
| Entrypoint | `websecure` (port 443) |
| TLS | Enabled |
| Middleware | `authelia-auth@docker` (ForwardAuth) |
| Priority | 20 |
Higher priority ensures `/birthday/admin/*` and `/birthday/api/admin/*` requests are intercepted before the generic public router.
### 4.3 HTTP Redirect Router — `bdinvite-red`
| Property | Value |
|---|---|
| Rule | ``Host(`demos.roadtotech.me`) && PathPrefix(`/birthday`)`` |
| Entrypoint | `web` (port 80) |
| Middleware | `https-redirect@docker` |
Redirects all HTTP traffic to HTTPS.
---
## 5. Authelia Integration
Authelia runs as a core infrastructure service (container: `authelia`, internal port 9091) on `proxy-net`. The ForwardAuth middleware is defined on the Traefik container:
```yaml
- "traefik.http.middlewares.authelia-auth.forwardauth.address=http://authelia:9091/api/verify?rd=https://auth.${DOMAIN}/"
- "traefik.http.middlewares.authelia-auth.forwardauth.trustForwardHeader=true"
- "traefik.http.middlewares.authelia-auth.forwardauth.authResponseHeaders=Remote-User,Remote-Groups,Remote-Email,Remote-Name"
```
### 5.1 Admin Authentication Flow
```
1. User visits https://demos.roadtotech.me/birthday/admin
2. Traefik matches bdinvite-admin router (priority 20)
3. Traefik forwards request to Authelia at http://authelia:9091/api/verify
4. IF unauthenticated:
→ Authelia returns 401
→ Traefik redirects browser to https://auth.roadtotech.me/?rd=https://demos.roadtotech.me/birthday/admin
5. User authenticates at Authelia portal
6. Authelia sets authelia_session cookie (valid across *.roadtotech.me)
7. Subsequent requests:
→ Authelia returns 200
→ Traefik forwards identity headers to the backend:
Remote-User, Remote-Email, Remote-Groups, Remote-Name
8. Backend reads Remote-User header to identify the admin
```
The backend performs **no authentication of its own** — no login page, no JWT, no session management.
---
## 6. docker-compose.yml
```yaml
services:
bdinvite:
build: .
container_name: bdinvite
restart: unless-stopped
volumes:
- ./data:/app/data
environment:
- BASE_PATH=/birthday
networks:
- proxy-net
labels:
- "diun.enable=false"
- "traefik.enable=true"
# Public router (invitation + public API)
- "traefik.http.routers.bdinvite-public.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
- "traefik.http.routers.bdinvite-public.entrypoints=websecure"
- "traefik.http.routers.bdinvite-public.tls=true"
- "traefik.http.routers.bdinvite-public.priority=10"
- "traefik.http.routers.bdinvite-public.service=bdinvite-svc"
# Admin router (Authelia-protected)
- "traefik.http.routers.bdinvite-admin.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && (PathPrefix(`/birthday/admin`) || PathPrefix(`/birthday/api/admin`))"
- "traefik.http.routers.bdinvite-admin.entrypoints=websecure"
- "traefik.http.routers.bdinvite-admin.tls=true"
- "traefik.http.routers.bdinvite-admin.priority=20"
- "traefik.http.routers.bdinvite-admin.middlewares=authelia-auth@docker"
- "traefik.http.routers.bdinvite-admin.service=bdinvite-svc"
# HTTP to HTTPS redirect
- "traefik.http.routers.bdinvite-red.rule=Host(`${SERVICE_DOMAIN:-demos.roadtotech.me}`) && PathPrefix(`/birthday`)"
- "traefik.http.routers.bdinvite-red.entrypoints=web"
- "traefik.http.routers.bdinvite-red.middlewares=https-redirect@docker"
# Service target
- "traefik.http.services.bdinvite-svc.loadbalancer.server.port=8000"
networks:
proxy-net:
external: true
```
---
## 7. appctl Manifest (app.yaml)
```yaml
name: "bdinvite"
aliases:
- "birthday"
- "invite"
domain: "demos.roadtotech.me"
description: "Interactive Digital Birthday Invitation with RSVP"
visible: true
auth: false
networks:
- proxy-net
env:
BASE_PATH: "/birthday"
homepage:
title: "Birthday Invite"
group: "Applications"
icon: "party.png"
container: "bdinvite"
weight: 30
```
`auth: false` because the public guest route exists. Authelia protection is applied selectively via Traefik labels, not universally to the entire domain.
### 7.1 Injected Environment Variables
`appctl` injects these standard environment variables from the manifest:
| Variable | Value |
|---|---|
| `SERVICE_NAME` | `bdinvite` |
| `CONTAINER_NAME` | `bdinvite` |
| `SERVICE_DOMAIN` | `demos.roadtotech.me` |
| `DOMAIN` | `demos.roadtotech.me` |
| `PROXY_NETWORK` | `proxy-net` |
| `BASE_PATH` | `/birthday` |
Additional secrets are sourced from `/run/secrets/traefik-deployments.env`.
---
## 8. Network Topology
```
Guest Browser
│
▼ HTTPS
demos.roadtotech.me (Traefik :443)
│
├─ /birthday/* (priority 10, public)
│ │
│ ▼
│ bdinvite:8000 (FastAPI)
│
└─ /birthday/admin/* (priority 20, Authelia)
│
▼ ForwardAuth
authelia:9091
│
├── 200 OK → bdinvite:8000 (+ Remote-User header)
│
└── 401 → redirect to auth.roadtotech.me
```
All containers communicate over the `proxy-net` external Docker network. Traefik discovers routing configuration via Docker labels on the `bdinvite` container.
---
## 9. Local Development
### 9.1 Backend Only
```bash
cd backend
uv sync --dev
uv run uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
```
### 9.2 Frontend Only (Separate Terminal)
```bash
cd frontend
npm install
npm run dev
```
Vite's dev server proxies `/birthday/api` to `http://localhost:8000`.
### 9.3 Full Docker Build
```bash
cd Sites/bdinvite
docker compose build
docker compose up -d
curl -s http://localhost:8000/birthday/api/config | python3 -m json.tool
```
---
## 10. Deployment Procedure
The user owns all production transitions. Agents provide deployment runbooks but never execute deployment commands.
After changes are validated locally:
1. Commit changes on feature branch
2. Push to Gitea remote
3. Merge to `main` (user action)
4. On server:
```bash
cd ~/Sites/bdinvite
git fetch && git pull origin main
appctl restart bdinvite
# Or for full rebuild:
docker compose up -d --build
```
Or via `appctl`:
```bash
appctl update bdinvite
```
`appctl update` performs: verify clean working tree → `git pull --ff-only` → `docker compose pull` → `docker compose up -d` → `appctl sync`.
---
## 11. Post-Deployment Verification
```bash
# Container status
ssh server-local "docker ps -a | grep bdinvite"
# Container logs
ssh server-local "docker logs --tail 20 bdinvite"
# API health
ssh server-local "curl -s http://localhost:8000/birthday/api/config | python3 -m json.tool"
# Public access (returns HTML)
curl -s https://demos.roadtotech.me/birthday/ | head -5
# Authelia protection (redirects to auth portal)
curl -sI https://demos.roadtotech.me/birthday/admin
# Admin API without auth (returns 401)
curl -sI https://demos.roadtotech.me/birthday/api/admin/rsvps
# appctl status
ssh server-local "appctl info bdinvite"
```
---
## 12. Rollback Procedure
```bash
# On server:
cd ~/Sites/bdinvite
git log --oneline -5 # identify previous good commit
git checkout <commit-hash>
docker compose up -d --build
# Verify rollback:
ssh server-local "docker logs --tail 10 bdinvite"
curl -s https://demos.roadtotech.me/birthday/api/config
# If database migration issues, restore from backup:
# (SQLite file is in ./data/bdinvite.db)
cp data/bdinvite.db.bak data/bdinvite.db
docker compose restart
```
---
## 13. Data Persistence
| Item | Detail |
|---|---|
| Database | SQLite at `./data/bdinvite.db` (volume-mounted via `./data:/app/data`) |
| Git tracking | `data/` directory is gitignored |
| Backups | Operator responsibility |
| WAL mode files | `-wal` and `-shm` are transient; managed by SQLite |