Skip to content
Open
6 changes: 3 additions & 3 deletions .env
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
VITE_API_BASE_URL=http://localhost:8080/api
VITE_APP_TITLE=Cruise Activity and Service Management System
VITE_APP_VERSION=1.0.0
VITE_API_BASE_URL=/api
VITE_APP_TITLE=Cruise Activity and Service Management System
VITE_APP_VERSION=1.0.0
6 changes: 3 additions & 3 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
VITE_API_BASE_URL=http://localhost:8080/api
VITE_APP_TITLE=Cruise Activity and Service Management System
VITE_APP_VERSION=1.0.0
VITE_API_BASE_URL=/api
VITE_APP_TITLE=Cruise Activity and Service Management System
VITE_APP_VERSION=1.0.0
27 changes: 27 additions & 0 deletions docs/KAN-66-RBAC.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# KAN-66 — Phân quyền giao diện

Phần web đồng bộ 8 role và permission với `Cruise-api` trong
`src/services/accessControl.ts`. Route guard, sidebar và command palette dùng
chung ma trận này. Backend vẫn là nơi quyết định quyền đối với từng API.

- Người dùng không đủ quyền vào URL trực tiếp được chuyển tới trang 403.
- Nhân viên POS vào `/` được chuyển tới `/pos`; các role khác có trang làm việc
tương ứng, tránh điều hướng lặp ở dashboard vận hành.
- Các thao tác đăng ký, đổi trạng thái và check-in hành khách bị khóa đối với
nhân viên chỉ có quyền đọc danh sách.
- Login gửi `usernameOrEmail`, lấy `accessToken`; request interceptor gửi Bearer
token. Response 401 xóa phiên và về login, 403 chuyển sang trang báo thiếu quyền,
kể cả khi service nghiệp vụ có fallback dữ liệu demo.
- `/api` là mặc định. Vite proxy tới đúng microservice ở localhost:8081–8084;
system health/info tới 8080. Production cần reverse proxy tương ứng hoặc cấu
hình `VITE_API_BASE_URL`. Gateway hiện tại chỉ có các endpoint giám sát hệ thống.
- Tài khoản demo chỉ bật ở development khi có
`VITE_ENABLE_DEMO_ACCOUNTS=true` hoặc trong test. Token demo không được API chấp nhận.

Kiểm tra local ngày 02/11/2026: 736 Vitest test (107 file) pass, bộ test script
Jules pass, lint exit 0 (còn warning của repo), TypeScript và production build pass.
Lệnh chạy: `npm ci`, `npx vitest run --maxWorkers=2`, `npm run test:jules`,
`npm run lint`, `npm run build`.

Chi tiết quyền API, bảng audit và giới hạn revocation nằm trong
`Cruise-api/docs/KAN-66-RBAC.md`. Chưa nghiệm thu staging hoặc chạy GitHub CI.
7 changes: 3 additions & 4 deletions src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,17 +132,16 @@ describe('App Routing Integration Tests', () => {
});
});

it('renders NotFoundPage when navigating to an unknown route', async () => {
it('denies an unclassified protected route', async () => {
render(
<MemoryRouter initialEntries={['/invalid-random-route']}>
<App />
</MemoryRouter>
);

await waitFor(() => {
expect(screen.getByRole('heading', { level: 2, name: '404' })).toBeInTheDocument();
expect(screen.getByText('Trang không tồn tại')).toBeInTheDocument();
expect(screen.getByRole('link', { name: /Về Trang Chủ/i })).toHaveAttribute('href', '/');
expect(screen.getByRole('heading', { name: 'Bạn không có quyền truy cập' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Về trang làm việc' })).toHaveAttribute('href', '/');
});
});

Expand Down
5 changes: 5 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { MainLayout } from './layouts/MainLayout';
import { PassengerLayout } from './layouts/PassengerLayout';
import { AdminAuthGuard } from './components/auth/AdminAuthGuard';
import { RoleGuard } from './components/auth/RoleGuard';
import { RouteAccessGuard } from './components/auth/RouteAccessGuard';
import { ForbiddenPage } from './pages/ForbiddenPage';
import { LoginPage } from './pages/LoginPage';
import { DashboardPage } from './pages/DashboardPage';
import { ActivitiesPage } from './pages/ActivitiesPage';
Expand Down Expand Up @@ -68,7 +70,9 @@ export function App() {

{/* Protected Maritime Operations & Administrative Fleet Console */}
<Route element={<AdminAuthGuard />}>
<Route element={<RouteAccessGuard />}>
<Route path="/" element={<MainLayout />}>
<Route path="forbidden" element={<ForbiddenPage />} />
<Route index element={<DashboardPage />} />
<Route path="ships" element={<ShipsPage />} />
<Route path="ships/:id" element={<ShipDetailPage />} />
Expand Down Expand Up @@ -101,6 +105,7 @@ export function App() {
<Route path="provider-settlement" element={<ProviderSettlementDashboard />} />
<Route path="*" element={<NotFoundPage />} />
</Route>
</Route>
</Route>
</Routes>
);
Expand Down
10 changes: 5 additions & 5 deletions src/ProtectedRoutes.app.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,19 +92,19 @@ describe('KAN-82, KAN-85 Protected routes in App', () => {
});

it.each<StaffRole>(['OPERATIONS_MANAGER', 'ITINERARY_COORDINATOR', 'SHORE_EXCURSION_MANAGER', 'POS_STAFF'])(
'keeps %s out of /users and shows the dashboard',
'keeps %s out of /users and shows forbidden page',
(role) => {
loginAs(role);
renderAt('/users');
expect(screen.getByText('Dashboard Page')).toBeInTheDocument();
expect(screen.getByText('Bạn không có quyền truy cập')).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.getByText('Bạn không có quyền truy cập')).toBeInTheDocument();
expect(screen.queryByText('User Detail Page')).not.toBeInTheDocument();
});

Expand All @@ -121,10 +121,10 @@ describe('KAN-82, KAN-85 Protected routes in App', () => {
expect(screen.queryByText('Users Page')).not.toBeInTheDocument();
});

it('shows the 404 page for unknown paths', () => {
it('denies unknown paths for signed-in staff', () => {
loginAs('SYSTEM_ADMIN');
renderAt('/does-not-exist');
expect(screen.getByText('Not Found Page')).toBeInTheDocument();
expect(screen.getByText('Bạn không có quyền truy cập')).toBeInTheDocument();
});
});
});
20 changes: 18 additions & 2 deletions src/components/auth/AdminAuthGuard.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
import React from 'react';
import { Navigate, Outlet, useLocation } from 'react-router-dom';
import React, { useEffect } from 'react';
import { Navigate, Outlet, useLocation, useNavigate } from 'react-router-dom';
import { authService } from '../../services/authService';
import { ACCESS_DENIED_EVENT } from '../../services/api';

export const AdminAuthGuard: React.FC = () => {
const location = useLocation();
const navigate = useNavigate();
const isStaff = authService.isStaff();

useEffect(() => {
const onDenied = (event: Event) => {
const status = (event as CustomEvent<{ status: number }>).detail.status;
if (status === 401) {
authService.clearSession();
navigate('/login', { replace: true });
} else {
navigate('/forbidden', { replace: true });
}
};
window.addEventListener(ACCESS_DENIED_EVENT, onDenied);
return () => window.removeEventListener(ACCESS_DENIED_EVENT, onDenied);
}, [navigate]);

if (!isStaff) {
const returnUrl = encodeURIComponent(location.pathname + location.search);
return <Navigate to={`/login?redirect=${returnUrl}`} replace />;
Comment thread
huytran2005 marked this conversation as resolved.
Resolved
Expand Down
76 changes: 76 additions & 0 deletions src/components/auth/RouteAccessGuard.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { act, render, screen } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { AdminAuthGuard } from './AdminAuthGuard';
import { RouteAccessGuard } from './RouteAccessGuard';
import { authService, type StaffRole } from '../../services/authService';
import { ACCESS_DENIED_EVENT } from '../../services/api';

function open(path: string, role?: StaffRole) {
if (role) authService.setSession('token', { id: 1, username: 'actor', fullName: 'Actor', role });
render(<MemoryRouter initialEntries={[path]}><Routes>
<Route path="/login" element={<div>Login required</div>} />
<Route element={<AdminAuthGuard />}><Route element={<RouteAccessGuard />}>
<Route path="/" element={<div>Operations dashboard</div>} />
<Route path="/pos" element={<div>Cashier workspace</div>} />
<Route path="/users" element={<div>Identity administration</div>} />
<Route path="/excursions/:id/roster" element={<div>Shore roster</div>} />
<Route path="/activities/:id/attendance" element={<div>Activity check-in</div>} />
<Route path="/forbidden" element={<div>Forbidden</div>} />
</Route></Route>
</Routes></MemoryRouter>);
}

describe('KAN-72 direct route authorization', () => {
beforeEach(() => { localStorage.clear(); sessionStorage.clear(); });
it.each(['POS_STAFF', 'OPERATIONS_MANAGER', 'ACTIVITY_MANAGER', 'SHORE_EXCURSION_MANAGER',
'ITINERARY_COORDINATOR', 'FINANCE_FRONT_DESK'] as StaffRole[])(
'blocks %s from opening user administration by URL', role => {
open('/users', role);
expect(screen.getByText('Forbidden')).toBeInTheDocument();
expect(screen.queryByText('Identity administration')).not.toBeInTheDocument();
},
);
it('allows administrator user management', () => {
open('/users', 'SYSTEM_ADMIN');
expect(screen.getByText('Identity administration')).toBeInTheDocument();
});
it('sends a cashier to the authorized landing page instead of an operations dashboard', () => {
open('/', 'POS_STAFF');
expect(screen.getByText('Cashier workspace')).toBeInTheDocument();
expect(screen.queryByText('Operations dashboard')).not.toBeInTheDocument();
});
it.each([
['/excursions/7/roster', 'SHORE_EXCURSION_MANAGER', 'Shore roster'],
['/activities/7/attendance', 'ACTIVITY_MANAGER', 'Activity check-in'],
] as const)('permits the owning role at %s', (path, role, content) => {
open(path, role);
expect(screen.getByText(content)).toBeInTheDocument();
});
it.each([
['/excursions/7/roster', 'ACTIVITY_MANAGER'], ['/activities/7/attendance', 'SHORE_EXCURSION_MANAGER'],
] as const)('rejects cross-role deep link %s for %s', (path, role) => {
open(path, role);
expect(screen.getByText('Forbidden')).toBeInTheDocument();
});
it('requires login for an anonymous deep link', () => {
open('/users');
expect(screen.getByText('Login required')).toBeInTheDocument();
});
it('does not accept a forged unknown staff role in local storage', () => {
open('/users', 'ADMIN' as StaffRole);
expect(screen.getByText('Login required')).toBeInTheDocument();
});
it('leaves an allowed page when the backend denies a mutation', () => {
open('/pos', 'POS_STAFF');
act(() => window.dispatchEvent(new CustomEvent(ACCESS_DENIED_EVENT, { detail: { status: 403 } })));
expect(screen.getByText('Forbidden')).toBeInTheDocument();
expect(screen.queryByText('Cashier workspace')).not.toBeInTheDocument();
});
it('clears an expired session and returns to login on a backend 401', () => {
open('/pos', 'POS_STAFF');
act(() => window.dispatchEvent(new CustomEvent(ACCESS_DENIED_EVENT, { detail: { status: 401 } })));
expect(screen.getByText('Login required')).toBeInTheDocument();
expect(authService.isAuthenticated()).toBe(false);
});
});
10 changes: 10 additions & 0 deletions src/components/auth/RouteAccessGuard.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Navigate, Outlet, useLocation } from 'react-router-dom';
import { authService } from '../../services/authService';
import { canAccessPath, homeForRole } from '../../services/accessControl';

export function RouteAccessGuard() {
const { pathname } = useLocation();
const role = authService.getCurrentUser()?.role;
if (canAccessPath(role, pathname)) return <Outlet />;
return <Navigate to={pathname === '/' ? homeForRole(role) : '/forbidden'} replace />;
}
10 changes: 7 additions & 3 deletions src/components/ui/CommandPaletteModal.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import React, { useEffect, useState, useMemo, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useFocusTrap } from '../../hooks/useFocusTrap';
import { authService } from '../../services/authService';
import { canAccessPath } from '../../services/accessControl';
import {
Search,
Compass,
Expand Down Expand Up @@ -143,16 +145,18 @@ export const CommandPaletteModal: React.FC<CommandPaletteModalProps> = ({

useFocusTrap(isOpen, modalRef, onClose);

const role = authService.getCurrentUser()?.role;
const filteredItems = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return ADMIN_COMMAND_ITEMS;
return ADMIN_COMMAND_ITEMS.filter(
const permitted = ADMIN_COMMAND_ITEMS.filter(item => canAccessPath(role, item.to));
if (!q) return permitted;
return permitted.filter(
(item) =>
item.label.toLowerCase().includes(q) ||
item.subtitle.toLowerCase().includes(q) ||
item.category.toLowerCase().includes(q)
);
}, [query]);
}, [query, role]);

useEffect(() => {
setActiveIndex(0);
Expand Down
2 changes: 2 additions & 0 deletions src/components/ui/ReactiveUiSuite.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ShinyText, DecryptedText } from './ShinyText';
import { Magnet } from './Magnet';
import { MaritimeGlobe3D } from './MaritimeGlobe3D';
import { CommandPaletteModal } from './CommandPaletteModal';
import { authService } from '../../services/authService';

describe('React Bits, Three.js & UI/UX Pro Max Suite', () => {
it('renders SpotlightCard and tracks cursor hover state', () => {
Expand Down Expand Up @@ -68,6 +69,7 @@ describe('React Bits, Three.js & UI/UX Pro Max Suite', () => {
});

it('renders CommandPaletteModal, filters modules and closes on Escape', () => {
authService.setSession('domain-test-admin', { id: 1, username: 'admin', fullName: 'Test Admin', role: 'SYSTEM_ADMIN' });
const onClose = vi.fn();
render(
<MemoryRouter>
Expand Down
2 changes: 2 additions & 0 deletions src/layouts/MainLayout.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { MainLayout } from './MainLayout';
import * as apiModule from '../services/api';
import { authService } from '../services/authService';

vi.mock('../services/api', () => ({
checkBackendHealth: vi.fn(),
Expand All @@ -13,6 +14,7 @@ vi.mock('../services/api', () => ({
describe('MainLayout (Layout & Async State Tests)', () => {
beforeEach(() => {
vi.clearAllMocks();
authService.setSession('domain-test-admin', { id: 1, username: 'admin', fullName: 'Test Admin', role: 'SYSTEM_ADMIN' });
});

afterEach(() => {
Expand Down
17 changes: 7 additions & 10 deletions src/layouts/MainLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import { checkBackendHealth, getBackendInfo } from '../services/api';
import type { SystemHealth, SystemInfo } from '../services/api';
import { authService } from '../services/authService';
import { canAccessPath } from '../services/accessControl';
import { CommandPaletteModal } from '../components/ui/CommandPaletteModal';
import { SpotlightCard } from '../components/ui/SpotlightCard';

Expand All @@ -32,10 +33,10 @@
const [isCommandOpen, setIsCommandOpen] = useState<boolean>(false);

const currentUser = authService.getCurrentUser() || {
id: 1,
username: 'admin',
fullName: 'Huy Trần Gia',
role: 'SYSTEM_ADMIN' as const,
id: '',
username: '',
fullName: 'Chưa đăng nhập',
role: 'PASSENGER' as const,
};

const fetchStatus = async () => {
Expand All @@ -47,7 +48,7 @@
};

useEffect(() => {
fetchStatus();

Check warning on line 51 in src/layouts/MainLayout.tsx

View workflow job for this annotation

GitHub Actions / Build & Test (Node.js 22 / Vitest)

react(set-state-in-effect)

src/layouts/MainLayout.tsx:51:5: Calling setState synchronously within an effect can trigger cascading renders
const interval = setInterval(fetchStatus, 15000);
return () => clearInterval(interval);
}, []);
Expand All @@ -73,7 +74,6 @@
label: string;
icon: typeof Compass;
code: string;
roles?: string[];
}[] = [
{ to: '/', label: 'Dashboard Tổng quan', icon: Compass, code: '01' },
{ to: '/ships', label: 'Quản lý Đội tàu', icon: Ship, code: '02' },
Expand All @@ -88,14 +88,11 @@
{ to: '/embarkation', label: 'Cảng Đón Khách (Terminal)', icon: Ship, code: '11' },
{ to: '/billing/settlement', label: 'Tất toán & Hoá đơn', icon: Receipt, code: '12' },
{ to: '/reports/operational', label: 'Báo Cáo Doanh Thu (Audit)', icon: Receipt, code: '13' },
{ to: '/users', label: 'Quản lý Người dùng', icon: Users, code: '14', roles: ['SYSTEM_ADMIN'] },
{ to: '/users', label: 'Quản lý Người dùng', icon: Users, code: '14' },
];

// Mục có khai báo `roles` chỉ hiện cho tài khoản thuộc các vai trò đó
const sessionRole = authService.getCurrentUser()?.role;
const navItems = allNavItems.filter(
(item) => !item.roles || (sessionRole !== undefined && item.roles.includes(sessionRole))
);
const navItems = allNavItems.filter(item => canAccessPath(sessionRole, item.to));

return (
<div
Expand Down
14 changes: 12 additions & 2 deletions src/layouts/MainLayoutRoles.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,25 @@ describe('MainLayout role-based menu', () => {
async (role) => {
signInAs(role);
renderLayout();
expect(await screen.findByText('Quản lý Đội tàu')).toBeInTheDocument();
expect(await screen.findByText('CRUISE MANAGER')).toBeInTheDocument();
expect(screen.queryByText('Quản lý Người dùng')).not.toBeInTheDocument();
}
);

it('hides the menu when there is no signed-in user', async () => {
signInAs(null);
renderLayout();
expect(await screen.findByText('Quản lý Đội tàu')).toBeInTheDocument();
expect(await screen.findByText('CRUISE MANAGER')).toBeInTheDocument();
expect(screen.queryByText('Quản lý Đội tàu')).not.toBeInTheDocument();
expect(screen.queryByText('Quản lý Người dùng')).not.toBeInTheDocument();
});

it('limits a cashier menu to authorized workspaces', async () => {
signInAs('POS_STAFF');
renderLayout();
expect(await screen.findByText('POS & Chi tiêu Onboard')).toBeInTheDocument();
expect(screen.queryByText('Quản lý Đội tàu')).not.toBeInTheDocument();
expect(screen.queryByText('Tất toán & Hoá đơn')).not.toBeInTheDocument();
expect(screen.queryByText('Hoạt động & Excursion')).not.toBeInTheDocument();
});
});
16 changes: 16 additions & 0 deletions src/pages/ForbiddenPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Link } from 'react-router-dom';
import { authService } from '../services/authService';
import { homeForRole } from '../services/accessControl';

export function ForbiddenPage() {
return (
<section className="mx-auto max-w-xl p-6" aria-labelledby="forbidden-title">
<p className="text-sm font-mono">403</p>
<h1 id="forbidden-title" className="text-2xl font-semibold mt-2">Bạn không có quyền truy cập</h1>
<p className="mt-3">Vai trò của bạn không được phép mở chức năng này. Liên hệ quản trị viên nếu cần thay đổi quyền.</p>
<Link className="inline-block mt-6 underline" to={homeForRole(authService.getCurrentUser()?.role)}>
Về trang làm việc
</Link>
</section>
);
}
Loading
Loading