Restructures frontend to a feature-based folder layout
Continuous Integration / config (pull_request) Successful in 11s
Continuous Integration / changes (pull_request) Successful in 21s
Continuous Integration / backend-build (pull_request) Skipped
Continuous Integration / backend-test (pull_request) Skipped
Continuous Integration / vulnerability-scan (pull_request) Skipped
Continuous Integration / frontend-prepare (pull_request) Successful in 1m37s
Continuous Integration / frontend-build (pull_request) Successful in 2m12s
Continuous Integration / frontend-test (pull_request) Successful in 4m42s
Continuous Integration / frontend-lint (pull_request) Successful in 2m2s
Continuous Integration / publish-production (pull_request) Skipped
Continuous Integration / deploy-production (pull_request) Skipped
Continuous Integration / publish-test (pull_request) Successful in 6m51s
Continuous Integration / deploy-test (pull_request) Skipped
Continuous Integration / config (pull_request) Successful in 11s
Continuous Integration / changes (pull_request) Successful in 21s
Continuous Integration / backend-build (pull_request) Skipped
Continuous Integration / backend-test (pull_request) Skipped
Continuous Integration / vulnerability-scan (pull_request) Skipped
Continuous Integration / frontend-prepare (pull_request) Successful in 1m37s
Continuous Integration / frontend-build (pull_request) Successful in 2m12s
Continuous Integration / frontend-test (pull_request) Successful in 4m42s
Continuous Integration / frontend-lint (pull_request) Successful in 2m2s
Continuous Integration / publish-production (pull_request) Skipped
Continuous Integration / deploy-production (pull_request) Skipped
Continuous Integration / publish-test (pull_request) Successful in 6m51s
Continuous Integration / deploy-test (pull_request) Skipped
Groups auth, setup, invitation, profile, users, cms, availability and system code (services/hooks, components, schemas, mocks, pages) under src/features/<name> instead of splitting by technical layer (api/, components/, lib/schemas/, mocks/, pages/). Renames the old connection-oriented `api` layer to `services` per feature, and splits the monolithic api/types.ts into per-feature types.ts files (with ProblemDetails/ApiResult merged into lib/api-client.ts as shared infra). Layout-agnostic code (ui primitives, app shell, i18n, test utils, lib) stays at the top level. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { renderApp } from '@/test/utils';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE, makeAuthResponse, mockUser } from '@/features/auth/mocks/fixtures';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
beforeEach(() => {
|
||||
_resetSetupStatusCache();
|
||||
});
|
||||
|
||||
describe('RoleGuard', () => {
|
||||
it('renders protected content when user has an allowed role (Owner on /users)', async () => {
|
||||
// Default auth mock returns Owner role, /users requires Owner or Administrator
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/auth/refresh`, () =>
|
||||
HttpResponse.json(makeAuthResponse()),
|
||||
),
|
||||
);
|
||||
renderApp('/users');
|
||||
|
||||
expect(await screen.findByTestId('users-title')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows access denied message when user lacks the required role', async () => {
|
||||
// Authenticate with 'User' role — /users requires Owner or Administrator
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/auth/refresh`, () =>
|
||||
HttpResponse.json(makeAuthResponse({ user: { ...mockUser, role: 'User' } })),
|
||||
),
|
||||
);
|
||||
renderApp('/users');
|
||||
|
||||
expect(await screen.findByTestId('access-denied-message')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('users-title')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { Link } from '@tanstack/react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { UserRole } from '@/features/auth/services/types';
|
||||
import { useAuth } from '@/features/auth/context/auth-context';
|
||||
|
||||
interface RoleGuardProps {
|
||||
allowedRoles: UserRole[];
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function RoleGuard({ allowedRoles, children }: RoleGuardProps) {
|
||||
const { t } = useTranslation();
|
||||
const { user } = useAuth();
|
||||
|
||||
if (user !== null && allowedRoles.includes(user.role)) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
const requiredLabel = allowedRoles.join(' or ');
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="access-denied-message"
|
||||
className="flex flex-col items-center justify-center gap-4 py-16 text-center"
|
||||
>
|
||||
<h1 className="text-2xl font-semibold">{t('errors.accessDenied')}</h1>
|
||||
<p className="max-w-sm text-sm text-muted-foreground">
|
||||
{t('errors.accessDeniedDetail', { roles: requiredLabel })}
|
||||
</p>
|
||||
<Link to="/dashboard" className="text-sm text-primary underline-offset-4 hover:underline">
|
||||
{t('nav.dashboard')}
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { I18nextProvider } from 'react-i18next';
|
||||
import type { ReactNode } from 'react';
|
||||
import { AuthProvider } from '@/features/auth/context/AuthProvider';
|
||||
import { useAuth } from '@/features/auth/context/auth-context';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE, mockUser } from '@/features/auth/mocks/fixtures';
|
||||
import { mockGuest } from '@/test/utils';
|
||||
import i18n from '@/i18n/config';
|
||||
|
||||
function wrapper({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<AuthProvider>{children}</AuthProvider>
|
||||
</I18nextProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('AuthContext', () => {
|
||||
it('hydrates the session via silent refresh on mount (BR-U1-01)', async () => {
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
|
||||
await waitFor(() => expect(result.current.status).toBe('authenticated'));
|
||||
expect(result.current.isAuthenticated).toBe(true);
|
||||
expect(result.current.user?.email).toBe(mockUser.email);
|
||||
expect(result.current.accessToken).toBe('mock-access-token');
|
||||
});
|
||||
|
||||
it('falls back to guest when silent refresh fails', async () => {
|
||||
mockGuest();
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
|
||||
await waitFor(() => expect(result.current.status).toBe('guest'));
|
||||
expect(result.current.isAuthenticated).toBe(false);
|
||||
expect(result.current.user).toBeNull();
|
||||
});
|
||||
|
||||
it('refreshes and retries once on a 401 (BR-U1-04)', async () => {
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
await waitFor(() => expect(result.current.isAuthenticated).toBe(true));
|
||||
|
||||
let calls = 0;
|
||||
server.use(
|
||||
http.get(`${API_BASE}/api/v1/widgets`, () => {
|
||||
calls += 1;
|
||||
if (calls === 1) {
|
||||
return HttpResponse.json(
|
||||
{ status: 401, title: 'Unauthorized' },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
return HttpResponse.json({ value: 'ok' });
|
||||
}),
|
||||
);
|
||||
|
||||
let data: unknown;
|
||||
await act(async () => {
|
||||
data = await api.get('/api/v1/widgets');
|
||||
});
|
||||
|
||||
expect(calls).toBe(2);
|
||||
expect(data).toEqual({ value: 'ok' });
|
||||
});
|
||||
|
||||
it('clears the session when the 401 refresh also fails', async () => {
|
||||
const { result } = renderHook(() => useAuth(), { wrapper });
|
||||
await waitFor(() => expect(result.current.isAuthenticated).toBe(true));
|
||||
|
||||
// Both the protected call and the refresh now fail.
|
||||
server.use(
|
||||
http.get(`${API_BASE}/api/v1/widgets`, () =>
|
||||
HttpResponse.json({ status: 401 }, { status: 401 }),
|
||||
),
|
||||
http.post(`${API_BASE}/api/v1/auth/refresh`, () =>
|
||||
HttpResponse.json({ status: 401 }, { status: 401 }),
|
||||
),
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
await expect(api.get('/api/v1/widgets')).rejects.toThrow();
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.isAuthenticated).toBe(false));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
import type { AuthResponse } from '@/features/auth/services/types';
|
||||
import { api } from '@/lib/api-client';
|
||||
import { AuthContext, type AuthContextValue, type AuthStatus } from '@/features/auth/context/auth-context';
|
||||
|
||||
/**
|
||||
* Owns the in-memory authentication session. On mount it attempts a silent
|
||||
* refresh using the httpOnly cookie (BR-U1-01) and wires the ApiClient's
|
||||
* 401 interceptor to this provider's refresh/clear logic (BR-U1-04).
|
||||
*/
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<AuthContextValue['user']>(null);
|
||||
const [accessToken, setAccessToken] = useState<string | null>(null);
|
||||
const [expiresAt, setExpiresAt] = useState<string | null>(null);
|
||||
const [status, setStatus] = useState<AuthStatus>('loading');
|
||||
|
||||
const applySession = useCallback((data: AuthResponse) => {
|
||||
setUser(data.user);
|
||||
setAccessToken(data.accessToken);
|
||||
setExpiresAt(data.expiresAt);
|
||||
api.setAccessToken(data.accessToken);
|
||||
setStatus('authenticated');
|
||||
}, []);
|
||||
|
||||
const clearSession = useCallback(() => {
|
||||
setUser(null);
|
||||
setAccessToken(null);
|
||||
setExpiresAt(null);
|
||||
api.setAccessToken(null);
|
||||
setStatus('guest');
|
||||
}, []);
|
||||
|
||||
const refresh = useCallback(async (): Promise<string | null> => {
|
||||
try {
|
||||
const data = await api.post<AuthResponse>('/api/v1/auth/refresh', undefined, {
|
||||
skipAuthRefresh: true,
|
||||
});
|
||||
applySession(data);
|
||||
return data.accessToken;
|
||||
} catch {
|
||||
clearSession();
|
||||
return null;
|
||||
}
|
||||
}, [applySession, clearSession]);
|
||||
|
||||
const login = useCallback(
|
||||
async (email: string, password: string) => {
|
||||
const data = await api.post<AuthResponse>(
|
||||
'/api/v1/auth/login',
|
||||
{ email, password },
|
||||
{ skipAuthRefresh: true },
|
||||
);
|
||||
applySession(data);
|
||||
},
|
||||
[applySession],
|
||||
);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
try {
|
||||
await api.post('/api/v1/auth/revoke', undefined, { skipAuthRefresh: true });
|
||||
} catch {
|
||||
// Revoke is best-effort; clear local state regardless.
|
||||
} finally {
|
||||
clearSession();
|
||||
}
|
||||
}, [clearSession]);
|
||||
|
||||
// Wire the ApiClient interceptor hooks to this provider.
|
||||
useEffect(() => {
|
||||
api.setRefreshHandler(refresh);
|
||||
api.setAuthFailureHandler(clearSession);
|
||||
return () => {
|
||||
api.setRefreshHandler(null);
|
||||
api.setAuthFailureHandler(null);
|
||||
};
|
||||
}, [refresh, clearSession]);
|
||||
|
||||
// Silent refresh on app mount (BR-U1-01). This intentionally synchronizes
|
||||
// React state with the external session (httpOnly cookie) on startup.
|
||||
useEffect(() => {
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
const value = useMemo<AuthContextValue>(
|
||||
() => ({
|
||||
status,
|
||||
user,
|
||||
accessToken,
|
||||
expiresAt,
|
||||
isAuthenticated: status === 'authenticated',
|
||||
login,
|
||||
logout,
|
||||
refresh,
|
||||
}),
|
||||
[status, user, accessToken, expiresAt, login, logout, refresh],
|
||||
);
|
||||
|
||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { createContext, useContext } from 'react';
|
||||
import type { User } from '@/features/auth/services/types';
|
||||
|
||||
export type AuthStatus = 'loading' | 'authenticated' | 'guest';
|
||||
|
||||
export interface AuthContextValue {
|
||||
status: AuthStatus;
|
||||
user: User | null;
|
||||
/** Access token, kept only in memory (BR-U1-02). */
|
||||
accessToken: string | null;
|
||||
expiresAt: string | null;
|
||||
isAuthenticated: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
/** Performs a cookie-based silent refresh; resolves to the new token or null. */
|
||||
refresh: () => Promise<string | null>;
|
||||
}
|
||||
|
||||
export const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
|
||||
export function useAuth(): AuthContextValue {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (ctx === null) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { AuthResponse, User } from '@/features/auth/services/types';
|
||||
import { getAppConfig } from '@/lib/config';
|
||||
|
||||
/**
|
||||
* Base URL the ApiClient targets; mocks must match it exactly. Reads the same
|
||||
* getAppConfig().apiBaseUrl the real ApiClient is constructed with, rather than
|
||||
* re-deriving VITE_API_BASE_URL with its own fallback — a second, diverging default here
|
||||
* previously matched the real client's origin only when a local .env.local happened to set
|
||||
* VITE_API_BASE_URL, and silently mismatched (all mocks unmatched) whenever it was unset, as in CI.
|
||||
*/
|
||||
export const API_BASE = getAppConfig().apiBaseUrl;
|
||||
|
||||
export const TEST_CREDENTIALS = {
|
||||
email: 'owner@example.com',
|
||||
password: 'Password123!',
|
||||
};
|
||||
|
||||
export const mockUser: User = {
|
||||
id: '11111111-1111-1111-1111-111111111111',
|
||||
email: TEST_CREDENTIALS.email,
|
||||
name: 'Test Owner',
|
||||
role: 'Owner',
|
||||
isActive: true,
|
||||
};
|
||||
|
||||
export function makeAuthResponse(overrides: Partial<AuthResponse> = {}): AuthResponse {
|
||||
return {
|
||||
accessToken: 'mock-access-token',
|
||||
// Fixed timestamp keeps fixtures deterministic.
|
||||
expiresAt: '2099-01-01T00:00:00.000Z',
|
||||
user: mockUser,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import type { LoginRequest } from '@/features/auth/services/types';
|
||||
import type { ProblemDetails } from '@/lib/api-client';
|
||||
import { API_BASE, makeAuthResponse, TEST_CREDENTIALS } from './fixtures';
|
||||
|
||||
function problem(status: number, title: string, detail?: string): ProblemDetails {
|
||||
return {
|
||||
type: 'about:blank',
|
||||
title,
|
||||
status,
|
||||
detail,
|
||||
traceId: '00-mock-trace-00',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Default auth mocks aligned with the real backend contract:
|
||||
* POST /api/v1/auth/login, /refresh, /revoke. Tests override these per case
|
||||
* via `server.use(...)` to simulate failures and 401 flows.
|
||||
*/
|
||||
export const authHandlers = [
|
||||
http.post(`${API_BASE}/api/v1/auth/login`, async ({ request }) => {
|
||||
const body = (await request.json()) as LoginRequest;
|
||||
if (body.email === TEST_CREDENTIALS.email && body.password === TEST_CREDENTIALS.password) {
|
||||
return HttpResponse.json(makeAuthResponse());
|
||||
}
|
||||
return HttpResponse.json(problem(401, 'Invalid email or password'), { status: 401 });
|
||||
}),
|
||||
|
||||
// By default refresh succeeds (simulates a valid httpOnly cookie present).
|
||||
http.post(`${API_BASE}/api/v1/auth/refresh`, () => {
|
||||
return HttpResponse.json(makeAuthResponse());
|
||||
}),
|
||||
|
||||
http.post(`${API_BASE}/api/v1/auth/revoke`, () => {
|
||||
return new HttpResponse(null, { status: 204 });
|
||||
}),
|
||||
|
||||
http.post(`${API_BASE}/api/v1/Auth/change-password`, async ({ request }) => {
|
||||
const body = (await request.json()) as { currentPassword: string; newPassword: string };
|
||||
if (body.currentPassword === TEST_CREDENTIALS.password) {
|
||||
return new HttpResponse(null, { status: 200 });
|
||||
}
|
||||
return HttpResponse.json(
|
||||
problem(400, 'Incorrect password', 'Current password is incorrect.'),
|
||||
{ status: 400 },
|
||||
);
|
||||
}),
|
||||
];
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { renderApp, mockGuest } from '@/test/utils';
|
||||
import { TEST_CREDENTIALS } from '@/features/auth/mocks/fixtures';
|
||||
|
||||
describe('LoginPage', () => {
|
||||
it('shows validation errors when submitting an empty form', async () => {
|
||||
mockGuest();
|
||||
const user = userEvent.setup();
|
||||
renderApp('/login');
|
||||
|
||||
const submit = await screen.findByTestId('login-form-submit-button');
|
||||
await user.click(submit);
|
||||
|
||||
expect(await screen.findByTestId('login-email-error')).toBeInTheDocument();
|
||||
expect(await screen.findByTestId('login-password-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('logs in with valid credentials and lands on the dashboard', async () => {
|
||||
mockGuest();
|
||||
const user = userEvent.setup();
|
||||
renderApp('/login');
|
||||
|
||||
await user.type(await screen.findByTestId('login-email-input'), TEST_CREDENTIALS.email);
|
||||
await user.type(screen.getByTestId('login-password-input'), TEST_CREDENTIALS.password);
|
||||
await user.click(screen.getByTestId('login-form-submit-button'));
|
||||
|
||||
expect(await screen.findByTestId('dashboard-title')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows an error banner on invalid credentials', async () => {
|
||||
mockGuest();
|
||||
const user = userEvent.setup();
|
||||
renderApp('/login');
|
||||
|
||||
await user.type(await screen.findByTestId('login-email-input'), 'wrong@example.com');
|
||||
await user.type(screen.getByTestId('login-password-input'), 'wrongpassword');
|
||||
await user.click(screen.getByTestId('login-form-submit-button'));
|
||||
|
||||
const banner = await screen.findByTestId('login-error');
|
||||
expect(banner).toBeInTheDocument();
|
||||
|
||||
// Still on the login page.
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByTestId('dashboard-title')).not.toBeInTheDocument(),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useNavigate, useSearch } from '@tanstack/react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { useAuth } from '@/features/auth/context/auth-context';
|
||||
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
||||
import { loginFormSchema, type LoginFormData } from '@/features/auth/schemas/auth';
|
||||
|
||||
export function LoginPage() {
|
||||
const { t } = useTranslation();
|
||||
const { login } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const search = useSearch({ strict: false }) as { redirect?: string };
|
||||
const [serverError, setServerError] = useState<string | null>(null);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<LoginFormData>({
|
||||
resolver: zodResolver(loginFormSchema),
|
||||
mode: 'onTouched',
|
||||
defaultValues: { email: '', password: '' },
|
||||
});
|
||||
|
||||
const onSubmit = handleSubmit(async (values) => {
|
||||
setServerError(null);
|
||||
try {
|
||||
await login(values.email, values.password);
|
||||
await navigate({ to: (search.redirect as string | undefined) ?? '/dashboard' });
|
||||
} catch (err) {
|
||||
if (err instanceof ProblemDetailsError && err.status === 401) {
|
||||
setServerError(t('login.errors.invalidCredentials'));
|
||||
} else if (err instanceof NetworkError) {
|
||||
setServerError(t('errors.network'));
|
||||
} else {
|
||||
setServerError(t('login.errors.generic'));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center bg-secondary/40 p-4">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>{t('login.title')}</CardTitle>
|
||||
<CardDescription>{t('login.subtitle')}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={onSubmit} noValidate className="space-y-4">
|
||||
{serverError !== null && (
|
||||
<div
|
||||
role="alert"
|
||||
data-testid="login-error"
|
||||
className="rounded-md border border-destructive/50 bg-destructive/10 px-3 py-2 text-sm text-destructive"
|
||||
>
|
||||
{serverError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">{t('login.email')}</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
placeholder={t('login.emailPlaceholder')}
|
||||
data-testid="login-email-input"
|
||||
aria-invalid={errors.email !== undefined}
|
||||
{...register('email')}
|
||||
/>
|
||||
{errors.email && (
|
||||
<p
|
||||
className="text-sm text-destructive"
|
||||
data-testid="login-email-error"
|
||||
>
|
||||
{errors.email.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">{t('login.password')}</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
autoComplete="current-password"
|
||||
data-testid="login-password-input"
|
||||
aria-invalid={errors.password !== undefined}
|
||||
{...register('password')}
|
||||
/>
|
||||
{errors.password && (
|
||||
<p
|
||||
className="text-sm text-destructive"
|
||||
data-testid="login-password-error"
|
||||
>
|
||||
{errors.password.message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting}
|
||||
data-testid="login-form-submit-button"
|
||||
>
|
||||
{isSubmitting ? t('login.submitting') : t('login.submit')}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
passwordSchema,
|
||||
setupFormSchema,
|
||||
loginFormSchema,
|
||||
invitationCompleteFormSchema,
|
||||
} from '@/features/auth/schemas/auth';
|
||||
|
||||
describe('passwordSchema', () => {
|
||||
it('accepts a valid password', () => {
|
||||
expect(passwordSchema.safeParse('Password1!').success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a password that is too short', () => {
|
||||
expect(passwordSchema.safeParse('Pass1!').success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a password without an uppercase letter', () => {
|
||||
expect(passwordSchema.safeParse('password1!').success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a password without a digit', () => {
|
||||
expect(passwordSchema.safeParse('Password!').success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a password without a special character', () => {
|
||||
expect(passwordSchema.safeParse('Password1').success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setupFormSchema', () => {
|
||||
const valid = {
|
||||
name: 'Admin',
|
||||
email: 'admin@example.com',
|
||||
password: 'Password1!',
|
||||
confirmPassword: 'Password1!',
|
||||
language: 'nl' as const,
|
||||
};
|
||||
|
||||
it('accepts valid setup data', () => {
|
||||
expect(setupFormSchema.safeParse(valid).success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects when passwords do not match', () => {
|
||||
const result = setupFormSchema.safeParse({ ...valid, confirmPassword: 'Different1!' });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects empty name', () => {
|
||||
expect(setupFormSchema.safeParse({ ...valid, name: '' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects name exceeding 255 characters', () => {
|
||||
expect(setupFormSchema.safeParse({ ...valid, name: 'a'.repeat(256) }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects invalid email format', () => {
|
||||
expect(setupFormSchema.safeParse({ ...valid, email: 'not-an-email' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects empty email', () => {
|
||||
expect(setupFormSchema.safeParse({ ...valid, email: '' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects invalid language', () => {
|
||||
expect(setupFormSchema.safeParse({ ...valid, language: 'fr' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts "en" as language', () => {
|
||||
expect(setupFormSchema.safeParse({ ...valid, language: 'en' }).success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loginFormSchema', () => {
|
||||
it('accepts valid login credentials', () => {
|
||||
expect(loginFormSchema.safeParse({ email: 'user@example.com', password: 'anypass' }).success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects empty email', () => {
|
||||
expect(loginFormSchema.safeParse({ email: '', password: 'pass' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects invalid email format', () => {
|
||||
expect(loginFormSchema.safeParse({ email: 'not-email', password: 'pass' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects empty password', () => {
|
||||
expect(loginFormSchema.safeParse({ email: 'user@example.com', password: '' }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('invitationCompleteFormSchema', () => {
|
||||
const valid = {
|
||||
name: 'New User',
|
||||
password: 'Password1!',
|
||||
confirmPassword: 'Password1!',
|
||||
};
|
||||
|
||||
it('accepts valid invitation completion data', () => {
|
||||
expect(invitationCompleteFormSchema.safeParse(valid).success).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects when passwords do not match', () => {
|
||||
expect(
|
||||
invitationCompleteFormSchema.safeParse({ ...valid, confirmPassword: 'Different1!' }).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects empty name', () => {
|
||||
expect(invitationCompleteFormSchema.safeParse({ ...valid, name: '' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects weak password', () => {
|
||||
expect(
|
||||
invitationCompleteFormSchema.safeParse({
|
||||
...valid,
|
||||
password: 'weak',
|
||||
confirmPassword: 'weak',
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
// Shared password validation schema matching backend rules:
|
||||
// - Minimum 8 characters
|
||||
// - At least 1 uppercase letter
|
||||
// - At least 1 digit
|
||||
// - At least 1 special character
|
||||
export const passwordSchema = z.string()
|
||||
.min(8, 'Wachtwoord moet minstens 8 tekens bevatten')
|
||||
.regex(/[A-Z]/, 'Wachtwoord moet minstens één hoofdletter bevatten')
|
||||
.regex(/[0-9]/, 'Wachtwoord moet minstens één cijfer bevatten')
|
||||
.regex(
|
||||
/[!@#$%^&*()\-_=+[\]{}|;:,.<>?]/,
|
||||
'Wachtwoord moet minstens één speciaal teken bevatten'
|
||||
);
|
||||
|
||||
export const confirmPasswordSchema = z.string()
|
||||
.min(1, 'Bevestig wachtwoord is vereist');
|
||||
|
||||
// Setup form schema
|
||||
export const setupFormSchema = z.object({
|
||||
name: z.string()
|
||||
.min(1, 'Naam is vereist')
|
||||
.max(255, 'Naam mag maximaal 255 tekens zijn'),
|
||||
email: z.string()
|
||||
.min(1, 'E-mailadres is vereist')
|
||||
.email('Voer een geldig e-mailadres in'),
|
||||
password: passwordSchema,
|
||||
confirmPassword: confirmPasswordSchema,
|
||||
language: z.enum(['en', 'nl'])
|
||||
}).refine((data) => data.password === data.confirmPassword, {
|
||||
message: 'Wachtwoorden komen niet overeen',
|
||||
path: ['confirmPassword']
|
||||
});
|
||||
|
||||
export type SetupFormData = z.infer<typeof setupFormSchema>;
|
||||
|
||||
// Invitation completion form schema
|
||||
export const invitationCompleteFormSchema = z.object({
|
||||
name: z.string()
|
||||
.min(1, 'Naam is vereist')
|
||||
.max(255, 'Naam mag maximaal 255 tekens zijn'),
|
||||
password: passwordSchema,
|
||||
confirmPassword: confirmPasswordSchema
|
||||
}).refine((data) => data.password === data.confirmPassword, {
|
||||
message: 'Wachtwoorden komen niet overeen',
|
||||
path: ['confirmPassword']
|
||||
});
|
||||
|
||||
export type InvitationCompleteFormData = z.infer<typeof invitationCompleteFormSchema>;
|
||||
|
||||
// Login form schema (password only)
|
||||
export const loginFormSchema = z.object({
|
||||
email: z.string()
|
||||
.min(1, 'E-mailadres is vereist')
|
||||
.email('Voer een geldig e-mailadres in'),
|
||||
password: z.string()
|
||||
.min(1, 'Wachtwoord is vereist')
|
||||
});
|
||||
|
||||
export type LoginFormData = z.infer<typeof loginFormSchema>;
|
||||
@@ -0,0 +1,21 @@
|
||||
// Roles aligned with backend authorization.
|
||||
export type UserRole = 'Owner' | 'Administrator' | 'User';
|
||||
|
||||
export interface User {
|
||||
id: string; // UUID
|
||||
email: string;
|
||||
name: string;
|
||||
role: UserRole;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
accessToken: string; // JWT access token
|
||||
expiresAt: string; // ISO timestamp
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface LoginRequest {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
Reference in New Issue
Block a user