review
This commit is contained in:
parent
b173b47925
commit
66bc4c5a45
10 changed files with 367 additions and 320 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -12,7 +12,6 @@ node_modules/
|
||||||
|
|
||||||
# Env
|
# Env
|
||||||
.env
|
.env
|
||||||
.env
|
|
||||||
|
|
||||||
# IDE
|
# IDE
|
||||||
.idea/
|
.idea/
|
||||||
|
|
|
||||||
2
Makefile
2
Makefile
|
|
@ -51,4 +51,4 @@ test-frontend:
|
||||||
test-e2e:
|
test-e2e:
|
||||||
./scripts/e2e.sh
|
./scripts/e2e.sh
|
||||||
|
|
||||||
test: test-backend test-frontend
|
test: test-backend test-frontend test-e2e
|
||||||
|
|
|
||||||
|
|
@ -128,31 +128,6 @@ def require_permission(*required_permissions: Permission):
|
||||||
return permission_checker
|
return permission_checker
|
||||||
|
|
||||||
|
|
||||||
def require_any_permission(*required_permissions: Permission):
|
|
||||||
"""
|
|
||||||
Dependency factory that checks if user has ANY of the required permissions.
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
@app.get("/api/resource")
|
|
||||||
async def get_resource(user: User = Depends(require_any_permission(Permission.VIEW, Permission.ADMIN))):
|
|
||||||
...
|
|
||||||
"""
|
|
||||||
async def permission_checker(
|
|
||||||
request: Request,
|
|
||||||
db: AsyncSession = Depends(get_db),
|
|
||||||
) -> User:
|
|
||||||
user = await get_current_user(request, db)
|
|
||||||
user_permissions = await user.get_permissions(db)
|
|
||||||
|
|
||||||
if not any(p in user_permissions for p in required_permissions):
|
|
||||||
raise HTTPException(
|
|
||||||
status_code=status.HTTP_403_FORBIDDEN,
|
|
||||||
detail=f"Requires one of: {', '.join(p.value for p in required_permissions)}",
|
|
||||||
)
|
|
||||||
return user
|
|
||||||
return permission_checker
|
|
||||||
|
|
||||||
|
|
||||||
async def build_user_response(user: User, db: AsyncSession) -> UserResponse:
|
async def build_user_response(user: User, db: AsyncSession) -> UserResponse:
|
||||||
"""Build a UserResponse with roles and permissions."""
|
"""Build a UserResponse with roles and permissions."""
|
||||||
permissions = await user.get_permissions(db)
|
permissions = await user.get_permissions(db)
|
||||||
|
|
|
||||||
172
frontend/app/audit/page.test.tsx
Normal file
172
frontend/app/audit/page.test.tsx
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
import { render, screen, waitFor, cleanup } from "@testing-library/react";
|
||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||||
|
import AuditPage from "./page";
|
||||||
|
|
||||||
|
// Mock next/navigation
|
||||||
|
const mockPush = vi.fn();
|
||||||
|
vi.mock("next/navigation", () => ({
|
||||||
|
useRouter: () => ({ push: mockPush }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Default mock values for admin user
|
||||||
|
let mockUser: { id: number; email: string; roles: string[]; permissions: string[] } | null = {
|
||||||
|
id: 1,
|
||||||
|
email: "admin@example.com",
|
||||||
|
roles: ["admin"],
|
||||||
|
permissions: ["view_audit"],
|
||||||
|
};
|
||||||
|
let mockIsLoading = false;
|
||||||
|
const mockLogout = vi.fn();
|
||||||
|
const mockHasPermission = vi.fn((permission: string) =>
|
||||||
|
mockUser?.permissions.includes(permission) ?? false
|
||||||
|
);
|
||||||
|
|
||||||
|
vi.mock("../auth-context", () => ({
|
||||||
|
useAuth: () => ({
|
||||||
|
user: mockUser,
|
||||||
|
isLoading: mockIsLoading,
|
||||||
|
logout: mockLogout,
|
||||||
|
hasPermission: mockHasPermission,
|
||||||
|
}),
|
||||||
|
Permission: {
|
||||||
|
VIEW_COUNTER: "view_counter",
|
||||||
|
INCREMENT_COUNTER: "increment_counter",
|
||||||
|
USE_SUM: "use_sum",
|
||||||
|
VIEW_AUDIT: "view_audit",
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Mock fetch
|
||||||
|
const mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
mockUser = {
|
||||||
|
id: 1,
|
||||||
|
email: "admin@example.com",
|
||||||
|
roles: ["admin"],
|
||||||
|
permissions: ["view_audit"],
|
||||||
|
};
|
||||||
|
mockIsLoading = false;
|
||||||
|
mockHasPermission.mockImplementation((permission: string) =>
|
||||||
|
mockUser?.permissions.includes(permission) ?? false
|
||||||
|
);
|
||||||
|
// Default: successful empty response
|
||||||
|
mockFetch.mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
json: () => Promise.resolve({ records: [], total: 0, page: 1, per_page: 10, total_pages: 1 }),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("AuditPage", () => {
|
||||||
|
it("shows loading state", () => {
|
||||||
|
mockIsLoading = true;
|
||||||
|
render(<AuditPage />);
|
||||||
|
expect(screen.getByText("Loading...")).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("redirects to login when not authenticated", async () => {
|
||||||
|
mockUser = null;
|
||||||
|
render(<AuditPage />);
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(mockPush).toHaveBeenCalledWith("/login");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("redirects to home when user lacks audit permission", async () => {
|
||||||
|
mockUser = {
|
||||||
|
id: 1,
|
||||||
|
email: "user@example.com",
|
||||||
|
roles: ["regular"],
|
||||||
|
permissions: ["view_counter"],
|
||||||
|
};
|
||||||
|
mockHasPermission.mockReturnValue(false);
|
||||||
|
render(<AuditPage />);
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(mockPush).toHaveBeenCalledWith("/");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("displays error message when API fetch fails", async () => {
|
||||||
|
mockFetch.mockRejectedValue(new Error("Network error"));
|
||||||
|
render(<AuditPage />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
// Both tables should show errors since both calls fail
|
||||||
|
const errors = screen.getAllByText("Network error");
|
||||||
|
expect(errors.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("displays error when API returns non-ok response", async () => {
|
||||||
|
mockFetch.mockResolvedValue({
|
||||||
|
ok: false,
|
||||||
|
status: 500,
|
||||||
|
json: () => Promise.resolve({ detail: "Internal server error" }),
|
||||||
|
});
|
||||||
|
|
||||||
|
render(<AuditPage />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText("Failed to load counter records")).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("displays records when fetch succeeds", async () => {
|
||||||
|
const counterResponse = {
|
||||||
|
records: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
user_email: "recorduser@example.com",
|
||||||
|
value_before: 0,
|
||||||
|
value_after: 1,
|
||||||
|
created_at: "2024-01-01T00:00:00Z",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
total: 1,
|
||||||
|
page: 1,
|
||||||
|
per_page: 10,
|
||||||
|
total_pages: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
const sumResponse = {
|
||||||
|
records: [],
|
||||||
|
total: 0,
|
||||||
|
page: 1,
|
||||||
|
per_page: 10,
|
||||||
|
total_pages: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
json: () => Promise.resolve(counterResponse),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
json: () => Promise.resolve(sumResponse),
|
||||||
|
});
|
||||||
|
|
||||||
|
render(<AuditPage />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText("recorduser@example.com")).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows table headers", async () => {
|
||||||
|
render(<AuditPage />);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
// Check for counter table headers
|
||||||
|
expect(screen.getByText("Counter Activity")).toBeTruthy();
|
||||||
|
expect(screen.getByText("Sum Activity")).toBeTruthy();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
@ -1,9 +1,10 @@
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState, useCallback } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useAuth, Permission } from "../auth-context";
|
import { useAuth, Permission } from "../auth-context";
|
||||||
import { API_URL } from "../config";
|
import { API_URL } from "../config";
|
||||||
|
import { sharedStyles } from "../styles/shared";
|
||||||
|
|
||||||
interface CounterRecord {
|
interface CounterRecord {
|
||||||
id: number;
|
id: number;
|
||||||
|
|
@ -33,6 +34,8 @@ interface PaginatedResponse<T> {
|
||||||
export default function AuditPage() {
|
export default function AuditPage() {
|
||||||
const [counterData, setCounterData] = useState<PaginatedResponse<CounterRecord> | null>(null);
|
const [counterData, setCounterData] = useState<PaginatedResponse<CounterRecord> | null>(null);
|
||||||
const [sumData, setSumData] = useState<PaginatedResponse<SumRecord> | null>(null);
|
const [sumData, setSumData] = useState<PaginatedResponse<SumRecord> | null>(null);
|
||||||
|
const [counterError, setCounterError] = useState<string | null>(null);
|
||||||
|
const [sumError, setSumError] = useState<string | null>(null);
|
||||||
const [counterPage, setCounterPage] = useState(1);
|
const [counterPage, setCounterPage] = useState(1);
|
||||||
const [sumPage, setSumPage] = useState(1);
|
const [sumPage, setSumPage] = useState(1);
|
||||||
const { user, isLoading, logout, hasPermission } = useAuth();
|
const { user, isLoading, logout, hasPermission } = useAuth();
|
||||||
|
|
@ -50,41 +53,51 @@ export default function AuditPage() {
|
||||||
}
|
}
|
||||||
}, [isLoading, user, router, canViewAudit]);
|
}, [isLoading, user, router, canViewAudit]);
|
||||||
|
|
||||||
|
const fetchCounterRecords = useCallback(async (page: number) => {
|
||||||
|
setCounterError(null);
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_URL}/api/audit/counter?page=${page}&per_page=10`, {
|
||||||
|
credentials: "include",
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error("Failed to load counter records");
|
||||||
|
}
|
||||||
|
const data = await res.json();
|
||||||
|
setCounterData(data);
|
||||||
|
} catch (err) {
|
||||||
|
setCounterData(null);
|
||||||
|
setCounterError(err instanceof Error ? err.message : "Failed to load counter records");
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const fetchSumRecords = useCallback(async (page: number) => {
|
||||||
|
setSumError(null);
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${API_URL}/api/audit/sum?page=${page}&per_page=10`, {
|
||||||
|
credentials: "include",
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error("Failed to load sum records");
|
||||||
|
}
|
||||||
|
const data = await res.json();
|
||||||
|
setSumData(data);
|
||||||
|
} catch (err) {
|
||||||
|
setSumData(null);
|
||||||
|
setSumError(err instanceof Error ? err.message : "Failed to load sum records");
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (user && canViewAudit) {
|
if (user && canViewAudit) {
|
||||||
fetchCounterRecords(counterPage);
|
fetchCounterRecords(counterPage);
|
||||||
}
|
}
|
||||||
}, [user, counterPage, canViewAudit]);
|
}, [user, counterPage, canViewAudit, fetchCounterRecords]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (user && canViewAudit) {
|
if (user && canViewAudit) {
|
||||||
fetchSumRecords(sumPage);
|
fetchSumRecords(sumPage);
|
||||||
}
|
}
|
||||||
}, [user, sumPage, canViewAudit]);
|
}, [user, sumPage, canViewAudit, fetchSumRecords]);
|
||||||
|
|
||||||
const fetchCounterRecords = async (page: number) => {
|
|
||||||
try {
|
|
||||||
const res = await fetch(`${API_URL}/api/audit/counter?page=${page}&per_page=10`, {
|
|
||||||
credentials: "include",
|
|
||||||
});
|
|
||||||
const data = await res.json();
|
|
||||||
setCounterData(data);
|
|
||||||
} catch {
|
|
||||||
setCounterData(null);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchSumRecords = async (page: number) => {
|
|
||||||
try {
|
|
||||||
const res = await fetch(`${API_URL}/api/audit/sum?page=${page}&per_page=10`, {
|
|
||||||
credentials: "include",
|
|
||||||
});
|
|
||||||
const data = await res.json();
|
|
||||||
setSumData(data);
|
|
||||||
} catch {
|
|
||||||
setSumData(null);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleLogout = async () => {
|
const handleLogout = async () => {
|
||||||
await logout();
|
await logout();
|
||||||
|
|
@ -142,7 +155,12 @@ export default function AuditPage() {
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{counterData?.records.map((record) => (
|
{counterError && (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={4} style={styles.errorRow}>{counterError}</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
{!counterError && counterData?.records.map((record) => (
|
||||||
<tr key={record.id} style={styles.tr}>
|
<tr key={record.id} style={styles.tr}>
|
||||||
<td style={styles.td}>{record.user_email}</td>
|
<td style={styles.td}>{record.user_email}</td>
|
||||||
<td style={styles.tdNum}>{record.value_before}</td>
|
<td style={styles.tdNum}>{record.value_before}</td>
|
||||||
|
|
@ -150,7 +168,7 @@ export default function AuditPage() {
|
||||||
<td style={styles.tdDate}>{formatDate(record.created_at)}</td>
|
<td style={styles.tdDate}>{formatDate(record.created_at)}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
{(!counterData || counterData.records.length === 0) && (
|
{!counterError && (!counterData || counterData.records.length === 0) && (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={4} style={styles.emptyRow}>No records yet</td>
|
<td colSpan={4} style={styles.emptyRow}>No records yet</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|
@ -201,7 +219,12 @@ export default function AuditPage() {
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{sumData?.records.map((record) => (
|
{sumError && (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={5} style={styles.errorRow}>{sumError}</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
{!sumError && sumData?.records.map((record) => (
|
||||||
<tr key={record.id} style={styles.tr}>
|
<tr key={record.id} style={styles.tr}>
|
||||||
<td style={styles.td}>{record.user_email}</td>
|
<td style={styles.td}>{record.user_email}</td>
|
||||||
<td style={styles.tdNum}>{record.a}</td>
|
<td style={styles.tdNum}>{record.a}</td>
|
||||||
|
|
@ -210,7 +233,7 @@ export default function AuditPage() {
|
||||||
<td style={styles.tdDate}>{formatDate(record.created_at)}</td>
|
<td style={styles.tdDate}>{formatDate(record.created_at)}</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
{(!sumData || sumData.records.length === 0) && (
|
{!sumError && (!sumData || sumData.records.length === 0) && (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={5} style={styles.emptyRow}>No records yet</td>
|
<td colSpan={5} style={styles.emptyRow}>No records yet</td>
|
||||||
</tr>
|
</tr>
|
||||||
|
|
@ -246,73 +269,8 @@ export default function AuditPage() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const styles: Record<string, React.CSSProperties> = {
|
const pageStyles: Record<string, React.CSSProperties> = {
|
||||||
main: {
|
// Override content for audit-specific layout
|
||||||
minHeight: "100vh",
|
|
||||||
background: "linear-gradient(135deg, #0f0f23 0%, #1a1a3e 50%, #2d1b4e 100%)",
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
},
|
|
||||||
loader: {
|
|
||||||
flex: 1,
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
justifyContent: "center",
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
color: "rgba(255, 255, 255, 0.5)",
|
|
||||||
fontSize: "1.125rem",
|
|
||||||
},
|
|
||||||
header: {
|
|
||||||
padding: "1.5rem 2rem",
|
|
||||||
borderBottom: "1px solid rgba(255, 255, 255, 0.06)",
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "space-between",
|
|
||||||
alignItems: "center",
|
|
||||||
},
|
|
||||||
nav: {
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: "0.75rem",
|
|
||||||
},
|
|
||||||
navLink: {
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
color: "rgba(255, 255, 255, 0.5)",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
textDecoration: "none",
|
|
||||||
transition: "color 0.2s",
|
|
||||||
},
|
|
||||||
navDivider: {
|
|
||||||
color: "rgba(255, 255, 255, 0.2)",
|
|
||||||
fontSize: "0.75rem",
|
|
||||||
},
|
|
||||||
navCurrent: {
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
color: "#a78bfa",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
fontWeight: 600,
|
|
||||||
},
|
|
||||||
userInfo: {
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: "1rem",
|
|
||||||
},
|
|
||||||
userEmail: {
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
color: "rgba(255, 255, 255, 0.6)",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
},
|
|
||||||
logoutBtn: {
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
padding: "0.5rem 1rem",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
fontWeight: 500,
|
|
||||||
background: "rgba(255, 255, 255, 0.05)",
|
|
||||||
color: "rgba(255, 255, 255, 0.7)",
|
|
||||||
border: "1px solid rgba(255, 255, 255, 0.1)",
|
|
||||||
borderRadius: "8px",
|
|
||||||
cursor: "pointer",
|
|
||||||
transition: "all 0.2s",
|
|
||||||
},
|
|
||||||
content: {
|
content: {
|
||||||
flex: 1,
|
flex: 1,
|
||||||
padding: "2rem",
|
padding: "2rem",
|
||||||
|
|
@ -401,6 +359,12 @@ const styles: Record<string, React.CSSProperties> = {
|
||||||
color: "rgba(255, 255, 255, 0.3)",
|
color: "rgba(255, 255, 255, 0.3)",
|
||||||
fontSize: "0.875rem",
|
fontSize: "0.875rem",
|
||||||
},
|
},
|
||||||
|
errorRow: {
|
||||||
|
padding: "2rem 1rem",
|
||||||
|
textAlign: "center",
|
||||||
|
color: "#f87171",
|
||||||
|
fontSize: "0.875rem",
|
||||||
|
},
|
||||||
pagination: {
|
pagination: {
|
||||||
display: "flex",
|
display: "flex",
|
||||||
justifyContent: "center",
|
justifyContent: "center",
|
||||||
|
|
@ -428,3 +392,5 @@ const styles: Record<string, React.CSSProperties> = {
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const styles = { ...sharedStyles, ...pageStyles };
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { createContext, useContext, useState, useEffect, ReactNode } from "react";
|
import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from "react";
|
||||||
|
|
||||||
import { API_URL } from "./config";
|
import { API_URL } from "./config";
|
||||||
|
|
||||||
|
|
@ -100,17 +100,17 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||||
setUser(null);
|
setUser(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const hasPermission = (permission: PermissionType): boolean => {
|
const hasPermission = useCallback((permission: PermissionType): boolean => {
|
||||||
return user?.permissions.includes(permission) ?? false;
|
return user?.permissions.includes(permission) ?? false;
|
||||||
};
|
}, [user]);
|
||||||
|
|
||||||
const hasAnyPermission = (...permissions: PermissionType[]): boolean => {
|
const hasAnyPermission = useCallback((...permissions: PermissionType[]): boolean => {
|
||||||
return permissions.some((p) => user?.permissions.includes(p) ?? false);
|
return permissions.some((p) => user?.permissions.includes(p) ?? false);
|
||||||
};
|
}, [user]);
|
||||||
|
|
||||||
const hasRole = (role: string): boolean => {
|
const hasRole = useCallback((role: string): boolean => {
|
||||||
return user?.roles.includes(role) ?? false;
|
return user?.roles.includes(role) ?? false;
|
||||||
};
|
}, [user]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContext.Provider
|
<AuthContext.Provider
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import { useEffect, useState } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useAuth, Permission } from "./auth-context";
|
import { useAuth, Permission } from "./auth-context";
|
||||||
import { API_URL } from "./config";
|
import { API_URL } from "./config";
|
||||||
|
import { sharedStyles } from "./styles/shared";
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
const [count, setCount] = useState<number | null>(null);
|
const [count, setCount] = useState<number | null>(null);
|
||||||
|
|
@ -90,80 +91,7 @@ export default function Home() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const styles: Record<string, React.CSSProperties> = {
|
const pageStyles: Record<string, React.CSSProperties> = {
|
||||||
main: {
|
|
||||||
minHeight: "100vh",
|
|
||||||
background: "linear-gradient(135deg, #0f0f23 0%, #1a1a3e 50%, #2d1b4e 100%)",
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
},
|
|
||||||
loader: {
|
|
||||||
flex: 1,
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
justifyContent: "center",
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
color: "rgba(255, 255, 255, 0.5)",
|
|
||||||
fontSize: "1.125rem",
|
|
||||||
},
|
|
||||||
header: {
|
|
||||||
padding: "1.5rem 2rem",
|
|
||||||
borderBottom: "1px solid rgba(255, 255, 255, 0.06)",
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "space-between",
|
|
||||||
alignItems: "center",
|
|
||||||
},
|
|
||||||
nav: {
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: "0.75rem",
|
|
||||||
},
|
|
||||||
navLink: {
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
color: "rgba(255, 255, 255, 0.5)",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
textDecoration: "none",
|
|
||||||
transition: "color 0.2s",
|
|
||||||
},
|
|
||||||
navDivider: {
|
|
||||||
color: "rgba(255, 255, 255, 0.2)",
|
|
||||||
fontSize: "0.75rem",
|
|
||||||
},
|
|
||||||
navCurrent: {
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
color: "#a78bfa",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
fontWeight: 600,
|
|
||||||
},
|
|
||||||
userInfo: {
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: "1rem",
|
|
||||||
},
|
|
||||||
userEmail: {
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
color: "rgba(255, 255, 255, 0.6)",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
},
|
|
||||||
logoutBtn: {
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
padding: "0.5rem 1rem",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
fontWeight: 500,
|
|
||||||
background: "rgba(255, 255, 255, 0.05)",
|
|
||||||
color: "rgba(255, 255, 255, 0.7)",
|
|
||||||
border: "1px solid rgba(255, 255, 255, 0.1)",
|
|
||||||
borderRadius: "8px",
|
|
||||||
cursor: "pointer",
|
|
||||||
transition: "all 0.2s",
|
|
||||||
},
|
|
||||||
content: {
|
|
||||||
flex: 1,
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
justifyContent: "center",
|
|
||||||
padding: "2rem",
|
|
||||||
},
|
|
||||||
counterCard: {
|
counterCard: {
|
||||||
background: "rgba(255, 255, 255, 0.03)",
|
background: "rgba(255, 255, 255, 0.03)",
|
||||||
backdropFilter: "blur(10px)",
|
backdropFilter: "blur(10px)",
|
||||||
|
|
@ -216,3 +144,5 @@ const styles: Record<string, React.CSSProperties> = {
|
||||||
fontWeight: 400,
|
fontWeight: 400,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const styles = { ...sharedStyles, ...pageStyles };
|
||||||
|
|
|
||||||
82
frontend/app/styles/shared.ts
Normal file
82
frontend/app/styles/shared.ts
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
import React from "react";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared styles used across multiple pages.
|
||||||
|
* These styles define the common layout and theming for the app.
|
||||||
|
*/
|
||||||
|
export const sharedStyles: Record<string, React.CSSProperties> = {
|
||||||
|
main: {
|
||||||
|
minHeight: "100vh",
|
||||||
|
background: "linear-gradient(135deg, #0f0f23 0%, #1a1a3e 50%, #2d1b4e 100%)",
|
||||||
|
display: "flex",
|
||||||
|
flexDirection: "column",
|
||||||
|
},
|
||||||
|
loader: {
|
||||||
|
flex: 1,
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||||
|
color: "rgba(255, 255, 255, 0.5)",
|
||||||
|
fontSize: "1.125rem",
|
||||||
|
},
|
||||||
|
header: {
|
||||||
|
padding: "1.5rem 2rem",
|
||||||
|
borderBottom: "1px solid rgba(255, 255, 255, 0.06)",
|
||||||
|
display: "flex",
|
||||||
|
justifyContent: "space-between",
|
||||||
|
alignItems: "center",
|
||||||
|
},
|
||||||
|
nav: {
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: "0.75rem",
|
||||||
|
},
|
||||||
|
navLink: {
|
||||||
|
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||||
|
color: "rgba(255, 255, 255, 0.5)",
|
||||||
|
fontSize: "0.875rem",
|
||||||
|
textDecoration: "none",
|
||||||
|
transition: "color 0.2s",
|
||||||
|
},
|
||||||
|
navDivider: {
|
||||||
|
color: "rgba(255, 255, 255, 0.2)",
|
||||||
|
fontSize: "0.75rem",
|
||||||
|
},
|
||||||
|
navCurrent: {
|
||||||
|
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||||
|
color: "#a78bfa",
|
||||||
|
fontSize: "0.875rem",
|
||||||
|
fontWeight: 600,
|
||||||
|
},
|
||||||
|
userInfo: {
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
gap: "1rem",
|
||||||
|
},
|
||||||
|
userEmail: {
|
||||||
|
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||||
|
color: "rgba(255, 255, 255, 0.6)",
|
||||||
|
fontSize: "0.875rem",
|
||||||
|
},
|
||||||
|
logoutBtn: {
|
||||||
|
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||||
|
padding: "0.5rem 1rem",
|
||||||
|
fontSize: "0.875rem",
|
||||||
|
fontWeight: 500,
|
||||||
|
background: "rgba(255, 255, 255, 0.05)",
|
||||||
|
color: "rgba(255, 255, 255, 0.7)",
|
||||||
|
border: "1px solid rgba(255, 255, 255, 0.1)",
|
||||||
|
borderRadius: "8px",
|
||||||
|
cursor: "pointer",
|
||||||
|
transition: "all 0.2s",
|
||||||
|
},
|
||||||
|
content: {
|
||||||
|
flex: 1,
|
||||||
|
display: "flex",
|
||||||
|
alignItems: "center",
|
||||||
|
justifyContent: "center",
|
||||||
|
padding: "2rem",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
|
@ -4,12 +4,14 @@ import { useEffect, useState } from "react";
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
import { useAuth, Permission } from "../auth-context";
|
import { useAuth, Permission } from "../auth-context";
|
||||||
import { API_URL } from "../config";
|
import { API_URL } from "../config";
|
||||||
|
import { sharedStyles } from "../styles/shared";
|
||||||
|
|
||||||
export default function SumPage() {
|
export default function SumPage() {
|
||||||
const [a, setA] = useState("");
|
const [a, setA] = useState("");
|
||||||
const [b, setB] = useState("");
|
const [b, setB] = useState("");
|
||||||
const [result, setResult] = useState<number | null>(null);
|
const [result, setResult] = useState<number | null>(null);
|
||||||
const [showResult, setShowResult] = useState(false);
|
const [showResult, setShowResult] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
const { user, isLoading, logout, hasPermission } = useAuth();
|
const { user, isLoading, logout, hasPermission } = useAuth();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
|
|
@ -28,6 +30,7 @@ export default function SumPage() {
|
||||||
const handleSum = async () => {
|
const handleSum = async () => {
|
||||||
const numA = parseFloat(a) || 0;
|
const numA = parseFloat(a) || 0;
|
||||||
const numB = parseFloat(b) || 0;
|
const numB = parseFloat(b) || 0;
|
||||||
|
setError(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_URL}/api/sum`, {
|
const res = await fetch(`${API_URL}/api/sum`, {
|
||||||
|
|
@ -36,13 +39,14 @@ export default function SumPage() {
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
body: JSON.stringify({ a: numA, b: numB }),
|
body: JSON.stringify({ a: numA, b: numB }),
|
||||||
});
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error("Calculation failed");
|
||||||
|
}
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setResult(data.result);
|
setResult(data.result);
|
||||||
setShowResult(true);
|
setShowResult(true);
|
||||||
} catch {
|
} catch (err) {
|
||||||
// Fallback to local calculation if API fails
|
setError(err instanceof Error ? err.message : "Calculation failed");
|
||||||
setResult(numA + numB);
|
|
||||||
setShowResult(true);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -51,6 +55,7 @@ export default function SumPage() {
|
||||||
setB("");
|
setB("");
|
||||||
setResult(null);
|
setResult(null);
|
||||||
setShowResult(false);
|
setShowResult(false);
|
||||||
|
setError(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleLogout = async () => {
|
const handleLogout = async () => {
|
||||||
|
|
@ -123,6 +128,9 @@ export default function SumPage() {
|
||||||
<span style={styles.equalsIcon}>=</span>
|
<span style={styles.equalsIcon}>=</span>
|
||||||
Calculate
|
Calculate
|
||||||
</button>
|
</button>
|
||||||
|
{error && (
|
||||||
|
<div style={styles.error}>{error}</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div style={styles.resultSection}>
|
<div style={styles.resultSection}>
|
||||||
|
|
@ -145,80 +153,7 @@ export default function SumPage() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const styles: Record<string, React.CSSProperties> = {
|
const pageStyles: Record<string, React.CSSProperties> = {
|
||||||
main: {
|
|
||||||
minHeight: "100vh",
|
|
||||||
background: "linear-gradient(135deg, #0f0f23 0%, #1a1a3e 50%, #2d1b4e 100%)",
|
|
||||||
display: "flex",
|
|
||||||
flexDirection: "column",
|
|
||||||
},
|
|
||||||
loader: {
|
|
||||||
flex: 1,
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
justifyContent: "center",
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
color: "rgba(255, 255, 255, 0.5)",
|
|
||||||
fontSize: "1.125rem",
|
|
||||||
},
|
|
||||||
header: {
|
|
||||||
padding: "1.5rem 2rem",
|
|
||||||
borderBottom: "1px solid rgba(255, 255, 255, 0.06)",
|
|
||||||
display: "flex",
|
|
||||||
justifyContent: "space-between",
|
|
||||||
alignItems: "center",
|
|
||||||
},
|
|
||||||
nav: {
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: "0.75rem",
|
|
||||||
},
|
|
||||||
navLink: {
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
color: "rgba(255, 255, 255, 0.5)",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
textDecoration: "none",
|
|
||||||
transition: "color 0.2s",
|
|
||||||
},
|
|
||||||
navDivider: {
|
|
||||||
color: "rgba(255, 255, 255, 0.2)",
|
|
||||||
fontSize: "0.75rem",
|
|
||||||
},
|
|
||||||
navCurrent: {
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
color: "#a78bfa",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
fontWeight: 600,
|
|
||||||
},
|
|
||||||
userInfo: {
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
gap: "1rem",
|
|
||||||
},
|
|
||||||
userEmail: {
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
color: "rgba(255, 255, 255, 0.6)",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
},
|
|
||||||
logoutBtn: {
|
|
||||||
fontFamily: "'DM Sans', system-ui, sans-serif",
|
|
||||||
padding: "0.5rem 1rem",
|
|
||||||
fontSize: "0.875rem",
|
|
||||||
fontWeight: 500,
|
|
||||||
background: "rgba(255, 255, 255, 0.05)",
|
|
||||||
color: "rgba(255, 255, 255, 0.7)",
|
|
||||||
border: "1px solid rgba(255, 255, 255, 0.1)",
|
|
||||||
borderRadius: "8px",
|
|
||||||
cursor: "pointer",
|
|
||||||
transition: "all 0.2s",
|
|
||||||
},
|
|
||||||
content: {
|
|
||||||
flex: 1,
|
|
||||||
display: "flex",
|
|
||||||
alignItems: "center",
|
|
||||||
justifyContent: "center",
|
|
||||||
padding: "2rem",
|
|
||||||
},
|
|
||||||
card: {
|
card: {
|
||||||
background: "rgba(255, 255, 255, 0.03)",
|
background: "rgba(255, 255, 255, 0.03)",
|
||||||
backdropFilter: "blur(10px)",
|
backdropFilter: "blur(10px)",
|
||||||
|
|
@ -344,5 +279,13 @@ const styles: Record<string, React.CSSProperties> = {
|
||||||
resetIcon: {
|
resetIcon: {
|
||||||
fontSize: "1.25rem",
|
fontSize: "1.25rem",
|
||||||
},
|
},
|
||||||
|
error: {
|
||||||
|
fontFamily: "'DM Sans', system-ui, sans-serif",
|
||||||
|
color: "#f87171",
|
||||||
|
fontSize: "0.875rem",
|
||||||
|
marginTop: "0.5rem",
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const styles = { ...sharedStyles, ...pageStyles };
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { test, expect, Page, APIRequestContext } from "@playwright/test";
|
import { test, expect, Page } from "@playwright/test";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Permission-based E2E tests
|
* Permission-based E2E tests
|
||||||
|
|
@ -14,14 +14,23 @@ const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000";
|
||||||
|
|
||||||
// Test credentials - must match what's seeded in the database via seed.py
|
// Test credentials - must match what's seeded in the database via seed.py
|
||||||
// These come from environment variables DEV_USER_EMAIL/PASSWORD and DEV_ADMIN_EMAIL/PASSWORD
|
// These come from environment variables DEV_USER_EMAIL/PASSWORD and DEV_ADMIN_EMAIL/PASSWORD
|
||||||
|
// Tests will fail fast if these are not set
|
||||||
|
function getRequiredEnv(name: string): string {
|
||||||
|
const value = process.env[name];
|
||||||
|
if (!value) {
|
||||||
|
throw new Error(`Required environment variable ${name} is not set. Run 'source .env' or set it in your environment.`);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
const REGULAR_USER = {
|
const REGULAR_USER = {
|
||||||
email: process.env.DEV_USER_EMAIL || "user@example.com",
|
email: getRequiredEnv("DEV_USER_EMAIL"),
|
||||||
password: process.env.DEV_USER_PASSWORD || "user123",
|
password: getRequiredEnv("DEV_USER_PASSWORD"),
|
||||||
};
|
};
|
||||||
|
|
||||||
const ADMIN_USER = {
|
const ADMIN_USER = {
|
||||||
email: process.env.DEV_ADMIN_EMAIL || "admin@example.com",
|
email: getRequiredEnv("DEV_ADMIN_EMAIL"),
|
||||||
password: process.env.DEV_ADMIN_PASSWORD || "admin123",
|
password: getRequiredEnv("DEV_ADMIN_PASSWORD"),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Helper to clear auth cookies
|
// Helper to clear auth cookies
|
||||||
|
|
@ -29,17 +38,6 @@ async function clearAuth(page: Page) {
|
||||||
await page.context().clearCookies();
|
await page.context().clearCookies();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper to create a user with specific role via API
|
|
||||||
async function createUserWithRole(
|
|
||||||
request: APIRequestContext,
|
|
||||||
email: string,
|
|
||||||
password: string,
|
|
||||||
roleName: string
|
|
||||||
): Promise<void> {
|
|
||||||
// This requires direct DB access or a test endpoint
|
|
||||||
// For now, we'll use the seeded users from conftest
|
|
||||||
}
|
|
||||||
|
|
||||||
// Helper to login a user
|
// Helper to login a user
|
||||||
async function loginUser(page: Page, email: string, password: string) {
|
async function loginUser(page: Page, email: string, password: string) {
|
||||||
await page.goto("/login");
|
await page.goto("/login");
|
||||||
|
|
@ -149,19 +147,9 @@ test.describe("Regular User Access", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test.describe("Admin User Access", () => {
|
test.describe("Admin User Access", () => {
|
||||||
// Skip these tests if admin user isn't set up
|
|
||||||
// In real scenario, you'd create admin user in beforeAll
|
|
||||||
test.skip(
|
|
||||||
!process.env.DEV_ADMIN_EMAIL,
|
|
||||||
"Admin tests require DEV_ADMIN_EMAIL and DEV_ADMIN_PASSWORD env vars"
|
|
||||||
);
|
|
||||||
|
|
||||||
const adminEmail = process.env.DEV_ADMIN_EMAIL || ADMIN_USER.email;
|
|
||||||
const adminPassword = process.env.DEV_ADMIN_PASSWORD || ADMIN_USER.password;
|
|
||||||
|
|
||||||
test.beforeEach(async ({ page }) => {
|
test.beforeEach(async ({ page }) => {
|
||||||
await clearAuth(page);
|
await clearAuth(page);
|
||||||
await loginUser(page, adminEmail, adminPassword);
|
await loginUser(page, ADMIN_USER.email, ADMIN_USER.password);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("redirected from counter page to audit", async ({ page }) => {
|
test("redirected from counter page to audit", async ({ page }) => {
|
||||||
|
|
@ -258,17 +246,9 @@ test.describe("Permission Boundary via API", () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test("admin user API call to counter returns 403", async ({ page, request }) => {
|
test("admin user API call to counter returns 403", async ({ page, request }) => {
|
||||||
const adminEmail = process.env.DEV_ADMIN_EMAIL;
|
|
||||||
const adminPassword = process.env.DEV_ADMIN_PASSWORD;
|
|
||||||
|
|
||||||
if (!adminEmail || !adminPassword) {
|
|
||||||
test.skip();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Login as admin
|
// Login as admin
|
||||||
await clearAuth(page);
|
await clearAuth(page);
|
||||||
await loginUser(page, adminEmail, adminPassword);
|
await loginUser(page, ADMIN_USER.email, ADMIN_USER.password);
|
||||||
|
|
||||||
// Get cookies
|
// Get cookies
|
||||||
const cookies = await page.context().cookies();
|
const cookies = await page.context().cookies();
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue