Some checks failed
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 1m5s
Deploy / Build API Image (push) Failing after 27s
Deploy / Build Web Image (push) Failing after 12s
Deploy / Build AI Services Image (push) Failing after 10s
E2E Tests / Playwright E2E (push) Failing after 16s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 3s
Security Scanning / Trivy Scan — API Image (push) Failing after 57s
Deploy / Deploy to Staging (push) Has been cancelled
Deploy / Rollback Staging (push) Has been cancelled
Deploy / Smoke Test Production (push) Has been cancelled
Deploy / Rollback Production (push) Has been cancelled
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 11s
Deploy / Smoke Test Staging (push) Has been cancelled
Deploy / Deploy to Production (push) Has been cancelled
Security Scanning / Trivy Scan — Web Image (push) Failing after 46s
Security Scanning / Trivy Filesystem Scan (push) Has been cancelled
Security Scanning / Security Gate (push) Has been cancelled
Security Scanning / Trivy Scan — AI Services Image (push) Has been cancelled
Five compounding problems caused hundreds of "Console ApiError: Unauthorized" entries on every load of /dashboard (and friends) while unauthenticated or while the auth cookie was stale: 1. QueryClient had `throwOnError: true` as a blanket default, so every 401 from any react-query hook propagated to the nearest error boundary instead of staying in the query's `error` state. That also invited React to re-render and re-fire the boundary multiple times per failing query. 2. React Query retried all failures 3 times with exponential backoff, so a single 401 became four requests. 401 isn't fixable by retry, so this is just noise. 3. Dashboard layout rendered `<NotificationBell />` unconditionally, which polled /notifications/unread-count on mount even when no user was signed in → 401 on every mount. 4. Dashboard + Admin layouts had no redirect-to-login guard, so protected queries (market-report, heatmap, admin/dashboard, …) all mounted and fired against the API before the user ever saw the login screen. 5. Admin layout waited on `user` but had no way to distinguish "store still initialising" from "user genuinely absent" — so an expired cookie left the page stuck on a spinner while the same 401 storm played out in the background. Fixes - query-client.ts: `throwOnError` and `retry` are now predicates. Only 5xx / network errors bubble to boundaries and are retried; 4xx (auth, validation, not-found) stay in query error state so the component can render an empty/auth placeholder. - auth-store.ts: new `isInitialized` flag set in a finally block at the end of `initialize()`. Downstream guards use it to distinguish "still booting" from "definitely logged out". - (dashboard)/layout.tsx: redirects to /login?next=<path> once initialised and unauthenticated, and renders a lightweight loading screen in the meantime so child queries never mount. - (admin)/layout.tsx: same guard. Non-ADMIN logged-in users still bounce to /dashboard. - notification-bell.tsx: short-circuits `fetchUnreadCount` when `isAuthenticated` is false. Verified in dev: visiting /vi/dashboard unauthenticated now redirects to /login?redirect=/dashboard with zero console errors and no /analytics/… calls to the backend. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
154 lines
5.3 KiB
TypeScript
154 lines
5.3 KiB
TypeScript
'use client';
|
|
|
|
import {
|
|
LayoutDashboard,
|
|
Users,
|
|
ClipboardList,
|
|
ShieldCheck,
|
|
LogOut,
|
|
Menu,
|
|
X,
|
|
} from 'lucide-react';
|
|
import { usePathname, useRouter } from 'next/navigation';
|
|
import { useTranslations } from 'next-intl';
|
|
import { useEffect, useState } from 'react';
|
|
import { Button } from '@/components/ui/button';
|
|
import { LanguageSwitcher } from '@/components/ui/language-switcher';
|
|
import { Link } from '@/i18n/navigation';
|
|
import { useAuthStore } from '@/lib/auth-store';
|
|
import { cn } from '@/lib/utils';
|
|
|
|
export default function AdminLayout({ children }: { children: React.ReactNode }) {
|
|
const pathname = usePathname();
|
|
const router = useRouter();
|
|
const { user, isAuthenticated, isInitialized, logout } = useAuthStore();
|
|
const [sidebarOpen, setSidebarOpen] = useState(false);
|
|
const t = useTranslations();
|
|
|
|
const adminNavItems = [
|
|
{ href: '/admin' as const, label: t('adminNav.dashboard'), icon: LayoutDashboard },
|
|
{ href: '/admin/users' as const, label: t('adminNav.users'), icon: Users },
|
|
{ href: '/admin/moderation' as const, label: t('adminNav.moderation'), icon: ClipboardList },
|
|
{ href: '/admin/kyc' as const, label: t('adminNav.kyc'), icon: ShieldCheck },
|
|
];
|
|
|
|
useEffect(() => {
|
|
// Once the auth store finished its initial cookie→profile probe:
|
|
// - no session → push to /login (don't leave a spinner forever)
|
|
// - authenticated but not ADMIN → push to regular dashboard
|
|
if (!isInitialized) return;
|
|
if (!isAuthenticated) {
|
|
router.replace(`/login?next=${encodeURIComponent(pathname)}`);
|
|
return;
|
|
}
|
|
if (user && user.role !== 'ADMIN') {
|
|
router.replace('/dashboard');
|
|
}
|
|
}, [isInitialized, isAuthenticated, user, router, pathname]);
|
|
|
|
if (!isInitialized || !user) {
|
|
return (
|
|
<div className="flex min-h-screen items-center justify-center" role="status">
|
|
<div className="text-muted-foreground">{t('common.loading')}</div>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
if (user.role !== 'ADMIN') {
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<div className="flex min-h-screen bg-background">
|
|
{/* Mobile overlay */}
|
|
{sidebarOpen && (
|
|
<div
|
|
className="fixed inset-0 z-40 bg-black/50 lg:hidden"
|
|
onClick={() => setSidebarOpen(false)}
|
|
aria-hidden="true"
|
|
/>
|
|
)}
|
|
|
|
{/* Sidebar */}
|
|
<aside
|
|
role="navigation"
|
|
aria-label={t('nav.adminNav')}
|
|
className={cn(
|
|
'fixed inset-y-0 left-0 z-50 w-64 border-r bg-card transition-transform lg:static lg:translate-x-0',
|
|
sidebarOpen ? 'translate-x-0' : '-translate-x-full',
|
|
)}
|
|
>
|
|
<div className="flex h-14 items-center border-b px-4">
|
|
<Link href="/admin" className="flex items-center gap-2">
|
|
<span className="text-lg font-bold text-primary">{t('common.goodgo')}</span>
|
|
<span className="rounded bg-primary/10 px-1.5 py-0.5 text-xs font-semibold text-primary">
|
|
{t('common.admin')}
|
|
</span>
|
|
</Link>
|
|
<button
|
|
aria-label={t('adminNav.closeMenu')}
|
|
className="ml-auto lg:hidden"
|
|
onClick={() => setSidebarOpen(false)}
|
|
>
|
|
<X className="h-5 w-5" />
|
|
</button>
|
|
</div>
|
|
|
|
<nav aria-label={t('nav.adminNav')} className="flex flex-col gap-1 p-3">
|
|
{adminNavItems.map((item) => {
|
|
const Icon = item.icon;
|
|
const isActive =
|
|
item.href === '/admin'
|
|
? pathname === '/admin' || pathname.match(/^\/(vi|en)\/admin$/)
|
|
: pathname.includes(item.href);
|
|
return (
|
|
<Link
|
|
key={item.href}
|
|
href={item.href}
|
|
onClick={() => setSidebarOpen(false)}
|
|
className={cn(
|
|
'flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors',
|
|
isActive
|
|
? 'bg-primary/10 text-primary'
|
|
: 'text-muted-foreground hover:bg-accent hover:text-accent-foreground',
|
|
)}
|
|
>
|
|
<Icon className="h-4 w-4" aria-hidden="true" />
|
|
{item.label}
|
|
</Link>
|
|
);
|
|
})}
|
|
</nav>
|
|
|
|
<div className="mt-auto border-t p-3">
|
|
<div className="mb-2 flex items-center justify-between px-3">
|
|
<span className="text-xs text-muted-foreground truncate">{user.fullName}</span>
|
|
<LanguageSwitcher />
|
|
</div>
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
className="w-full justify-start gap-2"
|
|
onClick={() => logout()}
|
|
>
|
|
<LogOut className="h-4 w-4" aria-hidden="true" />
|
|
{t('common.logout')}
|
|
</Button>
|
|
</div>
|
|
</aside>
|
|
|
|
{/* Main content */}
|
|
<div className="flex flex-1 flex-col">
|
|
<header className="sticky top-0 z-30 flex h-14 items-center border-b bg-background/95 px-4 backdrop-blur lg:hidden">
|
|
<button aria-label={t('adminNav.openMenu')} onClick={() => setSidebarOpen(true)}>
|
|
<Menu className="h-5 w-5" />
|
|
</button>
|
|
<span className="ml-3 text-sm font-semibold">{t('common.goodgo')} {t('common.admin')}</span>
|
|
</header>
|
|
|
|
<main id="main-content" role="main" className="flex-1 p-4 md:p-6">{children}</main>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|