1 Commits

Author SHA1 Message Date
evan 6231befaa8 cleanup 2
continuous-integration/drone/pr Build is failing
2026-07-03 16:49:58 -04:00
2 changed files with 85 additions and 0 deletions
+68
View File
@@ -0,0 +1,68 @@
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { AdminRoute } from './AdminRoute';
import { useAuth } from './AuthContext';
vi.mock('./AuthContext', () => ({
useAuth: vi.fn(),
}));
const mockedUseAuth = vi.mocked(useAuth);
describe('AdminRoute', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders children for admin users', () => {
mockedUseAuth.mockReturnValue({
isAuthenticated: true,
isCheckingAuth: false,
user: { username: 'evan', is_admin: true },
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
});
render(
<MemoryRouter>
<AdminRoute>
<div>Admin Panel</div>
</AdminRoute>
</MemoryRouter>
);
expect(screen.getByText('Admin Panel')).toBeInTheDocument();
});
it('redirects non-admin users to the home page', () => {
mockedUseAuth.mockReturnValue({
isAuthenticated: true,
isCheckingAuth: false,
user: { username: 'evan', is_admin: false },
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
});
render(
<MemoryRouter initialEntries={['/admin']}>
<Routes>
<Route
path="/admin"
element={
<AdminRoute>
<div>Admin Panel</div>
</AdminRoute>
}
/>
<Route path="/" element={<div>Home Page</div>} />
</Routes>
</MemoryRouter>
);
expect(screen.getByText('Home Page')).toBeInTheDocument();
expect(screen.queryByText('Admin Panel')).not.toBeInTheDocument();
});
});
+17
View File
@@ -0,0 +1,17 @@
import { Navigate } from 'react-router-dom';
import { useAuth } from './AuthContext';
interface AdminRouteProps {
children: React.ReactNode;
}
// Role Guard - Runs behind ProtectedRoute, so auth is already resolved and `user` is populated by the time this renders.
export function AdminRoute({ children }: AdminRouteProps) {
const { user } = useAuth();
if (!user?.is_admin) {
return <Navigate to="/" replace />;
}
return children;
}