refactor(auth): replace JWT/password-lock with token guards
This commit is contained in:
42
components/admin-guard.tsx
Normal file
42
components/admin-guard.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { authApi } from '@/lib/api';
|
||||
|
||||
export default function AdminGuard({ children }: { children: React.ReactNode }) {
|
||||
const params = useSearchParams();
|
||||
const [state, setState] = useState<'checking' | 'ok' | 'denied'>('checking');
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
const adm = params.get('adm');
|
||||
try {
|
||||
if (adm) {
|
||||
await authApi.session({ adm });
|
||||
// strip the param from URL but keep route
|
||||
const url = new URL(window.location.href);
|
||||
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; };
|
||||
}, [params]);
|
||||
|
||||
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}</>;
|
||||
}
|
||||
@@ -97,44 +97,6 @@ export default function SettingsSection({ settings, onUpdate }: SettingsSectionP
|
||||
This appears below the title on the homepage
|
||||
</p>
|
||||
</div>
|
||||
<div className="pt-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-center mb-3">
|
||||
<input
|
||||
type="checkbox"
|
||||
id="passwordLockEnabled"
|
||||
className="h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"
|
||||
checked={settingsForm.passwordLockEnabled}
|
||||
onChange={(e) =>
|
||||
setSettingsForm((prev) => ({ ...prev, passwordLockEnabled: e.target.checked }))
|
||||
}
|
||||
/>
|
||||
<label htmlFor="passwordLockEnabled" className="ml-2 block text-base font-medium text-gray-700 dark:text-gray-300">
|
||||
Enable Password Lock
|
||||
</label>
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 mb-3">
|
||||
When enabled, visitors must enter a password to access the website
|
||||
</p>
|
||||
{settingsForm.passwordLockEnabled && (
|
||||
<div>
|
||||
<label className="block text-base font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
Site Password
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 dark:bg-gray-700 dark:text-white"
|
||||
value={settingsForm.passwordLock || ''}
|
||||
onChange={(e) =>
|
||||
setSettingsForm((prev) => ({ ...prev, passwordLock: e.target.value }))
|
||||
}
|
||||
placeholder="Enter password (leave blank to keep current)"
|
||||
/>
|
||||
<p className="mt-1 text-sm text-gray-500 dark:text-gray-400">
|
||||
Leave blank to keep the current password unchanged
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
@@ -161,20 +123,6 @@ export default function SettingsSection({ settings, onUpdate }: SettingsSectionP
|
||||
<p className="text-sm font-medium text-gray-500 dark:text-gray-400">Homepage Subtext</p>
|
||||
<p className="text-base text-gray-900 dark:text-white">{settings.homepageSubtext}</p>
|
||||
</div>
|
||||
<div className="pt-3 border-t border-gray-200 dark:border-gray-700">
|
||||
<p className="text-sm font-medium text-gray-500 dark:text-gray-400">Password Lock</p>
|
||||
<p className="text-base text-gray-900 dark:text-white">
|
||||
{settings.passwordLockEnabled ? (
|
||||
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-base font-medium bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200">
|
||||
Enabled
|
||||
</span>
|
||||
) : (
|
||||
<span className="inline-flex items-center px-2.5 py-1 rounded-full text-base font-medium bg-gray-100 dark:bg-gray-700 text-gray-800 dark:text-gray-300">
|
||||
Disabled
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
45
components/guest-guard.tsx
Normal file
45
components/guest-guard.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { authApi } from '@/lib/api';
|
||||
|
||||
type Status = 'checking' | { kind: 'ok'; guestName: string } | 'denied';
|
||||
|
||||
export default function GuestGuard({ children }: { children: React.ReactNode }) {
|
||||
const params = useSearchParams();
|
||||
const [status, setStatus] = useState<Status>('checking');
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
const usr = params.get('usr');
|
||||
try {
|
||||
if (usr) {
|
||||
await authApi.session({ usr });
|
||||
// user said leaving the token in URL is fine — do NOT strip
|
||||
}
|
||||
const who = await authApi.whoami();
|
||||
if (cancelled) return;
|
||||
if (who.role === 'admin' || who.role === 'guest') {
|
||||
setStatus({ kind: 'ok', guestName: who.guest?.name ?? 'admin' });
|
||||
} else {
|
||||
setStatus('denied');
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) setStatus('denied');
|
||||
}
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, [params]);
|
||||
|
||||
if (status === 'checking') return <div className="min-h-screen flex items-center justify-center text-gray-500">Verificando convite…</div>;
|
||||
if (status === '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">Convite necessário</h1>
|
||||
<p className="text-gray-500">Esta lista é por convite. Use o link que recebeu.</p>
|
||||
</div>
|
||||
</div>;
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useAuth } from '@/lib/auth-context';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { authApi } from '@/lib/api';
|
||||
|
||||
interface HeaderProps {
|
||||
title: string;
|
||||
@@ -11,11 +12,24 @@ interface HeaderProps {
|
||||
}
|
||||
|
||||
export default function Header({ title, subtitle, imageUrl, actions, maxWidth = 'max-w-7xl' }: HeaderProps) {
|
||||
const { isAuthenticated } = useAuth();
|
||||
const [isAdmin, setIsAdmin] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const who = await authApi.whoami();
|
||||
if (!cancelled) setIsAdmin(who.role === 'admin');
|
||||
} catch {
|
||||
if (!cancelled) setIsAdmin(false);
|
||||
}
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{isAuthenticated && (
|
||||
{isAdmin && (
|
||||
<div className="sticky top-0 z-50 bg-amber-50 dark:bg-amber-900/40 border-b border-amber-200/70 dark:border-amber-800/60 backdrop-blur">
|
||||
<div className={`${maxWidth} mx-auto py-3 px-4 sm:px-6 lg:px-8`}>
|
||||
<p className="text-center text-sm text-amber-900 dark:text-amber-100">
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useRouter, usePathname } from 'next/navigation';
|
||||
|
||||
export default function PasswordLockGuard({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const [isChecking, setIsChecking] = useState(true);
|
||||
const [isLocked, setIsLocked] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Skip check for admin and lock pages
|
||||
if (pathname.startsWith('/admin') || pathname === '/lock') {
|
||||
setIsChecking(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const checkPasswordLock = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/settings');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success && data.settings.passwordLockEnabled) {
|
||||
setIsLocked(true);
|
||||
// Redirect to lock page
|
||||
router.push('/lock');
|
||||
} else {
|
||||
setIsChecking(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking password lock:', error);
|
||||
// On error, allow access to prevent site lockout
|
||||
setIsChecking(false);
|
||||
}
|
||||
};
|
||||
|
||||
checkPasswordLock();
|
||||
}, [pathname, router]);
|
||||
|
||||
// Show loading or nothing while checking
|
||||
if (isChecking) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
|
||||
<p className="text-gray-600 dark:text-gray-400">Loading...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// If locked, don't render children (redirect is happening)
|
||||
if (isLocked) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useAuth } from '@/lib/auth-context';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export default function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
const { isAuthenticated, isLoading } = useAuth();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && !isAuthenticated) {
|
||||
router.push('/admin/login');
|
||||
}
|
||||
}, [isAuthenticated, isLoading, router]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center">
|
||||
<div className="text-gray-600">Loading...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
Reference in New Issue
Block a user