Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : UQO Éval — Le Grand Défi Immobilier8 * File : apps/web/src/admin/Admin.tsx9 * Module : admin10 * Repository : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website : https://jeux.uqo-eval.app12 * Created : 2026-11-2513 * Last Modified : 2026-11-2514 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/** Espace d'administration du Grand Défi Immobilier. Accès par clé (lien remis au responsable), sans compte. */44import { useCallback, useEffect, useState, type FormEvent } from "react";45import { Link, Route, Switch, useLocation } from "wouter";46import { IconKey } from "../components/Icons";47import { Logo } from "../components/Logo";48import { ApiError, api } from "../lib/api";49import "./admin.css";50import Analytics from "./Analytics";51import CompetitionDetailPage from "./CompetitionDetail";52import Competitions, { CompetitionCreate } from "./Competitions";53import Dashboard from "./Dashboard";54import DataPage from "./Data";55import Journal from "./Journal";56import { errorMessage, setUnauthorizedHandler } from "./lib";57import Participants from "./Participants";58import Roster from "./Roster";59import { NotifyProvider } from "./ui";6061type Access = "checking" | "granted" | "locked";6263const NAV = [64 { href: "/admin", label: "Tableau de bord", match: (p: string) => p === "/admin" || p === "/admin/" },65 { href: "/admin/competitions", label: "Compétitions", match: (p: string) => p.startsWith("/admin/competitions") },66 { href: "/admin/participants", label: "Participants", match: (p: string) => p.startsWith("/admin/participants") },67 { href: "/admin/listes", label: "Listes de classe", match: (p: string) => p.startsWith("/admin/listes") },68 { href: "/admin/analyses", label: "Analyses", match: (p: string) => p.startsWith("/admin/analyses") },69 { href: "/admin/donnees", label: "Données", match: (p: string) => p.startsWith("/admin/donnees") },70 { href: "/admin/journal", label: "Journal", match: (p: string) => p.startsWith("/admin/journal") },71] as const;7273function Gate({ onGranted, notice }: { onGranted: () => void; notice: string | null }) {74 const [key, setKey] = useState("");75 const [busy, setBusy] = useState(false);76 const [error, setError] = useState<string | null>(null);7778 const submit = async (event: FormEvent): Promise<void> => {79 event.preventDefault();80 if (!key.trim() || busy) return;81 setBusy(true);82 setError(null);83 try {84 await api("/api/v1/admin/login", { method: "POST", body: { key: key.trim() } });85 onGranted();86 } catch (e) {87 setError(errorMessage(e));88 setBusy(false);89 }90 };9192 return (93 <main className="adm-gate">94 <form className="adm-gate-box" onSubmit={(e) => void submit(e)} noValidate>95 <Logo />96 <div className="stack">97 <p className="eyebrow">Administration</p>98 <h1 className="title">Accès réservé</h1>99 <p className="adm-lede">100 L'accès se fait par le lien d'administration remis au responsable de l'activité. Si vous avez reçu la clé seule, saisissez-la ci-dessous.101 </p>102 </div>103 {notice && <p className="adm-gate-notice" role="status">{notice}</p>}104 <div className="field">105 <label htmlFor="adm-cle">Clé d'administration</label>106 <input id="adm-cle" className="input" type="password" autoComplete="current-password" value={key} onChange={(e) => setKey(e.target.value)} aria-invalid={error ? true : undefined} aria-describedby={error ? "adm-cle-erreur" : undefined} maxLength={200} required />107 {error && <p id="adm-cle-erreur" className="error-text" role="alert">{error}</p>}108 </div>109 <button type="submit" className="btn btn-dark" disabled={busy || !key.trim()}>110 <IconKey size={18} />{busy ? "Vérification…" : "Ouvrir l'administration"}111 </button>112 <p className="small muted">Aucun compte ni mot de passe personnel n'est créé. La session expire après douze heures.</p>113 <p className="small"><Link href="/">Retour au jeu</Link></p>114 </form>115 </main>116 );117}118119export default function Admin() {120 const [location] = useLocation();121 const [access, setAccess] = useState<Access>("checking");122 const [notice, setNotice] = useState<string | null>(null);123 const [open, setOpen] = useState(false);124125 const check = useCallback(async (): Promise<void> => {126 const params = new URLSearchParams(window.location.search);127 const urlKey = params.get("cle");128 const stripKey = (): void => {129 params.delete("cle");130 const query = params.toString();131 window.history.replaceState(window.history.state, "", `${window.location.pathname}${query ? `?${query}` : ""}${window.location.hash}`);132 };133 try {134 const session = await api<{ authenticated: boolean; open: boolean }>("/api/v1/admin/session");135 setOpen(session.open);136 if (session.authenticated) {137 if (urlKey !== null) stripKey();138 setAccess("granted");139 return;140 }141 if (urlKey !== null) {142 try {143 await api("/api/v1/admin/login", { method: "POST", body: { key: urlKey } });144 stripKey();145 setAccess("granted");146 return;147 } catch (e) {148 stripKey();149 setNotice(e instanceof ApiError && e.status === 401 ? "La clé contenue dans le lien n'est pas valide. Demandez un nouveau lien au responsable." : errorMessage(e));150 }151 }152 setAccess("locked");153 } catch (e) {154 setNotice(errorMessage(e));155 setAccess("locked");156 }157 }, []);158159 useEffect(() => {160 void check();161 }, [check]);162163 useEffect(() => {164 setUnauthorizedHandler(() => {165 setNotice("Votre session d'administration a expiré. Saisissez de nouveau la clé.");166 setAccess("locked");167 });168 return () => setUnauthorizedHandler(null);169 }, []);170171 useEffect(() => {172 const robots = document.createElement("meta");173 robots.name = "robots";174 robots.content = "noindex, nofollow";175 document.head.appendChild(robots);176 return () => robots.remove();177 }, []);178179 // À chaque changement de section : titre du document et retour en haut de page.180 useEffect(() => {181 if (access !== "granted") {182 document.title = "Administration — UQO ÉVAL";183 return;184 }185 const current = NAV.find((n) => n.match(location));186 document.title = `${current?.label ?? "Administration"} — Administration UQO ÉVAL`;187 window.scrollTo(0, 0);188 }, [location, access]);189190 // Barre d'onglets mobile : l'onglet courant reste visible.191 useEffect(() => {192 if (access !== "granted") return;193 document.querySelector<HTMLElement>('.adm-nav a[aria-current="page"]')?.scrollIntoView({ block: "nearest", inline: "center" });194 }, [location, access]);195196 if (access === "checking") {197 return (198 <div className="center-screen" role="status">199 <span className="spinner" aria-hidden="true" />200 <span className="sr-only">Vérification de l'accès…</span>201 </div>202 );203 }204205 if (access === "locked") {206 return (207 <div className="adm adm-locked">208 <Gate209 notice={notice}210 onGranted={() => {211 setNotice(null);212 setAccess("granted");213 }}214 />215 </div>216 );217 }218219 return (220 <NotifyProvider>221 <div className="adm">222 <a className="skip-link" href="#adm-contenu">Aller au contenu</a>223 <header className="adm-side">224 <div className="adm-brand">225 <Link href="/admin"><Logo size={30} /></Link>226 <span className="adm-brand-tag">Administration</span>227 </div>228 <nav aria-label="Sections de l'administration" className="adm-nav">229 <ul role="list">230 {NAV.map((item) => {231 const current = item.match(location);232 return (233 <li key={item.href}>234 <Link href={item.href} aria-current={current ? "page" : undefined}>{item.label}</Link>235 </li>236 );237 })}238 </ul>239 </nav>240 <div className="adm-side-foot">241 {open && <p className="small">Mode local : aucune clé n'est exigée.</p>}242 <p className="small"><a href="/" target="_blank" rel="noreferrer">Ouvrir le jeu<span className="sr-only"> (nouvel onglet)</span></a></p>243 </div>244 </header>245 <main className="adm-main" id="adm-contenu">246 <Switch>247 <Route path="/admin" component={Dashboard} />248 <Route path="/admin/competitions" component={Competitions} />249 <Route path="/admin/competitions/nouvelle" component={CompetitionCreate} />250 <Route path="/admin/competitions/:id">{(params) => <CompetitionDetailPage key={params.id} id={params.id} />}</Route>251 <Route path="/admin/participants" component={Participants} />252 <Route path="/admin/listes" component={Roster} />253 <Route path="/admin/analyses" component={Analytics} />254 <Route path="/admin/donnees" component={DataPage} />255 <Route path="/admin/journal" component={Journal} />256 <Route>257 <div className="adm-page">258 <h1 className="title">Section introuvable</h1>259 <p className="adm-lede">Cette adresse ne correspond à aucune section de l'administration.</p>260 <p><Link href="/admin" className="btn btn-dark">Retour au tableau de bord</Link></p>261 </div>262 </Route>263 </Switch>264 </main>265 </div>266 </NotifyProvider>267 );268}269