SPB Git

Repository Public

page.tsx 12.4 KB 182 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Music SP8 * File             : src/app/(app)/compte/page.tsx9 * Module           : app10 * Repository       : https://git.spboucher.ai/sp-music11 * Project Website  : https://music.spboucher.ai12 * Created          : 2026-11-1713 * Last Modified    : 2026-11-1714 *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: support@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"use client";44import { browserSupportsWebAuthn, startRegistration } from "@simplewebauthn/browser";45import { useRouter, useSearchParams } from "next/navigation";46import { Suspense, useState } from "react";47import { api } from "@/lib/client-api";48import { fmtDate } from "@/lib/format";49import { ACCENT_NAMES } from "@/i18n/messages";50import { useLocale, useT } from "@/i18n";51import type { Key } from "@/i18n/messages";52import { authErrorKey, deviceName } from "@/components/auth-forms";53import { Async, Confirm, PageHeader, Sheet, useApi, useErrorText, useMe, useToast } from "@/components/ui";54import { IAlert, IEdit, IKey, IPlus, ISpinner, ITrash } from "@/components/icons";5556interface Passkey { id: string; name: string; deviceType: string | null; backedUp: boolean; createdAt: string; lastUsedAt: string | null }57interface Session { id: string; method: string; userAgent: string; ip: string | null; createdAt: string; lastSeenAt: string; current: boolean }5859function describeAgent(ua: string): string {60  if (/^SPMusic\//.test(ua)) return `SP Music · ${(ua.match(/\(([^;)]+)/)?.[1] ?? "Mac").slice(0, 40)}`;61  const os = /iPhone/.test(ua) ? "iPhone" : /iPad/.test(ua) ? "iPad" : /Macintosh/.test(ua) ? "Mac" : /Android/.test(ua) ? "Android" : /Windows/.test(ua) ? "Windows" : /Linux/.test(ua) ? "Linux" : "";62  const br = /Edg\//.test(ua) ? "Edge" : /Firefox\//.test(ua) ? "Firefox" : /Chrome\//.test(ua) ? "Chrome" : /Safari\//.test(ua) ? "Safari" : "";63  return [br, os].filter(Boolean).join(" · ") || ua.slice(0, 40) || "—";64}6566function Account() {67  const t = useT(); const locale = useLocale(); const me = useMe(); const toast = useToast(); const text = useErrorText(); const router = useRouter();68  const recovered = useSearchParams().get("recovered") === "1";69  const keys = useApi<{ items: Passkey[] }>("/api/v1/me/passkeys");70  const sessions = useApi<{ items: Session[] }>("/api/v1/me/sessions");71  const codes = useApi<{ remaining: number }>("/api/v1/me/recovery-codes");72  const [adding, setAdding] = useState(false);73  const [busy, setBusy] = useState(false);74  const [newName, setNewName] = useState("");75  const [rename, setRename] = useState<Passkey | null>(null);76  const [del, setDel] = useState<Passkey | null>(null);77  const [err, setErr] = useState<Key | null>(null);7879  const addPasskey = async () => {80    setBusy(true); setErr(null);81    try {82      const { challengeId, options } = await api<{ challengeId: string; options: never }>("/api/v1/auth/register/options", { body: {} });83      const response = await startRegistration({ optionsJSON: options });84      await api("/api/v1/auth/register/verify", { body: { challengeId, response, name: newName.trim() || deviceName() } });85      setAdding(false); keys.reload(); toast(t("account.passkeyAdded"));86    } catch (e) { setErr(authErrorKey(e)); } finally { setBusy(false); }87  };88  const pref = async (body: Record<string, string>) => {89    try { await api("/api/v1/me/preferences", { method: "PATCH", body }); if (body.accent) document.documentElement.dataset.accent = body.accent; router.refresh(); }90    catch (e) { toast(text(e), "error"); }91  };92  const logout = async () => { try { await api("/api/v1/auth/logout", { method: "POST", body: {} }); } finally { window.location.assign("/login"); } };9394  return (95    <div className="max-w-2xl">96      <PageHeader title={t("account.title")} />97      {recovered && <p className="mb-5 flex items-start gap-2 rounded-xl border border-[#57431a] bg-[#261e0d] p-3 text-sm text-warn" role="status"><IAlert size={16} className="mt-0.5 flex-none" />{t("account.recoveredNote")}</p>}9899      <section className="card mb-5 p-5">100        <p className="text-lg font-bold">{me.displayName}</p>101        <p className="text-sm text-muted">{me.email}</p>102        <p className="mt-2"><span className={`chip ${me.role === "admin" ? "chip-accent" : ""}`}>{t(me.role === "admin" ? (me.isOwner ? "role.owner" : "role.admin") : "role.listener")}</span></p>103      </section>104105      <section className="card mb-5 p-5" aria-labelledby="h-pk">106        <div className="mb-1 flex items-center justify-between gap-3">107          <h2 id="h-pk" className="h-section">{t("account.passkeys")}</h2>108          <button className="btn btn-sm" onClick={() => { setNewName(deviceName()); setErr(null); setAdding(true); }} disabled={typeof window !== "undefined" && !browserSupportsWebAuthn()}><IPlus size={14} />{t("account.addPasskey")}</button>109        </div>110        <p className="mb-3 text-sm leading-relaxed text-muted">{t("account.passkeysHelp")}</p>111        <Async res={keys}>{(d) => (112          <ul className="divide-y divide-line">{d.items.map((k) => (113            <li key={k.id} className="flex items-center gap-3 py-3">114              <span className="flex h-10 w-10 flex-none items-center justify-center rounded-xl bg-raised text-accent"><IKey size={18} /></span>115              <div className="min-w-0 flex-1">116                <p className="truncate text-sm font-semibold">{k.name} {k.backedUp && <span className="chip ml-1">{t("account.synced")}</span>}</p>117                <p className="text-xs text-muted">{t("account.created", { date: fmtDate(k.createdAt, locale, false) })} · {k.lastUsedAt ? t("account.lastUsed", { date: fmtDate(k.lastUsedAt, locale) }) : t("account.neverUsed")}</p>118              </div>119              <button className="icon-btn text-muted" onClick={() => { setNewName(k.name); setRename(k); }} aria-label={t("account.renamePasskey", { name: k.name })}><IEdit size={18} /></button>120              <button className="icon-btn text-muted" onClick={() => setDel(k)} disabled={d.items.length <= 1} title={d.items.length <= 1 ? t("err.last_passkey") : undefined} aria-label={t("account.revokePasskey", { name: k.name })}><ITrash size={18} /></button>121            </li>))}</ul>)}</Async>122        {codes.data && <p className="mt-3 border-t border-line pt-3 text-xs leading-relaxed text-faint">{t("account.recoveryCodes", { n: codes.data.remaining })}</p>}123      </section>124125      <section className="card mb-5 p-5" aria-labelledby="h-se">126        <div className="mb-3 flex items-center justify-between gap-3">127          <h2 id="h-se" className="h-section">{t("account.sessions")}</h2>128          <button className="btn btn-sm" onClick={async () => { try { const r = await api<{ revoked: number }>("/api/v1/me/sessions/revoke-others", { method: "POST", body: {} }); toast(t("account.revokedN", { n: r.revoked })); sessions.reload(); } catch (e) { toast(text(e), "error"); } }}>{t("account.revokeOthers")}</button>129        </div>130        <Async res={sessions}>{(d) => (131          <ul className="divide-y divide-line">{d.items.map((s) => (132            <li key={s.id} className="flex items-center gap-3 py-3">133              <div className="min-w-0 flex-1">134                <p className="truncate text-sm font-semibold">{describeAgent(s.userAgent)} {s.current && <span className="chip chip-ok ml-1">{t("account.thisDevice")}</span>}</p>135                <p className="text-xs text-muted">{t("account.lastSeen", { date: fmtDate(s.lastSeenAt, locale) })}{s.ip ? ` · ${s.ip}` : ""}</p>136              </div>137              {!s.current && <button className="btn btn-sm" onClick={async () => { try { await api(`/api/v1/me/sessions/${s.id}`, { method: "DELETE" }); sessions.reload(); } catch (e) { toast(text(e), "error"); } }}>{t("account.revoke")}</button>}138            </li>))}</ul>)}</Async>139      </section>140141      <section className="card mb-5 p-5" aria-labelledby="h-pr">142        <h2 id="h-pr" className="h-section mb-3">{t("account.preferences")}</h2>143        <fieldset>144          <legend className="label">{t("account.accent")}</legend>145          <div className="flex flex-wrap gap-2.5">{ACCENT_NAMES.map((a) => (146            <button key={a} data-accent={a} aria-pressed={me.accent === a} aria-label={t(`accent.${a}` as Key)} title={t(`accent.${a}` as Key)} onClick={() => pref({ accent: a })}147              className={`h-10 w-10 rounded-full border-2 ${me.accent === a ? "border-ink" : "border-transparent"}`} style={{ background: "linear-gradient(135deg, var(--accent), var(--accent-2))" }} />))}</div>148        </fieldset>149        <div className="mt-4"><label className="label" htmlFor="lang">{t("account.language")}</label>150          <select id="lang" className="input !w-auto" value={me.locale} onChange={(e) => pref({ locale: e.target.value })}><option value="fr">Français</option><option value="en">English</option></select></div>151      </section>152153      <section className="card mb-5 p-5 text-sm leading-relaxed text-muted" aria-labelledby="h-pv">154        <h2 id="h-pv" className="h-section mb-2 text-ink">{t("account.privacy")}</h2>155        <p>{t("account.privacyBody")}</p>156      </section>157158      <button className="btn w-full sm:w-auto" onClick={logout}>{t("account.logout")}</button>159160      <Sheet open={adding} onClose={() => setAdding(false)} title={t("account.addPasskey")}>161        <form onSubmit={(e) => { e.preventDefault(); void addPasskey(); }}>162          <p className="mb-3 text-sm leading-relaxed text-muted">{t("account.addPasskeyBody")}</p>163          <label className="label" htmlFor="npk">{t("auth.passkeyName")}</label>164          <input id="npk" className="input" value={newName} maxLength={60} onChange={(e) => setNewName(e.target.value)} data-autofocus />165          {err && <p className="mt-3 text-sm text-danger" role="alert">{t(err)}</p>}166          <div className="mt-4 flex justify-end gap-2"><button type="button" className="btn" onClick={() => setAdding(false)}>{t("common.cancel")}</button><button className="btn btn-primary" disabled={busy}>{busy ? <ISpinner size={16} /> : <IKey size={16} />}{t("auth.createPasskey")}</button></div>167        </form>168      </Sheet>169      <Sheet open={!!rename} onClose={() => setRename(null)} title={t("account.renameTitle")}>170        <form onSubmit={async (e) => { e.preventDefault(); try { await api(`/api/v1/me/passkeys/${rename!.id}`, { method: "PATCH", body: { name: newName.trim() } }); setRename(null); keys.reload(); } catch (x) { toast(text(x), "error"); } }}>171          <label className="label" htmlFor="rpk">{t("auth.passkeyName")}</label>172          <input id="rpk" className="input" value={newName} maxLength={60} onChange={(e) => setNewName(e.target.value)} data-autofocus />173          <div className="mt-4 flex justify-end gap-2"><button type="button" className="btn" onClick={() => setRename(null)}>{t("common.cancel")}</button><button className="btn btn-primary" disabled={!newName.trim()}>{t("common.save")}</button></div>174        </form>175      </Sheet>176      <Confirm open={!!del} onClose={() => setDel(null)} danger title={t("account.revokeTitle")} confirmLabel={t("account.revoke")} body={t("account.revokeBody", { name: del?.name ?? "" })}177        onConfirm={async () => { try { await api(`/api/v1/me/passkeys/${del!.id}`, { method: "DELETE" }); setDel(null); keys.reload(); toast(t("account.passkeyRevoked")); } catch (e) { toast(text(e), "error"); setDel(null); } }} />178    </div>179  );180}181export default function AccountPage() { return <Suspense><Account /></Suspense>; }182
Files main
Menu

Theme