178 lines
7.8 KiB
TypeScript
178 lines
7.8 KiB
TypeScript
"use client";
|
||
|
||
import { useEffect, useRef, useState } from "react";
|
||
import { ChevronDown, QrCode, Smartphone } from "lucide-react";
|
||
import { Button } from "@/components/ui/button";
|
||
|
||
type Purpose = "login" | "link";
|
||
type Phase = { at: "idle" } | { at: "qr"; qr: string; deeplink: string; status: string } | { at: "done" } | { at: "error"; message: string };
|
||
|
||
const STATUS: Record<string, string> = {
|
||
pending: "Отсканируйте QR в eGov Mobile",
|
||
scanned: "QR отсканирован — подпишите в eGov Mobile",
|
||
completed: "Подписано, входим…",
|
||
};
|
||
const PHONE_STATUS: Record<string, string> = {
|
||
pending: "Откройте eGov Mobile и подпишите вход, потом вернитесь сюда",
|
||
scanned: "Подпишите в eGov Mobile и вернитесь сюда",
|
||
completed: "Подписано, входим…",
|
||
};
|
||
|
||
/** Saved per tab so a phone that reloads the page on return from eGov Mobile picks the flow up again. */
|
||
const SAVED = "peppa.egov.flow";
|
||
interface Saved {
|
||
purpose: Purpose;
|
||
qr: string;
|
||
deeplink: string;
|
||
expiresAt: number;
|
||
}
|
||
|
||
function readSaved(purpose: Purpose): Saved | null {
|
||
try {
|
||
const s = JSON.parse(sessionStorage.getItem(SAVED) ?? "null") as Saved | null;
|
||
return s && s.purpose === purpose && s.expiresAt > Date.now() ? s : null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
function writeSaved(s: Saved | null) {
|
||
try {
|
||
if (s) sessionStorage.setItem(SAVED, JSON.stringify(s));
|
||
else sessionStorage.removeItem(SAVED);
|
||
} catch {
|
||
/* private mode: no resume, the flow still works */
|
||
}
|
||
}
|
||
|
||
const isPhone = () => typeof window !== "undefined" && (/Android|iPhone|iPad|iPod/i.test(navigator.userAgent) || (navigator.maxTouchPoints > 1 && /Macintosh/.test(navigator.userAgent)));
|
||
|
||
/**
|
||
* eGov sign-in (PEP-65/72): on a computer — the relay's QR for eGov Mobile; on the phone itself —
|
||
* a deep link that opens eGov Mobile, with the QR folded away. Polls the flow and finishes it;
|
||
* `login` signs in (PEP-71: registers on first login), `link` binds the IIN (Settings).
|
||
*/
|
||
export function EgovSign({ purpose, next, label }: { purpose: Purpose; next?: string; label: string }) {
|
||
const [phase, setPhase] = useState<Phase>({ at: "idle" });
|
||
const [phone, setPhone] = useState(false);
|
||
const [showQr, setShowQr] = useState(false);
|
||
const alive = useRef(true);
|
||
const gen = useRef(0);
|
||
const wake = useRef<(() => void) | null>(null);
|
||
|
||
const fail = (message: string) => {
|
||
writeSaved(null);
|
||
if (alive.current) setPhase({ at: "error", message });
|
||
};
|
||
|
||
async function poll() {
|
||
// One loop at a time: a newer poll (or unmount) bumps the generation and the old one stops.
|
||
const my = ++gen.current;
|
||
const stale = () => !alive.current || gen.current !== my;
|
||
{
|
||
for (;;) {
|
||
// Wait 2 s, or less when the tab comes back from eGov Mobile.
|
||
await new Promise<void>((res) => {
|
||
const t = setTimeout(res, 2000);
|
||
wake.current = () => {
|
||
clearTimeout(t);
|
||
res();
|
||
};
|
||
});
|
||
wake.current = null;
|
||
if (stale()) return;
|
||
const s = (await (await fetch("/auth/egov/status", { cache: "no-store" })).json().catch(() => ({}))) as { status?: string; error?: string };
|
||
if (stale()) return;
|
||
if (s.error) return fail(s.error);
|
||
if (s.status === "expired") return fail("Вход истёк — начните заново");
|
||
if (s.status === "rejected") return fail("Подписание отменено в eGov Mobile");
|
||
setPhase((p) => (p.at === "qr" ? { ...p, status: s.status ?? p.status } : p));
|
||
if (s.status === "completed") break;
|
||
}
|
||
const c = await fetch("/auth/egov/complete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ next }) });
|
||
const done = (await c.json().catch(() => ({}))) as { redirect?: string; error?: string };
|
||
if (!c.ok || !done.redirect) return fail(done.error ?? "Не удалось войти через eGov");
|
||
writeSaved(null);
|
||
setPhase({ at: "done" });
|
||
window.location.assign(done.redirect);
|
||
}
|
||
}
|
||
|
||
// Set on mount too: StrictMode (dev) mounts, unmounts and mounts again.
|
||
useEffect(() => {
|
||
alive.current = true;
|
||
setPhone(isPhone());
|
||
const saved = readSaved(purpose);
|
||
if (saved) {
|
||
setPhase({ at: "qr", qr: saved.qr, deeplink: saved.deeplink, status: "pending" });
|
||
void poll().catch((e: Error) => fail(e.message));
|
||
}
|
||
const onVisible = () => document.visibilityState === "visible" && wake.current?.();
|
||
document.addEventListener("visibilitychange", onVisible);
|
||
window.addEventListener("pageshow", onVisible);
|
||
return () => {
|
||
alive.current = false;
|
||
gen.current++;
|
||
wake.current?.();
|
||
document.removeEventListener("visibilitychange", onVisible);
|
||
window.removeEventListener("pageshow", onVisible);
|
||
};
|
||
// eslint-disable-next-line react-hooks/exhaustive-deps -- once per mount
|
||
}, []);
|
||
|
||
async function start() {
|
||
const r = await fetch("/auth/egov/start", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ purpose }) });
|
||
const body = (await r.json()) as { qr?: string; deeplink?: string; expiresAt?: number; error?: string };
|
||
if (!r.ok || !body.qr) return fail(body.error ?? "Не удалось начать вход через eGov");
|
||
const deeplink = body.deeplink ?? "";
|
||
writeSaved({ purpose, qr: body.qr, deeplink, expiresAt: body.expiresAt ?? Date.now() + 5 * 60_000 });
|
||
setShowQr(false);
|
||
setPhase({ at: "qr", qr: body.qr, deeplink, status: "pending" });
|
||
await poll();
|
||
}
|
||
|
||
if (phase.at === "qr") {
|
||
const qrBlock = (
|
||
// eslint-disable-next-line @next/next/no-img-element -- data URL from the server
|
||
<img src={phase.qr} alt="QR для eGov Mobile" width={220} height={220} className="rounded-md bg-white p-1" />
|
||
);
|
||
const status = (phone ? PHONE_STATUS : STATUS)[phase.status] ?? phase.status;
|
||
if (phone && phase.deeplink) {
|
||
return (
|
||
<div className="flex w-full flex-col items-center gap-3 rounded-lg border bg-card p-4">
|
||
<Button asChild variant="default" size="lg" className="w-full">
|
||
<a href={phase.deeplink}>
|
||
<Smartphone /> Открыть eGov Mobile
|
||
</a>
|
||
</Button>
|
||
<p className="m-0 text-sm text-muted-foreground" aria-live="polite">{status}</p>
|
||
<button type="button" className="inline-flex items-center gap-1 text-xs text-muted-foreground underline-offset-2 hover:underline" onClick={() => setShowQr((v) => !v)}>
|
||
<ChevronDown className={showQr ? "size-3 rotate-180" : "size-3"} /> {showQr ? "Скрыть QR" : "Войти с другого телефона по QR"}
|
||
</button>
|
||
{showQr && qrBlock}
|
||
</div>
|
||
);
|
||
}
|
||
return (
|
||
<div className="flex w-full flex-col items-center gap-3 rounded-lg border bg-card p-4">
|
||
{qrBlock}
|
||
<p className="m-0 text-sm text-muted-foreground" aria-live="polite">{status}</p>
|
||
{phase.deeplink && (
|
||
<Button asChild variant="outline" size="sm" className="w-full">
|
||
<a href={phase.deeplink}>
|
||
<Smartphone /> Открыть в eGov Mobile
|
||
</a>
|
||
</Button>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
return (
|
||
<div className="flex w-full flex-col gap-2">
|
||
{phase.at === "error" && <p className="m-0 text-sm text-destructive">{phase.message}</p>}
|
||
<Button variant={purpose === "login" ? "default" : "outline"} size="lg" className="w-full" disabled={phase.at === "done"} onClick={() => void start().catch((e: Error) => fail(e.message))}>
|
||
{phone ? <Smartphone /> : <QrCode />} {phase.at === "error" ? (phone ? "Начать заново" : "Новый QR") : phone ? `${label} Mobile` : label}
|
||
</Button>
|
||
</div>
|
||
);
|
||
}
|