import { useEffect, useState } from "react"; import "./brand/remilianet-login.css"; import { RemiliaLoginButton } from "./brand/RemiliaLoginButton"; import { getOidc, useOidc } from "./oidc"; type Profile = { user: { username: string; displayName: string } }; export function App() { const oidc = useOidc(); if (!oidc.isUserLoggedIn) { return Connect your account void oidc.login()} />; } return ; } function ConnectedAccount() { const oidc = useOidc({ assert: "user logged in" }); const [profile, setProfile] = useState(null); const [error, setError] = useState(""); const [attempt, setAttempt] = useState(0); const [loggingOut, setLoggingOut] = useState(false); useEffect(() => { const controller = new AbortController(); let active = true; setProfile(null); setError(""); if (loggingOut) return () => controller.abort(); void (async () => { try { const session = await getOidc({ assert: "user logged in" }); const token = await session.getAccessToken(); if (!active) return; const response = await fetch("https://www.remilia.net/api/v1/me", { credentials: "omit", signal: controller.signal, headers: { Authorization: `Bearer ${token}` }, }); if (!response.ok) throw new Error(`Profile request failed (${response.status}). Retry or log in again.`); const result: Profile = await response.json(); if (!result.user?.username || !result.user?.displayName) throw new Error("The profile response is incomplete."); if (active) setProfile(result); } catch (failure) { if (active && !controller.signal.aborted) setError(failure instanceof Error ? failure.message : "Unable to read the profile."); } })(); return () => { active = false; controller.abort(); }; }, [attempt, loggingOut]); return Connected account {profile && !loggingOut ? {profile.user.displayName} (~{profile.user.username}) : error && !loggingOut ? null : {loggingOut ? "Logging out…" : "Loading profile…"}} {error && !loggingOut && {error} setAttempt(value => value + 1)}>Retry profile} { setProfile(null); setError(""); setLoggingOut(true); void oidc.logout({ redirectTo: "home" }); }}>Log out ; }
{profile.user.displayName} (~{profile.user.username})
{loggingOut ? "Logging out…" : "Loading profile…"}
{error}