Some checks failed
Build and Push Docker Image / build-and-push (push) Has been cancelled
40 lines
1.3 KiB
TypeScript
40 lines
1.3 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useState } from 'react';
|
|
import { authApi } from '@/lib/api';
|
|
|
|
export default function AdminGuard({ children }: { children: React.ReactNode }) {
|
|
const [state, setState] = useState<'checking' | 'ok' | 'denied'>('checking');
|
|
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
(async () => {
|
|
const url = new URL(window.location.href);
|
|
const adm = url.searchParams.get('adm');
|
|
try {
|
|
if (adm) {
|
|
await authApi.session({ adm });
|
|
url.searchParams.delete('adm');
|
|
window.history.replaceState({}, '', url.toString());
|
|
}
|
|
const who = await authApi.whoami();
|
|
if (cancelled) return;
|
|
if (who.role === 'admin') setState('ok');
|
|
else setState('denied');
|
|
} catch {
|
|
if (!cancelled) setState('denied');
|
|
}
|
|
})();
|
|
return () => { cancelled = true; };
|
|
}, []);
|
|
|
|
if (state === 'checking') return <div className="min-h-screen flex items-center justify-center text-gray-500">Verificando…</div>;
|
|
if (state === 'denied') return <div className="min-h-screen flex items-center justify-center text-center px-6">
|
|
<div>
|
|
<h1 className="text-2xl font-bold mb-2">Acesso restrito</h1>
|
|
<p className="text-gray-500">Adicione <code>?adm=<token></code> à URL para entrar.</p>
|
|
</div>
|
|
</div>;
|
|
return <>{children}</>;
|
|
}
|