diff --git a/.env b/.env index 8addcb2..8397771 100644 --- a/.env +++ b/.env @@ -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 diff --git a/.env.example b/.env.example index 8addcb2..8397771 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/docs/KAN-66-RBAC.md b/docs/KAN-66-RBAC.md new file mode 100644 index 0000000..f2d0b9a --- /dev/null +++ b/docs/KAN-66-RBAC.md @@ -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. diff --git a/src/App.test.tsx b/src/App.test.tsx index 72a27ba..df66724 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -132,7 +132,7 @@ describe('App Routing Integration Tests', () => { }); }); - it('renders NotFoundPage when navigating to an unknown route', async () => { + it('denies an unclassified protected route', async () => { render( @@ -140,9 +140,8 @@ describe('App Routing Integration Tests', () => { ); 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', '/'); }); }); diff --git a/src/App.tsx b/src/App.tsx index 92d738a..6c1378e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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'; @@ -68,7 +70,9 @@ export function App() { {/* Protected Maritime Operations & Administrative Fleet Console */} }> + }> }> + } /> } /> } /> } /> @@ -101,6 +105,7 @@ export function App() { } /> } /> + ); diff --git a/src/ProtectedRoutes.app.test.tsx b/src/ProtectedRoutes.app.test.tsx index 5b40572..8a1f3f1 100644 --- a/src/ProtectedRoutes.app.test.tsx +++ b/src/ProtectedRoutes.app.test.tsx @@ -92,11 +92,11 @@ describe('KAN-82, KAN-85 Protected routes in App', () => { }); it.each(['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(); } ); @@ -104,7 +104,7 @@ describe('KAN-82, KAN-85 Protected routes in App', () => { 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(); }); @@ -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(); }); }); }); diff --git a/src/components/auth/AdminAuthGuard.tsx b/src/components/auth/AdminAuthGuard.tsx index d581048..c68bce8 100644 --- a/src/components/auth/AdminAuthGuard.tsx +++ b/src/components/auth/AdminAuthGuard.tsx @@ -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 ; diff --git a/src/components/auth/RouteAccessGuard.test.tsx b/src/components/auth/RouteAccessGuard.test.tsx new file mode 100644 index 0000000..15c33e7 --- /dev/null +++ b/src/components/auth/RouteAccessGuard.test.tsx @@ -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( + Login required} /> + }>}> + Operations dashboard} /> + Cashier workspace} /> + Identity administration} /> + Shore roster} /> + Activity check-in} /> + Forbidden} /> + + ); +} + +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); + }); +}); diff --git a/src/components/auth/RouteAccessGuard.tsx b/src/components/auth/RouteAccessGuard.tsx new file mode 100644 index 0000000..5128b61 --- /dev/null +++ b/src/components/auth/RouteAccessGuard.tsx @@ -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 ; + return ; +} diff --git a/src/components/ui/CommandPaletteModal.tsx b/src/components/ui/CommandPaletteModal.tsx index 377f665..ddec7e3 100644 --- a/src/components/ui/CommandPaletteModal.tsx +++ b/src/components/ui/CommandPaletteModal.tsx @@ -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, @@ -143,16 +145,18 @@ export const CommandPaletteModal: React.FC = ({ 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); diff --git a/src/components/ui/ReactiveUiSuite.test.tsx b/src/components/ui/ReactiveUiSuite.test.tsx index 6c1f014..c613f03 100644 --- a/src/components/ui/ReactiveUiSuite.test.tsx +++ b/src/components/ui/ReactiveUiSuite.test.tsx @@ -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', () => { @@ -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( diff --git a/src/layouts/MainLayout.test.tsx b/src/layouts/MainLayout.test.tsx index a4d93f9..42920fb 100644 --- a/src/layouts/MainLayout.test.tsx +++ b/src/layouts/MainLayout.test.tsx @@ -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(), @@ -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(() => { diff --git a/src/layouts/MainLayout.tsx b/src/layouts/MainLayout.tsx index 8171df1..4243cb9 100644 --- a/src/layouts/MainLayout.tsx +++ b/src/layouts/MainLayout.tsx @@ -21,6 +21,7 @@ import { 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'; @@ -32,10 +33,10 @@ export function MainLayout() { const [isCommandOpen, setIsCommandOpen] = useState(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 () => { @@ -73,7 +74,6 @@ export function MainLayout() { 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' }, @@ -88,14 +88,11 @@ export function MainLayout() { { 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 (
{ 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(); } ); @@ -53,7 +53,17 @@ describe('MainLayout role-based menu', () => { 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(); + }); }); diff --git a/src/pages/ForbiddenPage.tsx b/src/pages/ForbiddenPage.tsx new file mode 100644 index 0000000..bbd238c --- /dev/null +++ b/src/pages/ForbiddenPage.tsx @@ -0,0 +1,16 @@ +import { Link } from 'react-router-dom'; +import { authService } from '../services/authService'; +import { homeForRole } from '../services/accessControl'; + +export function ForbiddenPage() { + return ( +
+

403

+

Bạn không có quyền truy cập

+

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.

+ + Về trang làm việc + +
+ ); +} diff --git a/src/pages/LoginFailureAndSessionExpiration.test.tsx b/src/pages/LoginFailureAndSessionExpiration.test.tsx index 29c3cfd..2f7cf99 100644 --- a/src/pages/LoginFailureAndSessionExpiration.test.tsx +++ b/src/pages/LoginFailureAndSessionExpiration.test.tsx @@ -8,9 +8,13 @@ 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() }, -})); +vi.mock('../services/api', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + apiClient: { post: vi.fn(), get: vi.fn() }, + }; +}); const postMock = vi.mocked(apiClient.post); diff --git a/src/pages/PassengersPage.test.tsx b/src/pages/PassengersPage.test.tsx index 6445367..49d89de 100644 --- a/src/pages/PassengersPage.test.tsx +++ b/src/pages/PassengersPage.test.tsx @@ -1,9 +1,21 @@ -import { describe, it, expect, vi } from 'vitest'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { PassengersPage } from './PassengersPage'; +import { authService } from '../services/authService'; describe('PassengersPage (Component & User Interaction Tests)', () => { + beforeEach(() => { + authService.setSession('domain-test-admin', { id: 1, username: 'admin', fullName: 'Test Admin', role: 'SYSTEM_ADMIN' }); + }); + + it('keeps passenger mutation controls disabled for read-only staff', () => { + authService.setSession('token', { id: 3, username: 'activity', fullName: 'Activity', role: 'ACTIVITY_MANAGER' }); + render(); + expect(screen.getByRole('button', { name: 'Đăng Ký Khách' })).toBeDisabled(); + expect(screen.getAllByRole('combobox', { name: /Đổi trạng thái đăng ký/ })[0]).toBeDisabled(); + expect(screen.getAllByRole('button', { name: /Đã lên tàu|Chưa check-in/ })[0]).toBeDisabled(); + }); it('renders passenger table header and all initial passengers', () => { render(); diff --git a/src/pages/PassengersPage.tsx b/src/pages/PassengersPage.tsx index 9e012b8..977d657 100644 --- a/src/pages/PassengersPage.tsx +++ b/src/pages/PassengersPage.tsx @@ -25,8 +25,11 @@ import { } from '../services/passengerService'; import { getTours, INITIAL_TOURS, type CruiseTour } from '../services/tourService'; import { RegisterPassengerModal } from '../components/passengers/RegisterPassengerModal'; +import { authService } from '../services/authService'; +import { hasPermission } from '../services/accessControl'; export function PassengersPage() { + const canManage = hasPermission(authService.getCurrentUser()?.role, 'PASSENGERS_MANAGE'); const [tours, setTours] = useState(INITIAL_TOURS); const [selectedTourId, setSelectedTourId] = useState(1); const [searchTerm, setSearchTerm] = useState(''); @@ -120,6 +123,7 @@ export function PassengersPage() { }; const handleCheckInToggle = async (passenger: Passenger) => { + if (!canManage) return; const nextStatus = passenger.checkInStatus === 'BOARDED' ? 'NOT_CHECKED_IN' : 'BOARDED'; try { await updateCheckInStatus(passenger.id, nextStatus); @@ -131,6 +135,7 @@ export function PassengersPage() { }; const handleRegistrationStatusChange = async (passengerId: number, status: RegistrationStatus) => { + if (!canManage) return; try { await updateRegistrationStatus(passengerId, status); showToast('Đã cập nhật trạng thái đăng ký thành công!'); @@ -141,6 +146,7 @@ export function PassengersPage() { }; const handleRegisterSuccess = async (payload: RegisterPassengerPayload) => { + if (!canManage) return; await registerPassenger(payload); showToast(`Đã đăng ký thành công cho hành khách ${payload.fullName}!`); void loadPassengers(); @@ -202,6 +208,7 @@ export function PassengersPage() {