diff --git a/src/ProtectedRoutes.app.test.tsx b/src/ProtectedRoutes.app.test.tsx
new file mode 100644
index 0000000..5b40572
--- /dev/null
+++ b/src/ProtectedRoutes.app.test.tsx
@@ -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: () => };
+});
+vi.mock('./layouts/PassengerLayout', async () => {
+ const { Outlet } = await import('react-router-dom');
+ return { PassengerLayout: () => };
+});
+vi.mock('./pages/LoginPage', async () => {
+ const { useLocation } = await import('react-router-dom');
+ function LoginPageStub() {
+ const location = useLocation();
+ return (
+
+ Login Page {location.search}
+
+ );
+ }
+ return { LoginPage: LoginPageStub };
+});
+vi.mock('./pages/DashboardPage', () => ({ DashboardPage: () => Dashboard Page
}));
+vi.mock('./pages/UsersPage', () => ({ UsersPage: () => Users Page
}));
+vi.mock('./pages/UserDetailPage', () => ({ UserDetailPage: () => User Detail Page
}));
+vi.mock('./pages/NotFoundPage', () => ({ NotFoundPage: () => Not Found Page
}));
+vi.mock('./pages/PassengerHomePage', () => ({
+ PassengerHomePage: () => Passenger Home Page
,
+}));
+
+function loginAs(role: StaffRole) {
+ authService.setSession('test-token', { id: 1, username: 'tester', fullName: 'Test User', role });
+}
+
+function renderAt(path: string) {
+ return render(
+
+
+
+ );
+}
+
+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(['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();
+ });
+ });
+});
diff --git a/src/components/auth/ProtectedRoutes.test.tsx b/src/components/auth/ProtectedRoutes.test.tsx
new file mode 100644
index 0000000..42ca7e9
--- /dev/null
+++ b/src/components/auth/ProtectedRoutes.test.tsx
@@ -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 (
+
+ Login Page
+ {location.search}
+
+ );
+}
+
+function renderGuard(path: string) {
+ return render(
+
+
+ } />
+ }>
+ Ships Page} />
+ Ship Detail Page} />
+
+
+
+ );
+}
+
+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([
+ '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');
+ });
+});
\ No newline at end of file
diff --git a/src/components/auth/ProtectedRoutesByRole.test.tsx b/src/components/auth/ProtectedRoutesByRole.test.tsx
new file mode 100644
index 0000000..19fcd25
--- /dev/null
+++ b/src/components/auth/ProtectedRoutesByRole.test.tsx
@@ -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 (
+
+ Login Page
+ {location.search}
+
+ );
+}
+
+function renderGuard(allowedRoles: string[], redirectTo?: string) {
+ return render(
+
+
+ Home Page} />
+ Denied Page} />
+ }>
+ Admin Page} />
+
+
+
+ );
+}
+
+function renderBothGuards(allowedRoles: string[]) {
+ return render(
+
+
+ Home Page} />
+ } />
+ }>
+ }>
+ Admin Page} />
+
+
+
+
+ );
+}
+
+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();
+ });
+});
diff --git a/src/pages/LoginComponent.test.tsx b/src/pages/LoginComponent.test.tsx
new file mode 100644
index 0000000..083d45e
--- /dev/null
+++ b/src/pages/LoginComponent.test.tsx
@@ -0,0 +1,112 @@
+// KAN-84: Write Login Component Tests
+import { describe, it, expect, afterEach, vi } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter, Route, Routes } from 'react-router-dom';
+import { LoginPage } from './LoginPage';
+import { authService, type AuthUser } from '../services/authService';
+
+const adminUser: AuthUser = {
+ id: 1,
+ username: 'admin',
+ fullName: 'Admin Test',
+ role: 'SYSTEM_ADMIN',
+};
+
+function renderLogin(entry = '/login') {
+ return render(
+
+
+ } />
+ Home Page} />
+ POS Page} />
+
+
+ );
+}
+
+const usernameInput = () => screen.getByLabelText(/Tên đăng nhập/i);
+const passwordInput = () => screen.getByLabelText('Mật khẩu xác thực');
+const submitButton = () => screen.getByRole('button', { name: /Đăng nhập Vận Hành/i });
+
+describe('KAN-84 Write Login Component Tests: LoginPage', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('toggles password visibility', async () => {
+ const user = userEvent.setup();
+ renderLogin();
+
+ expect(passwordInput()).toHaveAttribute('type', 'password');
+
+ await user.click(screen.getByRole('button', { name: 'Hiển thị mật khẩu' }));
+ expect(passwordInput()).toHaveAttribute('type', 'text');
+
+ await user.click(screen.getByRole('button', { name: 'Ẩn mật khẩu' }));
+ expect(passwordInput()).toHaveAttribute('type', 'password');
+ });
+
+ it.each([
+ { name: 'empty form', username: '', password: '' },
+ { name: 'missing password', username: 'admin', password: '' },
+ { name: 'missing username', username: '', password: 'admin123' },
+ { name: 'blank username', username: ' ', password: 'admin123' },
+ ])('shows a validation error and skips login: $name', async ({ username, password }) => {
+ const user = userEvent.setup();
+ const loginSpy = vi.spyOn(authService, 'login');
+ renderLogin();
+
+ if (username) await user.type(usernameInput(), username);
+ if (password) await user.type(passwordInput(), password);
+ await user.click(submitButton());
+
+ expect(screen.getByRole('alert')).toHaveTextContent(/Vui lòng nhập đầy đủ/i);
+ expect(loginSpy).not.toHaveBeenCalled();
+ });
+
+ it('submits the typed credentials and goes to the home page', async () => {
+ const user = userEvent.setup();
+ const loginSpy = vi.spyOn(authService, 'login').mockResolvedValue(adminUser);
+ renderLogin();
+
+ await user.type(usernameInput(), 'admin');
+ await user.type(passwordInput(), 'admin123');
+ await user.click(submitButton());
+
+ await waitFor(() => expect(screen.getByText('Home Page')).toBeInTheDocument());
+ expect(loginSpy).toHaveBeenCalledWith({ username: 'admin', password: 'admin123' });
+ });
+
+ it('returns to the redirect target after login', async () => {
+ const user = userEvent.setup();
+ vi.spyOn(authService, 'login').mockResolvedValue(adminUser);
+ renderLogin('/login?redirect=/pos');
+
+ await user.click(screen.getByRole('button', { name: /Admin Toàn Quyền/i }));
+ await user.click(submitButton());
+
+ await waitFor(() => expect(screen.getByText('POS Page')).toBeInTheDocument());
+ });
+
+ it('disables the form while signing in', async () => {
+ const user = userEvent.setup();
+ let finish!: (u: AuthUser) => void;
+ vi.spyOn(authService, 'login').mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ })
+ );
+ renderLogin();
+
+ await user.click(screen.getByRole('button', { name: /Admin Toàn Quyền/i }));
+ await user.click(submitButton());
+
+ expect(usernameInput()).toBeDisabled();
+ expect(passwordInput()).toBeDisabled();
+
+ finish(adminUser);
+ await waitFor(() => expect(screen.getByText('Home Page')).toBeInTheDocument());
+ });
+});
diff --git a/src/pages/LoginFailureAndSessionExpiration.test.tsx b/src/pages/LoginFailureAndSessionExpiration.test.tsx
new file mode 100644
index 0000000..29c3cfd
--- /dev/null
+++ b/src/pages/LoginFailureAndSessionExpiration.test.tsx
@@ -0,0 +1,251 @@
+// KAN-86: Test Login Failure and Session Expiration
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter, Route, Routes } from 'react-router-dom';
+import { LoginPage } from './LoginPage';
+import { AdminAuthGuard } from '../components/auth/AdminAuthGuard';
+import { authService } from '../services/authService';
+import { apiClient } from '../services/api';
+
+vi.mock('../services/api', () => ({
+ apiClient: { post: vi.fn(), get: vi.fn() },
+}));
+
+const postMock = vi.mocked(apiClient.post);
+
+function backendReplies(user: Record, token = 'backend-token') {
+ postMock.mockResolvedValue({ data: { success: true, data: { token, user } } });
+}
+
+function renderApp(entry: string) {
+ return render(
+
+
+ } />
+ Home Page} />
+ }>
+ Ships Page} />
+
+
+
+ );
+}
+
+async function signIn(user: ReturnType, username: string, password: string) {
+ await user.type(screen.getByLabelText(/Tên đăng nhập/i), username);
+ await user.type(screen.getByLabelText('Mật khẩu xác thực'), password);
+ await user.click(screen.getByRole('button', { name: /Đăng nhập Vận Hành/i }));
+}
+
+const startSession = () =>
+ authService.setSession('token', { id: 1, username: 'u', fullName: 'U', role: 'SYSTEM_ADMIN' });
+
+describe('KAN-86 Test Login Failure and Session Expiration: login failure', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ postMock.mockReset();
+ // default: backend is not running, so only demo accounts can sign in
+ postMock.mockRejectedValue(new Error('Network Error'));
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('shows an error and creates no session on a wrong password', async () => {
+ const user = userEvent.setup();
+ renderApp('/login');
+
+ await signIn(user, 'admin', 'wrong-password');
+
+ await waitFor(() =>
+ expect(screen.getByRole('alert')).toHaveTextContent(/Tên đăng nhập hoặc mật khẩu không chính xác/i)
+ );
+ expect(screen.getByRole('button', { name: /Đăng nhập Vận Hành/i })).toBeEnabled();
+ expect(authService.isAuthenticated()).toBe(false);
+ expect(screen.queryByText('Home Page')).not.toBeInTheDocument();
+ });
+
+ it('rejects an unknown username', async () => {
+ const user = userEvent.setup();
+ renderApp('/login');
+
+ await signIn(user, 'nobody', 'whatever');
+
+ await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(/không chính xác/i));
+ });
+
+ it('treats the password as case sensitive', async () => {
+ const user = userEvent.setup();
+ renderApp('/login');
+
+ await signIn(user, 'admin', 'ADMIN123');
+
+ await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());
+ expect(authService.isAuthenticated()).toBe(false);
+ });
+
+ it('shows an error when the backend answers 401', async () => {
+ postMock.mockRejectedValue({ response: { status: 401 } });
+ const user = userEvent.setup();
+ renderApp('/login');
+
+ await signIn(user, 'admin', 'wrong');
+
+ await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(/không chính xác/i));
+ });
+
+ it('does not create a session when the backend returns no user', async () => {
+ postMock.mockResolvedValue({ data: { success: true, data: { token: 'abc' } } });
+ const user = userEvent.setup();
+ renderApp('/login');
+
+ await signIn(user, 'nobody', 'whatever');
+
+ await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());
+ expect(localStorage.getItem('authToken')).toBeNull();
+ });
+
+ it('rejects passenger accounts with their own message', async () => {
+ backendReplies({ id: 9, username: 'guest', fullName: 'Guest', role: 'PASSENGER' });
+ const user = userEvent.setup();
+ renderApp('/login');
+
+ await signIn(user, 'guest', 'guest123');
+
+ await waitFor(() =>
+ expect(screen.getByRole('alert')).toHaveTextContent(/hành khách không có quyền truy cập/i)
+ );
+ expect(localStorage.getItem('authToken')).toBeNull();
+ });
+
+ it('clears the error when a demo account is picked', async () => {
+ const user = userEvent.setup();
+ renderApp('/login');
+
+ await signIn(user, 'x', 'y');
+ await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());
+
+ await user.click(screen.getByRole('button', { name: /Ops Manager/i }));
+ expect(screen.queryByRole('alert')).not.toBeInTheDocument();
+ });
+
+ it('allows signing in again after a failed attempt', async () => {
+ const user = userEvent.setup();
+ renderApp('/login');
+
+ await signIn(user, 'admin', 'wrong');
+ await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());
+
+ await user.click(screen.getByRole('button', { name: /Admin Toàn Quyền/i }));
+ await user.click(screen.getByRole('button', { name: /Đăng nhập Vận Hành/i }));
+
+ await waitFor(() => expect(screen.getByText('Home Page')).toBeInTheDocument());
+ expect(authService.getCurrentUser()?.username).toBe('admin');
+ });
+
+ it('stores the token and user returned by the backend', async () => {
+ backendReplies({ id: 5, username: 'crew', fullName: 'Crew', role: 'POS_STAFF' });
+ const user = userEvent.setup();
+ renderApp('/login');
+
+ await signIn(user, 'crew', 'password');
+
+ await waitFor(() => expect(screen.getByText('Home Page')).toBeInTheDocument());
+ expect(localStorage.getItem('authToken')).toBe('backend-token');
+ expect(authService.getCurrentUser()?.role).toBe('POS_STAFF');
+ });
+
+ it('trims and lowercases the username before signing in', async () => {
+ const user = userEvent.setup();
+ renderApp('/login');
+
+ await signIn(user, ' ADMIN ', 'admin123');
+
+ await waitFor(() => expect(screen.getByText('Home Page')).toBeInTheDocument());
+ expect(authService.getCurrentUser()?.username).toBe('admin');
+ });
+});
+
+describe('KAN-86 Test Login Failure and Session Expiration: session expiration', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ postMock.mockReset();
+ postMock.mockRejectedValue(new Error('Network Error'));
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('logout clears the token and user from both storages', async () => {
+ startSession();
+ sessionStorage.setItem('authToken', 'other-token');
+ sessionStorage.setItem('currentUser', '{}');
+ postMock.mockResolvedValue({});
+
+ await authService.logout();
+
+ expect(postMock).toHaveBeenCalledWith('/auth/logout');
+ expect(localStorage.getItem('authToken')).toBeNull();
+ expect(localStorage.getItem('currentUser')).toBeNull();
+ expect(sessionStorage.getItem('authToken')).toBeNull();
+ expect(sessionStorage.getItem('currentUser')).toBeNull();
+ });
+
+ it('logout still clears the session when the server is unreachable', async () => {
+ startSession();
+
+ await expect(authService.logout()).resolves.toBeUndefined();
+
+ expect(authService.isAuthenticated()).toBe(false);
+ });
+
+ it('is not authenticated once the token or the user is gone', () => {
+ startSession();
+ localStorage.removeItem('authToken');
+ expect(authService.isAuthenticated()).toBe(false);
+
+ startSession();
+ localStorage.removeItem('currentUser');
+ expect(authService.isAuthenticated()).toBe(false);
+ });
+
+ it('returns null instead of crashing when the stored user is corrupted', () => {
+ localStorage.setItem('authToken', 'token');
+ localStorage.setItem('currentUser', '{not-json');
+
+ expect(authService.getCurrentUser()).toBeNull();
+ expect(authService.isAuthenticated()).toBe(false);
+ });
+
+ it('sends a signed-out user to login, then back to the page they wanted', async () => {
+ const user = userEvent.setup();
+ renderApp('/ships?tab=1');
+
+ expect(screen.getByText('CRUISE MANAGER')).toBeInTheDocument();
+ expect(screen.queryByText('Ships Page')).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole('button', { name: /Admin Toàn Quyền/i }));
+ await user.click(screen.getByRole('button', { name: /Đăng nhập Vận Hành/i }));
+
+ await waitFor(() => expect(screen.getByText('Ships Page')).toBeInTheDocument());
+ });
+
+ it('blocks a protected page after the session is removed', () => {
+ startSession();
+ const first = renderApp('/ships');
+ expect(screen.getByText('Ships Page')).toBeInTheDocument();
+ first.unmount();
+
+ localStorage.removeItem('authToken');
+ localStorage.removeItem('currentUser');
+ renderApp('/ships');
+
+ expect(screen.getByText('CRUISE MANAGER')).toBeInTheDocument();
+ expect(screen.queryByText('Ships Page')).not.toBeInTheDocument();
+ });
+});
diff --git a/src/services/handleAuthenticationExpiration.test.ts b/src/services/handleAuthenticationExpiration.test.ts
new file mode 100644
index 0000000..6ad5502
--- /dev/null
+++ b/src/services/handleAuthenticationExpiration.test.ts
@@ -0,0 +1,148 @@
+// KAN-83: Handle Authentication Expiration
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import axios, {
+ AxiosError,
+ type AxiosAdapter,
+ type AxiosResponse,
+ type InternalAxiosRequestConfig,
+} from 'axios';
+import { installAuthExpirationHandler } from './handleAuthenticationExpiration';
+
+const failWith =
+ (status: number): AxiosAdapter =>
+ (config: InternalAxiosRequestConfig) => {
+ const response = { data: {}, status, statusText: '', headers: {}, config } as AxiosResponse;
+ return Promise.reject(new AxiosError('Request failed', 'ERR_BAD_REQUEST', config, null, response));
+ };
+
+const succeed: AxiosAdapter = (config) =>
+ Promise.resolve({ data: { ok: true }, status: 200, statusText: 'OK', headers: {}, config } as AxiosResponse);
+
+function setup(adapter: AxiosAdapter, location = '/pos?tab=1') {
+ const client = axios.create({ adapter });
+ const redirect = vi.fn();
+ const remove = installAuthExpirationHandler(client, { redirect, getLocation: () => location });
+ return { client, redirect, remove };
+}
+
+function startSession() {
+ localStorage.setItem('authToken', 'secret-token');
+ localStorage.setItem('currentUser', JSON.stringify({ username: 'admin' }));
+}
+
+describe('KAN-83 Handle Authentication Expiration: installAuthExpirationHandler', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('clears the session and redirects to login with the current page on 401', async () => {
+ startSession();
+ const { client, redirect } = setup(failWith(401));
+
+ await expect(client.get('/ships')).rejects.toBeDefined();
+
+ expect(localStorage.getItem('authToken')).toBeNull();
+ expect(localStorage.getItem('currentUser')).toBeNull();
+ expect(redirect).toHaveBeenCalledTimes(1);
+ const target = String(redirect.mock.calls[0][0]);
+ expect(target).toContain('/login?reason=expired');
+ expect(target).toContain(encodeURIComponent('/pos?tab=1'));
+ });
+
+ it('also clears a session stored in sessionStorage', async () => {
+ sessionStorage.setItem('authToken', 'secret-token');
+ sessionStorage.setItem('currentUser', JSON.stringify({ username: 'admin' }));
+ const { client } = setup(failWith(401));
+
+ await expect(client.get('/ships')).rejects.toBeDefined();
+
+ expect(sessionStorage.getItem('authToken')).toBeNull();
+ expect(sessionStorage.getItem('currentUser')).toBeNull();
+ });
+
+ it('logs the expiry without leaking the token', async () => {
+ startSession();
+ const { client } = setup(failWith(401));
+
+ await expect(client.get('/ships')).rejects.toBeDefined();
+
+ const raw = String(vi.mocked(console.warn).mock.calls[0][0]);
+ expect(JSON.parse(raw)).toMatchObject({ event: 'auth.session_expired', path: '/pos' });
+ expect(raw).not.toContain('secret-token');
+ });
+
+ it('redirects only once when several requests fail together', async () => {
+ startSession();
+ const { client, redirect } = setup(failWith(401));
+
+ await Promise.allSettled([client.get('/a'), client.get('/b'), client.get('/c')]);
+
+ expect(redirect).toHaveBeenCalledTimes(1);
+ });
+
+ it('only clears the session when already on the login page', async () => {
+ startSession();
+ const { client, redirect } = setup(failWith(401), '/login?redirect=%2Fpos');
+
+ await expect(client.get('/ships')).rejects.toBeDefined();
+
+ expect(localStorage.getItem('authToken')).toBeNull();
+ expect(redirect).not.toHaveBeenCalled();
+ });
+
+ it.each(['/auth/login', '/auth/logout'])('ignores 401 from %s', async (path) => {
+ startSession();
+ const { client, redirect } = setup(failWith(401));
+
+ await expect(client.post(path, {})).rejects.toBeDefined();
+
+ expect(localStorage.getItem('authToken')).toBe('secret-token');
+ expect(redirect).not.toHaveBeenCalled();
+ });
+
+ it('does nothing when there is no session', async () => {
+ const { client, redirect } = setup(failWith(401));
+
+ await expect(client.get('/ships')).rejects.toBeDefined();
+
+ expect(redirect).not.toHaveBeenCalled();
+ expect(console.warn).not.toHaveBeenCalled();
+ });
+
+ it.each([403, 500])('keeps the session on a %i error', async (status) => {
+ startSession();
+ const { client, redirect } = setup(failWith(status));
+
+ await expect(client.get('/ships')).rejects.toBeDefined();
+
+ expect(localStorage.getItem('authToken')).toBe('secret-token');
+ expect(redirect).not.toHaveBeenCalled();
+ });
+
+ it('passes successful responses through', async () => {
+ startSession();
+ const { client, redirect } = setup(succeed);
+
+ const res = await client.get('/ships');
+
+ expect(res.data).toEqual({ ok: true });
+ expect(redirect).not.toHaveBeenCalled();
+ });
+
+ it('stops handling 401 after the handler is removed', async () => {
+ startSession();
+ const { client, redirect, remove } = setup(failWith(401));
+ remove();
+
+ await expect(client.get('/ships')).rejects.toBeDefined();
+
+ expect(localStorage.getItem('authToken')).toBe('secret-token');
+ expect(redirect).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/services/handleAuthenticationExpiration.ts b/src/services/handleAuthenticationExpiration.ts
new file mode 100644
index 0000000..c2154bc
--- /dev/null
+++ b/src/services/handleAuthenticationExpiration.ts
@@ -0,0 +1,47 @@
+// KAN-83: Handle Authentication Expiration
+import type { AxiosInstance } from 'axios';
+
+const AUTH_ENDPOINTS = ['/auth/login', '/auth/logout'];
+
+interface Options {
+ loginPath?: string;
+ getLocation?: () => string;
+ redirect?: (url: string) => void;
+}
+
+export function clearAuthSession(): void {
+ ['authToken', 'currentUser'].forEach((key) => {
+ localStorage.removeItem(key);
+ sessionStorage.removeItem(key);
+ });
+}
+
+export function installAuthExpirationHandler(client: AxiosInstance, options: Options = {}) {
+ const loginPath = options.loginPath ?? '/login';
+ const getLocation = options.getLocation ?? (() => window.location.pathname + window.location.search);
+ const redirect = options.redirect ?? ((url: string) => window.location.assign(url));
+
+ const id = client.interceptors.response.use(
+ (response) => response,
+ (error) => {
+ const url = String(error?.config?.url ?? '');
+ const isAuthCall = AUTH_ENDPOINTS.some((path) => url.includes(path));
+ const hasToken = localStorage.getItem('authToken') || sessionStorage.getItem('authToken');
+
+ // A 401 from login/logout means bad credentials, not an expired session
+ if (error?.response?.status === 401 && !isAuthCall && hasToken) {
+ clearAuthSession();
+ const current = getLocation();
+ console.warn(
+ JSON.stringify({ level: 'warn', event: 'auth.session_expired', path: current.split('?')[0] }),
+ );
+ if (!current.startsWith(loginPath)) {
+ redirect(`${loginPath}?reason=expired&redirect=${encodeURIComponent(current)}`);
+ }
+ }
+ return Promise.reject(error);
+ },
+ );
+
+ return () => client.interceptors.response.eject(id);
+}