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
This commit is contained in:
1 parent
39ac42cfce
commit
e1f745608a
5 files changed
+414
-5
No files matched your search
@@ -41,7 +41,7 @@ def callback(
|
|||||||
code: str = Query(..., description="Authorization code from IdP"),
|
code: str = Query(..., description="Authorization code from IdP"),
|
||||||
state: str = Query(..., description="CSRF state parameter"),
|
state: str = Query(..., description="CSRF state parameter"),
|
||||||
) -> Response:
|
) -> Response:
|
||||||
target_url = "/birthday/"
|
target_url = "/birthday/admin"
|
||||||
response = RedirectResponse(url=target_url, status_code=status.HTTP_302_FOUND)
|
response = RedirectResponse(url=target_url, status_code=status.HTTP_302_FOUND)
|
||||||
adapter.handle_callback(
|
adapter.handle_callback(
|
||||||
code=code,
|
code=code,
|
||||||
@@ -62,7 +62,11 @@ def callback(
|
|||||||
summary="Logout user session (API)",
|
summary="Logout user session (API)",
|
||||||
description="Revokes the session on server/storage, clears browser cookie (Max-Age=0), and returns JSON confirmation.",
|
description="Revokes the session on server/storage, clears browser cookie (Max-Age=0), and returns JSON confirmation.",
|
||||||
)
|
)
|
||||||
def logout(request: Request, adapter: AuthAdapterDep) -> Response:
|
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", "")
|
accept_header = request.headers.get("accept", "")
|
||||||
if request.method == "POST" or "application/json" in accept_header:
|
if request.method == "POST" or "application/json" in accept_header:
|
||||||
json_resp = JSONResponse(
|
json_resp = JSONResponse(
|
||||||
@@ -71,7 +75,9 @@ def logout(request: Request, adapter: AuthAdapterDep) -> Response:
|
|||||||
)
|
)
|
||||||
return adapter.logout(request, response=json_resp)
|
return adapter.logout(request, response=json_resp)
|
||||||
|
|
||||||
return adapter.logout(request)
|
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(
|
@router.get(
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -5,7 +5,7 @@
|
|||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "tsc -b && vite build",
|
"build": "tsc -b && vite build && cp -r dist/* ../backend/static/",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"lint": "biome check .",
|
"lint": "biome check .",
|
||||||
"lint:fix": "biome check --write .",
|
"lint:fix": "biome check --write .",
|
||||||
|
|||||||
@@ -1,6 +1,161 @@
|
|||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import { Link, NavLink, Outlet } from "react-router-dom";
|
import { Link, NavLink, Outlet } from "react-router-dom";
|
||||||
|
import { type AuthUser, fetchSession, logoutUser } from "../api/client";
|
||||||
|
|
||||||
export function AdminLayout() {
|
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 (
|
return (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
@@ -38,7 +193,7 @@ export function AdminLayout() {
|
|||||||
</h1>
|
</h1>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<nav style={{ display: "flex", alignItems: "center", gap: "1.4rem" }}>
|
<nav style={{ display: "flex", alignItems: "center", gap: "1.4rem", flexWrap: "wrap" }}>
|
||||||
<NavLink
|
<NavLink
|
||||||
to="/admin"
|
to="/admin"
|
||||||
end
|
end
|
||||||
@@ -88,6 +243,55 @@ export function AdminLayout() {
|
|||||||
<span>Ver Pública</span>
|
<span>Ver Pública</span>
|
||||||
<span>↗</span>
|
<span>↗</span>
|
||||||
</Link>
|
</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>
|
</nav>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
|
|||||||
@@ -158,3 +158,46 @@ export async function updateAdminRsvp(
|
|||||||
return res.json();
|
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" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
Reference in new issue
Block a user