Files
Makers3D/apps/web/app/components/BackofficeEntryClient.tsx

90 lines
2.6 KiB
TypeScript

"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { browserFetch } from "../lib/api";
import AdminClient, { type AdminSection } from "./AdminClient";
export default function BackofficeEntryClient({ section }: { section: AdminSection }) {
const pathname = usePathname();
const [state, setState] = useState<"loading" | "ready" | "forbidden">("loading");
const [error, setError] = useState("");
useEffect(() => {
let cancelled = false;
async function checkSession() {
try {
const response = await browserFetch<{ user: { id: string; role: string } | null }>("/auth/me");
if (cancelled) {
return;
}
if (!response.user) {
window.location.replace(`/login?returnTo=${encodeURIComponent(pathname || "/app/backoffice")}`);
return;
}
if (response.user.role !== "admin") {
setState("forbidden");
setError("Esta cuenta no tiene permisos de backoffice.");
return;
}
setState("ready");
} catch (sessionError) {
if (cancelled) {
return;
}
const message = sessionError instanceof Error ? sessionError.message : "No se pudo validar la sesion";
setError(message);
window.location.replace(`/login?returnTo=${encodeURIComponent(pathname || "/app/backoffice")}`);
}
}
void checkSession();
return () => {
cancelled = true;
};
}, [pathname]);
if (state === "loading") {
return (
<main className="page-shell ops-page">
<section className="panel stack">
<span className="eyebrow">Backoffice</span>
<h1 className="section-title">Validando acceso</h1>
<p className="muted">Comprobando la sesion antes de abrir el panel operativo.</p>
</section>
</main>
);
}
if (state === "forbidden") {
return (
<main className="page-shell ops-page">
<section className="panel stack">
<span className="eyebrow">Backoffice</span>
<h1 className="section-title">Acceso restringido</h1>
<p className="muted">{error}</p>
<div className="home-actions">
<Link href="/" className="button button-primary">Volver a la app</Link>
<Link href="/login?returnTo=%2Fapp%2Fbackoffice" className="button button-secondary">Entrar con otra cuenta</Link>
</div>
</section>
</main>
);
}
return (
<main className="page-shell ops-page">
<AdminClient section={section} />
</main>
);
}