Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 130 additions & 0 deletions src/ProtectedRoutes.app.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// KAN-82, KAN-85: Implement Protected Routes, Test Protected Routes by Role
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { App } from './App';
import { authService, type StaffRole } from './services/authService';

vi.mock('./layouts/MainLayout', async () => {
const { Outlet } = await import('react-router-dom');
return { MainLayout: () => <Outlet /> };
});
vi.mock('./layouts/PassengerLayout', async () => {
const { Outlet } = await import('react-router-dom');
return { PassengerLayout: () => <Outlet /> };
});
vi.mock('./pages/LoginPage', async () => {
const { useLocation } = await import('react-router-dom');
function LoginPageStub() {
const location = useLocation();
return (
<div>
Login Page <span data-testid="login-search">{location.search}</span>
</div>
);
}
return { LoginPage: LoginPageStub };
});
vi.mock('./pages/DashboardPage', () => ({ DashboardPage: () => <div>Dashboard Page</div> }));
vi.mock('./pages/UsersPage', () => ({ UsersPage: () => <div>Users Page</div> }));
vi.mock('./pages/UserDetailPage', () => ({ UserDetailPage: () => <div>User Detail Page</div> }));
vi.mock('./pages/NotFoundPage', () => ({ NotFoundPage: () => <div>Not Found Page</div> }));
vi.mock('./pages/PassengerHomePage', () => ({
PassengerHomePage: () => <div>Passenger Home Page</div>,
}));

function loginAs(role: StaffRole) {
authService.setSession('test-token', { id: 1, username: 'tester', fullName: 'Test User', role });
}

function renderAt(path: string) {
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>
);
}

describe('KAN-82, KAN-85 Protected routes in App', () => {
beforeEach(() => {
localStorage.clear();
sessionStorage.clear();
});

describe('when signed out', () => {
it('redirects the operations home page to login', () => {
renderAt('/');
expect(screen.getByText(/Login Page/)).toBeInTheDocument();
expect(screen.queryByText('Dashboard Page')).not.toBeInTheDocument();
});

it('redirects /users to login and remembers the page', () => {
renderAt('/users');
expect(screen.getByText(/Login Page/)).toBeInTheDocument();
expect(screen.getByTestId('login-search')).toHaveTextContent('?redirect=%2Fusers');
});

it('sends unknown paths to login instead of showing the 404 page', () => {
renderAt('/does-not-exist');
expect(screen.getByText(/Login Page/)).toBeInTheDocument();
expect(screen.queryByText('Not Found Page')).not.toBeInTheDocument();
});

it('keeps /login and the guest portal public', () => {
const first = renderAt('/login');
expect(screen.getByText(/Login Page/)).toBeInTheDocument();
first.unmount();

renderAt('/passenger-home');
expect(screen.getByText('Passenger Home Page')).toBeInTheDocument();
});
});

describe('when signed in', () => {
it('lets SYSTEM_ADMIN open the users pages', () => {
loginAs('SYSTEM_ADMIN');
const first = renderAt('/users');
expect(screen.getByText('Users Page')).toBeInTheDocument();
first.unmount();

renderAt('/users/5');
expect(screen.getByText('User Detail Page')).toBeInTheDocument();
});

it.each<StaffRole>(['OPERATIONS_MANAGER', 'ITINERARY_COORDINATOR', 'SHORE_EXCURSION_MANAGER', 'POS_STAFF'])(
'keeps %s out of /users and shows the dashboard',
(role) => {
loginAs(role);
renderAt('/users');
expect(screen.getByText('Dashboard Page')).toBeInTheDocument();
expect(screen.queryByText('Users Page')).not.toBeInTheDocument();
}
);

it('keeps non-admin staff out of /users/:id', () => {
loginAs('OPERATIONS_MANAGER');
renderAt('/users/5');
expect(screen.getByText('Dashboard Page')).toBeInTheDocument();
expect(screen.queryByText('User Detail Page')).not.toBeInTheDocument();
});

it('opens the dashboard without a redirect loop', () => {
loginAs('OPERATIONS_MANAGER');
renderAt('/');
expect(screen.getByText('Dashboard Page')).toBeInTheDocument();
});

it('sends a PASSENGER account to login', () => {
loginAs('PASSENGER');
renderAt('/users');
expect(screen.getByText(/Login Page/)).toBeInTheDocument();
expect(screen.queryByText('Users Page')).not.toBeInTheDocument();
});

it('shows the 404 page for unknown paths', () => {
loginAs('SYSTEM_ADMIN');
renderAt('/does-not-exist');
expect(screen.getByText('Not Found Page')).toBeInTheDocument();
});
});
});
104 changes: 104 additions & 0 deletions src/components/auth/ProtectedRoutes.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// KAN-82: Implement Protected Routes
import { describe, it, expect, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom';
import { AdminAuthGuard } from './AdminAuthGuard';
import { authService, type StaffRole } from '../../services/authService';

function LoginStub() {
const location = useLocation();
return (
<div>
Login Page
<span data-testid="login-search">{location.search}</span>
</div>
);
}

function renderGuard(path: string) {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="login" element={<LoginStub />} />
<Route element={<AdminAuthGuard />}>
<Route path="ships" element={<div>Ships Page</div>} />
<Route path="ships/:id" element={<div>Ship Detail Page</div>} />
</Route>
</Routes>
</MemoryRouter>
);
}

const staffUser = { id: 1, username: 'u', fullName: 'U', role: 'SYSTEM_ADMIN' as StaffRole };

describe('KAN-82 Implement Protected Routes: AdminAuthGuard', () => {
beforeEach(() => {
localStorage.clear();
sessionStorage.clear();
});

it.each<StaffRole>([
'SYSTEM_ADMIN',
'OPERATIONS_MANAGER',
'ITINERARY_COORDINATOR',
'ACTIVITY_MANAGER',
'SHORE_EXCURSION_MANAGER',
'POS_STAFF',
'FINANCE_FRONT_DESK',
])('lets %s through', (role) => {
authService.setSession('token', { ...staffUser, role });
renderGuard('/ships');
expect(screen.getByText('Ships Page')).toBeInTheDocument();
});

it('lets staff open nested routes with params', () => {
authService.setSession('token', staffUser);
renderGuard('/ships/7');
expect(screen.getByText('Ship Detail Page')).toBeInTheDocument();
});

it('accepts a session kept in sessionStorage', () => {
sessionStorage.setItem('authToken', 'token');
sessionStorage.setItem('currentUser', JSON.stringify(staffUser));
renderGuard('/ships');
expect(screen.getByText('Ships Page')).toBeInTheDocument();
});

it('blocks a PASSENGER account even with a token', () => {
authService.setSession('token', { ...staffUser, role: 'PASSENGER' });
renderGuard('/ships');
expect(screen.getByText(/Login Page/)).toBeInTheDocument();
expect(screen.queryByText('Ships Page')).not.toBeInTheDocument();
});

it('blocks when only the token exists', () => {
localStorage.setItem('authToken', 'token');
renderGuard('/ships');
expect(screen.getByText(/Login Page/)).toBeInTheDocument();
});

it('blocks when only the user exists', () => {
localStorage.setItem('currentUser', JSON.stringify(staffUser));
renderGuard('/ships');
expect(screen.getByText(/Login Page/)).toBeInTheDocument();
});

it('blocks when the stored user is corrupted', () => {
localStorage.setItem('authToken', 'token');
localStorage.setItem('currentUser', '{not-json');
renderGuard('/ships');
expect(screen.getByText(/Login Page/)).toBeInTheDocument();
});

it('keeps the requested path and query string in the redirect', () => {
renderGuard('/ships?tab=2&sort=name');
expect(screen.getByTestId('login-search')).toHaveTextContent(
`?redirect=${encodeURIComponent('/ships?tab=2&sort=name')}`
);
});

it('keeps nested route params in the redirect', () => {
renderGuard('/ships/7');
expect(screen.getByTestId('login-search')).toHaveTextContent('?redirect=%2Fships%2F7');
});
});
147 changes: 147 additions & 0 deletions src/components/auth/ProtectedRoutesByRole.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
// KAN-85: Test Protected Routes by Role
import { describe, it, expect, beforeEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import { RoleGuard } from './RoleGuard';
import { AdminAuthGuard } from './AdminAuthGuard';
import { authService, type StaffRole } from '../../services/authService';

function loginAs(role: StaffRole) {
authService.setSession('test-token', { id: 1, username: 'tester', fullName: 'Test User', role });
}

function LoginStub() {
const location = useLocation();
return (
<div>
Login Page
<span data-testid="login-search">{location.search}</span>
</div>
);
}

function renderGuard(allowedRoles: string[], redirectTo?: string) {
return render(
<MemoryRouter initialEntries={['/admin']}>
<Routes>
<Route path="/" element={<div>Home Page</div>} />
<Route path="/denied" element={<div>Denied Page</div>} />
<Route element={<RoleGuard allowedRoles={allowedRoles} redirectTo={redirectTo} />}>
<Route path="/admin" element={<div>Admin Page</div>} />
</Route>
</Routes>
</MemoryRouter>
);
}

function renderBothGuards(allowedRoles: string[]) {
return render(
<MemoryRouter initialEntries={['/admin']}>
<Routes>
<Route path="/" element={<div>Home Page</div>} />
<Route path="/login" element={<LoginStub />} />
<Route element={<AdminAuthGuard />}>
<Route element={<RoleGuard allowedRoles={allowedRoles} />}>
<Route path="/admin" element={<div>Admin Page</div>} />
</Route>
</Route>
</Routes>
</MemoryRouter>
);
}

describe('KAN-85 Test Protected Routes by Role: RoleGuard', () => {
const allowed: StaffRole[] = ['SYSTEM_ADMIN', 'OPERATIONS_MANAGER'];
const denied: StaffRole[] = [
'ITINERARY_COORDINATOR',
'ACTIVITY_MANAGER',
'SHORE_EXCURSION_MANAGER',
'POS_STAFF',
'FINANCE_FRONT_DESK',
'PASSENGER',
];

beforeEach(() => {
localStorage.clear();
sessionStorage.clear();
});

it.each(allowed)('allows %s', (role) => {
loginAs(role);
renderGuard(allowed);
expect(screen.getByText('Admin Page')).toBeInTheDocument();
});

it.each(denied)('redirects %s to the home page', (role) => {
loginAs(role);
renderGuard(allowed);
expect(screen.getByText('Home Page')).toBeInTheDocument();
expect(screen.queryByText('Admin Page')).not.toBeInTheDocument();
});

it('redirects when nobody is signed in', () => {
renderGuard(allowed);
expect(screen.getByText('Home Page')).toBeInTheDocument();
});

it('redirects when the stored user is corrupted', () => {
localStorage.setItem('currentUser', '{not-json');
renderGuard(allowed);
expect(screen.getByText('Home Page')).toBeInTheDocument();
});

it('compares roles case sensitively', () => {
authService.setSession('test-token', {
id: 1,
username: 'tester',
fullName: 'Test User',
role: 'system_admin' as StaffRole,
});
renderGuard(allowed);
expect(screen.getByText('Home Page')).toBeInTheDocument();
});

it('blocks everyone when allowedRoles is empty', () => {
loginAs('SYSTEM_ADMIN');
renderGuard([]);
expect(screen.getByText('Home Page')).toBeInTheDocument();
});

it('uses a custom redirect target', () => {
loginAs('POS_STAFF');
renderGuard(allowed, '/denied');
expect(screen.getByText('Denied Page')).toBeInTheDocument();
});
});

describe('KAN-85 Test Protected Routes by Role: AdminAuthGuard + RoleGuard', () => {
beforeEach(() => {
localStorage.clear();
sessionStorage.clear();
});

it('sends a signed-out user to login and keeps the page they wanted', () => {
renderBothGuards(['SYSTEM_ADMIN']);
expect(screen.getByText(/Login Page/)).toBeInTheDocument();
expect(screen.getByTestId('login-search')).toHaveTextContent('?redirect=%2Fadmin');
});

it('sends a signed-in user with the wrong role to the home page, not to login', () => {
loginAs('POS_STAFF');
renderBothGuards(['SYSTEM_ADMIN']);
expect(screen.getByText('Home Page')).toBeInTheDocument();
expect(screen.queryByText(/Login Page/)).not.toBeInTheDocument();
});

it('lets the right role in', () => {
loginAs('SYSTEM_ADMIN');
renderBothGuards(['SYSTEM_ADMIN']);
expect(screen.getByText('Admin Page')).toBeInTheDocument();
});

it('sends a passenger account to login', () => {
loginAs('PASSENGER');
renderBothGuards(['SYSTEM_ADMIN']);
expect(screen.getByText(/Login Page/)).toBeInTheDocument();
});
});
Loading
Loading