Add password reset functionality with form components, pages, and tests

- Implemented `PasswordResetRequestForm` and `PasswordResetConfirmForm` components with email and password validation, strength indicators, and error handling.
- Added dedicated pages for requesting and confirming password resets, integrated with React Query hooks and Next.js API routes.
- Included tests for validation rules, UI states, and token handling to ensure proper functionality and coverage.
- Updated ESLint and configuration files for new components and pages.
- Enhanced `IMPLEMENTATION_PLAN.md` with updated task details and documentation for password reset workflows.
This commit is contained in:
Felipe Cardoso
2025-11-01 00:57:57 +01:00
parent dbb05289b2
commit 925950d58e
25 changed files with 2306 additions and 74 deletions

View File

@@ -0,0 +1,19 @@
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Authentication',
};
export default function AuthLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<div className="flex min-h-screen items-center justify-center bg-gray-50 dark:bg-gray-900 px-4 py-12 sm:px-6 lg:px-8">
<div className="w-full max-w-md space-y-8">
{children}
</div>
</div>
);
}

View File

@@ -0,0 +1,23 @@
'use client';
import { LoginForm } from '@/components/auth/LoginForm';
export default function LoginPage() {
return (
<div className="space-y-6">
<div className="text-center">
<h2 className="text-3xl font-bold tracking-tight">
Sign in to your account
</h2>
<p className="mt-2 text-sm text-muted-foreground">
Access your dashboard and manage your account
</p>
</div>
<LoginForm
showRegisterLink
showPasswordResetLink
/>
</div>
);
}

View File

@@ -0,0 +1,67 @@
/**
* Password Reset Confirm Page
* Users set a new password using the token from their email
*/
'use client';
import { useSearchParams, useRouter } from 'next/navigation';
import { PasswordResetConfirmForm } from '@/components/auth/PasswordResetConfirmForm';
import { Alert } from '@/components/ui/alert';
import Link from 'next/link';
export default function PasswordResetConfirmPage() {
const searchParams = useSearchParams();
const router = useRouter();
const token = searchParams.get('token');
// Handle successful password reset
const handleSuccess = () => {
// Wait 3 seconds then redirect to login
setTimeout(() => {
router.push('/login');
}, 3000);
};
// If no token in URL, show error
if (!token) {
return (
<div className="space-y-6">
<div className="text-center">
<h2 className="text-3xl font-bold tracking-tight">
Invalid Reset Link
</h2>
</div>
<Alert variant="destructive">
<p className="text-sm">
This password reset link is invalid or has expired. Please request a new
password reset.
</p>
</Alert>
<div className="text-center">
<Link
href="/password-reset"
className="text-sm text-primary underline-offset-4 hover:underline font-medium"
>
Request new reset link
</Link>
</div>
</div>
);
}
return (
<div className="space-y-6">
<div className="text-center">
<h2 className="text-3xl font-bold tracking-tight">Set new password</h2>
<p className="mt-2 text-sm text-muted-foreground">
Choose a strong password for your account
</p>
</div>
<PasswordResetConfirmForm token={token} onSuccess={handleSuccess} showLoginLink />
</div>
);
}

View File

@@ -0,0 +1,25 @@
/**
* Password Reset Request Page
* Users enter their email to receive reset instructions
*/
'use client';
import { PasswordResetRequestForm } from '@/components/auth/PasswordResetRequestForm';
export default function PasswordResetPage() {
return (
<div className="space-y-6">
<div className="text-center">
<h2 className="text-3xl font-bold tracking-tight">
Reset your password
</h2>
<p className="mt-2 text-sm text-muted-foreground">
We&apos;ll send you an email with instructions to reset your password
</p>
</div>
<PasswordResetRequestForm showLoginLink />
</div>
);
}

View File

@@ -0,0 +1,20 @@
'use client';
import { RegisterForm } from '@/components/auth/RegisterForm';
export default function RegisterPage() {
return (
<div className="space-y-6">
<div className="text-center">
<h2 className="text-3xl font-bold tracking-tight">
Create your account
</h2>
<p className="mt-2 text-sm text-muted-foreground">
Get started with your free account today
</p>
</div>
<RegisterForm showLoginLink />
</div>
);
}

View File

@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { Providers } from "./providers";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -13,8 +14,8 @@ const geistMono = Geist_Mono({
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
title: "FastNext Template",
description: "FastAPI + Next.js Template",
};
export default function RootLayout({
@@ -27,7 +28,7 @@ export default function RootLayout({
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
<Providers>{children}</Providers>
</body>
</html>
);

View File

@@ -0,0 +1,30 @@
'use client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { useState } from 'react';
export function Providers({ children }: { children: React.ReactNode }) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000, // 1 minute
retry: 1,
refetchOnWindowFocus: true,
},
mutations: {
retry: false,
},
},
})
);
return (
<QueryClientProvider client={queryClient}>
{children}
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
}

View File

@@ -0,0 +1,114 @@
/**
* AuthGuard Component
* Protects routes by ensuring user is authenticated
* Redirects to login if not authenticated, preserving return URL
*/
'use client';
import { useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { useAuthStore } from '@/stores/authStore';
import { useMe } from '@/lib/api/hooks/useAuth';
import config from '@/config/app.config';
interface AuthGuardProps {
children: React.ReactNode;
requireAdmin?: boolean;
fallback?: React.ReactNode;
}
/**
* Loading spinner component
*/
function LoadingSpinner() {
return (
<div className="flex min-h-screen items-center justify-center">
<div className="flex flex-col items-center space-y-4">
<div className="h-12 w-12 animate-spin rounded-full border-4 border-gray-300 border-t-primary"></div>
<p className="text-sm text-muted-foreground">Loading...</p>
</div>
</div>
);
}
/**
* AuthGuard - Client component for route protection
*
* @param children - Protected content to render if authenticated
* @param requireAdmin - If true, requires user to be admin (is_superuser)
* @param fallback - Optional fallback component while loading
*
* @example
* ```tsx
* // In app/(authenticated)/layout.tsx
* export default function AuthenticatedLayout({ children }) {
* return (
* <AuthGuard>
* {children}
* </AuthGuard>
* );
* }
*
* // For admin routes
* export default function AdminLayout({ children }) {
* return (
* <AuthGuard requireAdmin>
* {children}
* </AuthGuard>
* );
* }
* ```
*/
export function AuthGuard({ children, requireAdmin = false, fallback }: AuthGuardProps) {
const router = useRouter();
const pathname = usePathname();
const { isAuthenticated, isLoading: authLoading, user } = useAuthStore();
// Fetch user data if authenticated but user not loaded
const { isLoading: userLoading } = useMe();
// Determine overall loading state
const isLoading = authLoading || (isAuthenticated && !user && userLoading);
useEffect(() => {
// If not loading and not authenticated, redirect to login
if (!isLoading && !isAuthenticated) {
// Preserve intended destination
const returnUrl = pathname !== config.routes.login
? `?returnUrl=${encodeURIComponent(pathname)}`
: '';
router.push(`${config.routes.login}${returnUrl}`);
}
// Note: 401 errors are handled by API interceptor which clears auth and redirects
}, [isLoading, isAuthenticated, pathname, router]);
// Check admin requirement
useEffect(() => {
if (requireAdmin && isAuthenticated && user && !user.is_superuser) {
// User is authenticated but not admin
console.warn('Access denied: Admin privileges required');
// TODO: Create dedicated 403 Forbidden page in Phase 4
router.push(config.routes.home);
}
}, [requireAdmin, isAuthenticated, user, router]);
// Show loading state
if (isLoading) {
return fallback ? <>{fallback}</> : <LoadingSpinner />;
}
// Show nothing if redirecting
if (!isAuthenticated) {
return null;
}
// Check admin requirement
if (requireAdmin && !user?.is_superuser) {
return null; // Will redirect via useEffect
}
// Render protected content
return <>{children}</>;
}

View File

@@ -0,0 +1,209 @@
/**
* LoginForm Component
* Handles user authentication with email and password
* Integrates with backend API and auth store
*/
'use client';
import { useState } from 'react';
import Link from 'next/link';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert } from '@/components/ui/alert';
import { useLogin } from '@/lib/api/hooks/useAuth';
import { getGeneralError, getFieldErrors } from '@/lib/api/errors';
import type { APIError } from '@/lib/api/errors';
import config from '@/config/app.config';
// ============================================================================
// Validation Schema
// ============================================================================
const loginSchema = z.object({
email: z
.string()
.min(1, 'Email is required')
.email('Please enter a valid email address'),
password: z
.string()
.min(1, 'Password is required')
.min(8, 'Password must be at least 8 characters')
.regex(/[0-9]/, 'Password must contain at least one number')
.regex(/[A-Z]/, 'Password must contain at least one uppercase letter'),
});
type LoginFormData = z.infer<typeof loginSchema>;
// ============================================================================
// Component
// ============================================================================
interface LoginFormProps {
/** Optional callback after successful login */
onSuccess?: () => void;
/** Show registration link */
showRegisterLink?: boolean;
/** Show password reset link */
showPasswordResetLink?: boolean;
/** Custom className for form container */
className?: string;
}
/**
* LoginForm - User authentication form
*
* Features:
* - Email and password validation
* - Loading states
* - Server error display
* - Links to registration and password reset
*
* @example
* ```tsx
* <LoginForm
* showRegisterLink
* showPasswordResetLink
* onSuccess={() => router.push('/dashboard')}
* />
* ```
*/
export function LoginForm({
onSuccess,
showRegisterLink = true,
showPasswordResetLink = true,
className,
}: LoginFormProps) {
const [serverError, setServerError] = useState<string | null>(null);
const loginMutation = useLogin();
const form = useForm<LoginFormData>({
resolver: zodResolver(loginSchema),
defaultValues: {
email: '',
password: '',
},
});
const onSubmit = async (data: LoginFormData) => {
try {
// Clear previous errors
setServerError(null);
form.clearErrors();
// Attempt login
await loginMutation.mutateAsync(data);
// Success callback
onSuccess?.();
} catch (error) {
// Handle API errors
const errors = error as APIError[];
// Set general error message
const generalError = getGeneralError(errors);
if (generalError) {
setServerError(generalError);
}
// Set field-specific errors
const fieldErrors = getFieldErrors(errors);
Object.entries(fieldErrors).forEach(([field, message]) => {
if (field === 'email' || field === 'password') {
form.setError(field, { message });
}
});
}
};
const isSubmitting = form.formState.isSubmitting || loginMutation.isPending;
return (
<div className={className}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{/* Server Error Alert */}
{serverError && (
<Alert variant="destructive">
<p className="text-sm">{serverError}</p>
</Alert>
)}
{/* Email Field */}
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
placeholder="you@example.com"
autoComplete="email"
disabled={isSubmitting}
{...form.register('email')}
aria-invalid={!!form.formState.errors.email}
aria-describedby={form.formState.errors.email ? 'email-error' : undefined}
/>
{form.formState.errors.email && (
<p id="email-error" className="text-sm text-destructive">
{form.formState.errors.email.message}
</p>
)}
</div>
{/* Password Field */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label htmlFor="password">Password</Label>
{showPasswordResetLink && (
<Link
href="/password-reset"
className="text-sm text-muted-foreground hover:text-primary underline-offset-4 hover:underline"
>
Forgot password?
</Link>
)}
</div>
<Input
id="password"
type="password"
placeholder="Enter your password"
autoComplete="current-password"
disabled={isSubmitting}
{...form.register('password')}
aria-invalid={!!form.formState.errors.password}
aria-describedby={form.formState.errors.password ? 'password-error' : undefined}
/>
{form.formState.errors.password && (
<p id="password-error" className="text-sm text-destructive">
{form.formState.errors.password.message}
</p>
)}
</div>
{/* Submit Button */}
<Button
type="submit"
className="w-full"
disabled={isSubmitting}
>
{isSubmitting ? 'Signing in...' : 'Sign in'}
</Button>
{/* Registration Link */}
{showRegisterLink && config.features.enableRegistration && (
<p className="text-center text-sm text-muted-foreground">
Don&apos;t have an account?{' '}
<Link
href={config.routes.register}
className="text-primary underline-offset-4 hover:underline font-medium"
>
Sign up
</Link>
</p>
)}
</form>
</div>
);
}

View File

@@ -0,0 +1,315 @@
/**
* PasswordResetConfirmForm Component
* Handles password reset with token from email
* Integrates with backend API password reset confirm flow
*/
'use client';
import { useState } from 'react';
import Link from 'next/link';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert } from '@/components/ui/alert';
import { usePasswordResetConfirm } from '@/lib/api/hooks/useAuth';
import { getGeneralError, getFieldErrors } from '@/lib/api/errors';
import type { APIError } from '@/lib/api/errors';
// ============================================================================
// Validation Schema
// ============================================================================
const resetConfirmSchema = z
.object({
token: z.string().min(1, 'Reset token is required'),
new_password: z
.string()
.min(1, 'New password is required')
.min(8, 'Password must be at least 8 characters')
.regex(/[0-9]/, 'Password must contain at least one number')
.regex(/[A-Z]/, 'Password must contain at least one uppercase letter'),
confirm_password: z.string().min(1, 'Please confirm your password'),
})
.refine((data) => data.new_password === data.confirm_password, {
message: 'Passwords do not match',
path: ['confirm_password'],
});
type ResetConfirmFormData = z.infer<typeof resetConfirmSchema>;
// ============================================================================
// Helper Functions
// ============================================================================
/**
* Calculate password strength based on requirements
*/
function calculatePasswordStrength(password: string): {
hasMinLength: boolean;
hasNumber: boolean;
hasUppercase: boolean;
strength: number;
} {
const hasMinLength = password.length >= 8;
const hasNumber = /[0-9]/.test(password);
const hasUppercase = /[A-Z]/.test(password);
const strength =
(hasMinLength ? 33 : 0) + (hasNumber ? 33 : 0) + (hasUppercase ? 34 : 0);
return { hasMinLength, hasNumber, hasUppercase, strength };
}
// ============================================================================
// Component
// ============================================================================
interface PasswordResetConfirmFormProps {
/** Reset token from URL query parameter */
token: string;
/** Optional callback after successful reset */
onSuccess?: () => void;
/** Show login link */
showLoginLink?: boolean;
/** Custom className for form container */
className?: string;
}
/**
* PasswordResetConfirmForm - Reset password with token
*
* Features:
* - Token validation
* - New password validation with strength indicator
* - Password confirmation matching
* - Loading states
* - Server error display
* - Success message
* - Link back to login
*
* @example
* ```tsx
* <PasswordResetConfirmForm
* token={searchParams.token}
* showLoginLink
* onSuccess={() => router.push('/login')}
* />
* ```
*/
export function PasswordResetConfirmForm({
token,
onSuccess,
showLoginLink = true,
className,
}: PasswordResetConfirmFormProps) {
const [serverError, setServerError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const resetMutation = usePasswordResetConfirm();
const form = useForm<ResetConfirmFormData>({
resolver: zodResolver(resetConfirmSchema),
defaultValues: {
token,
new_password: '',
confirm_password: '',
},
});
const watchPassword = form.watch('new_password');
const passwordStrength = calculatePasswordStrength(watchPassword);
const onSubmit = async (data: ResetConfirmFormData) => {
try {
// Clear previous errors and success message
setServerError(null);
setSuccessMessage(null);
form.clearErrors();
// Confirm password reset
await resetMutation.mutateAsync({
token: data.token,
new_password: data.new_password,
});
// Show success message
setSuccessMessage(
'Your password has been successfully reset. You can now log in with your new password.'
);
// Reset form
form.reset({ token, new_password: '', confirm_password: '' });
// Success callback
onSuccess?.();
} catch (error) {
// Handle API errors
const errors = error as APIError[];
// Set general error message
const generalError = getGeneralError(errors);
if (generalError) {
setServerError(generalError);
}
// Set field-specific errors
const fieldErrors = getFieldErrors(errors);
Object.entries(fieldErrors).forEach(([field, message]) => {
if (field === 'token' || field === 'new_password') {
form.setError(field, { message });
}
});
}
};
const isSubmitting = form.formState.isSubmitting || resetMutation.isPending;
return (
<div className={className}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{/* Success Alert */}
{successMessage && (
<Alert>
<p className="text-sm">{successMessage}</p>
</Alert>
)}
{/* Server Error Alert */}
{serverError && (
<Alert variant="destructive">
<p className="text-sm">{serverError}</p>
</Alert>
)}
{/* Instructions */}
<p className="text-sm text-muted-foreground">
Enter your new password below. Make sure it meets all security requirements.
</p>
{/* Hidden Token Field (for form submission) */}
<input type="hidden" {...form.register('token')} />
{/* New Password Field */}
<div className="space-y-2">
<Label htmlFor="new_password">
New Password <span className="text-destructive">*</span>
</Label>
<Input
id="new_password"
type="password"
placeholder="Enter new password"
autoComplete="new-password"
disabled={isSubmitting}
{...form.register('new_password')}
aria-invalid={!!form.formState.errors.new_password}
aria-describedby={
form.formState.errors.new_password
? 'new-password-error'
: 'password-requirements'
}
/>
{form.formState.errors.new_password && (
<p id="new-password-error" className="text-sm text-destructive">
{form.formState.errors.new_password.message}
</p>
)}
{/* Password Strength Indicator */}
{watchPassword && (
<div className="space-y-2" id="password-requirements">
<div className="h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
<div
className={`h-full transition-all ${
passwordStrength.strength === 100
? 'bg-green-500'
: passwordStrength.strength >= 66
? 'bg-yellow-500'
: 'bg-red-500'
}`}
style={{ width: `${passwordStrength.strength}%` }}
/>
</div>
<ul className="text-xs space-y-1">
<li
className={
passwordStrength.hasMinLength
? 'text-green-600 dark:text-green-400'
: 'text-muted-foreground'
}
>
{passwordStrength.hasMinLength ? '✓' : '○'} At least 8 characters
</li>
<li
className={
passwordStrength.hasNumber
? 'text-green-600 dark:text-green-400'
: 'text-muted-foreground'
}
>
{passwordStrength.hasNumber ? '✓' : '○'} Contains a number
</li>
<li
className={
passwordStrength.hasUppercase
? 'text-green-600 dark:text-green-400'
: 'text-muted-foreground'
}
>
{passwordStrength.hasUppercase ? '✓' : '○'} Contains an uppercase
letter
</li>
</ul>
</div>
)}
</div>
{/* Confirm Password Field */}
<div className="space-y-2">
<Label htmlFor="confirm_password">
Confirm Password <span className="text-destructive">*</span>
</Label>
<Input
id="confirm_password"
type="password"
placeholder="Re-enter new password"
autoComplete="new-password"
disabled={isSubmitting}
{...form.register('confirm_password')}
aria-invalid={!!form.formState.errors.confirm_password}
aria-describedby={
form.formState.errors.confirm_password
? 'confirm-password-error'
: undefined
}
/>
{form.formState.errors.confirm_password && (
<p id="confirm-password-error" className="text-sm text-destructive">
{form.formState.errors.confirm_password.message}
</p>
)}
</div>
{/* Submit Button */}
<Button type="submit" className="w-full" disabled={isSubmitting}>
{isSubmitting ? 'Resetting Password...' : 'Reset Password'}
</Button>
{/* Login Link */}
{showLoginLink && (
<p className="text-center text-sm text-muted-foreground">
Remember your password?{' '}
<Link
href="/login"
className="text-primary underline-offset-4 hover:underline font-medium"
>
Back to login
</Link>
</p>
)}
</form>
</div>
);
}

View File

@@ -0,0 +1,192 @@
/**
* PasswordResetRequestForm Component
* Handles password reset email request
* Integrates with backend API password reset flow
*/
'use client';
import { useState } from 'react';
import Link from 'next/link';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert } from '@/components/ui/alert';
import { usePasswordResetRequest } from '@/lib/api/hooks/useAuth';
import { getGeneralError, getFieldErrors } from '@/lib/api/errors';
import type { APIError } from '@/lib/api/errors';
// ============================================================================
// Validation Schema
// ============================================================================
const resetRequestSchema = z.object({
email: z
.string()
.min(1, 'Email is required')
.email('Please enter a valid email address'),
});
type ResetRequestFormData = z.infer<typeof resetRequestSchema>;
// ============================================================================
// Component
// ============================================================================
interface PasswordResetRequestFormProps {
/** Optional callback after successful request */
onSuccess?: () => void;
/** Show login link */
showLoginLink?: boolean;
/** Custom className for form container */
className?: string;
}
/**
* PasswordResetRequestForm - Request password reset email
*
* Features:
* - Email validation
* - Loading states
* - Server error display
* - Success message
* - Link back to login
*
* @example
* ```tsx
* <PasswordResetRequestForm
* showLoginLink
* onSuccess={() => setEmailSent(true)}
* />
* ```
*/
export function PasswordResetRequestForm({
onSuccess,
showLoginLink = true,
className,
}: PasswordResetRequestFormProps) {
const [serverError, setServerError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const resetMutation = usePasswordResetRequest();
const form = useForm<ResetRequestFormData>({
resolver: zodResolver(resetRequestSchema),
defaultValues: {
email: '',
},
});
const onSubmit = async (data: ResetRequestFormData) => {
try {
// Clear previous errors and success message
setServerError(null);
setSuccessMessage(null);
form.clearErrors();
// Request password reset
await resetMutation.mutateAsync({ email: data.email });
// Show success message
setSuccessMessage(
'Password reset instructions have been sent to your email address. Please check your inbox.'
);
// Reset form
form.reset();
// Success callback
onSuccess?.();
} catch (error) {
// Handle API errors
const errors = error as APIError[];
// Set general error message
const generalError = getGeneralError(errors);
if (generalError) {
setServerError(generalError);
}
// Set field-specific errors
const fieldErrors = getFieldErrors(errors);
Object.entries(fieldErrors).forEach(([field, message]) => {
if (field === 'email') {
form.setError(field, { message });
}
});
}
};
const isSubmitting = form.formState.isSubmitting || resetMutation.isPending;
return (
<div className={className}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{/* Success Alert */}
{successMessage && (
<Alert>
<p className="text-sm">{successMessage}</p>
</Alert>
)}
{/* Server Error Alert */}
{serverError && (
<Alert variant="destructive">
<p className="text-sm">{serverError}</p>
</Alert>
)}
{/* Instructions */}
<p className="text-sm text-muted-foreground">
Enter your email address and we&apos;ll send you instructions to reset your password.
</p>
{/* Email Field */}
<div className="space-y-2">
<Label htmlFor="email">
Email <span className="text-destructive">*</span>
</Label>
<Input
id="email"
type="email"
placeholder="you@example.com"
autoComplete="email"
disabled={isSubmitting}
{...form.register('email')}
aria-invalid={!!form.formState.errors.email}
aria-describedby={form.formState.errors.email ? 'email-error' : undefined}
/>
{form.formState.errors.email && (
<p id="email-error" className="text-sm text-destructive">
{form.formState.errors.email.message}
</p>
)}
</div>
{/* Submit Button */}
<Button
type="submit"
className="w-full"
disabled={isSubmitting}
>
{isSubmitting ? 'Sending...' : 'Send Reset Instructions'}
</Button>
{/* Login Link */}
{showLoginLink && (
<p className="text-center text-sm text-muted-foreground">
Remember your password?{' '}
<Link
href="/login"
className="text-primary underline-offset-4 hover:underline font-medium"
>
Back to login
</Link>
</p>
)}
</form>
</div>
);
}

View File

@@ -0,0 +1,311 @@
/**
* RegisterForm Component
* Handles user registration with validation
* Integrates with backend API and auth store
*/
'use client';
import { useState } from 'react';
import Link from 'next/link';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert } from '@/components/ui/alert';
import { useRegister } from '@/lib/api/hooks/useAuth';
import { getGeneralError, getFieldErrors } from '@/lib/api/errors';
import type { APIError } from '@/lib/api/errors';
import config from '@/config/app.config';
// ============================================================================
// Validation Schema
// ============================================================================
const registerSchema = z
.object({
email: z
.string()
.min(1, 'Email is required')
.email('Please enter a valid email address'),
first_name: z
.string()
.min(1, 'First name is required')
.min(2, 'First name must be at least 2 characters')
.max(50, 'First name must not exceed 50 characters'),
last_name: z
.string()
.max(50, 'Last name must not exceed 50 characters')
.optional()
.or(z.literal('')), // Allow empty string
password: z
.string()
.min(1, 'Password is required')
.min(8, 'Password must be at least 8 characters')
.regex(/[0-9]/, 'Password must contain at least one number')
.regex(/[A-Z]/, 'Password must contain at least one uppercase letter'),
confirmPassword: z
.string()
.min(1, 'Please confirm your password'),
})
.refine((data) => data.password === data.confirmPassword, {
message: 'Passwords do not match',
path: ['confirmPassword'],
});
type RegisterFormData = z.infer<typeof registerSchema>;
// ============================================================================
// Component
// ============================================================================
interface RegisterFormProps {
/** Optional callback after successful registration */
onSuccess?: () => void;
/** Show login link */
showLoginLink?: boolean;
/** Custom className for form container */
className?: string;
}
/**
* RegisterForm - User registration form
*
* Features:
* - Email, name, and password validation
* - Password confirmation matching
* - Password strength requirements display
* - Loading states
* - Server error display
* - Link to login page
*
* @example
* ```tsx
* <RegisterForm
* showLoginLink
* onSuccess={() => router.push('/dashboard')}
* />
* ```
*/
export function RegisterForm({
onSuccess,
showLoginLink = true,
className,
}: RegisterFormProps) {
const [serverError, setServerError] = useState<string | null>(null);
const registerMutation = useRegister();
const form = useForm<RegisterFormData>({
resolver: zodResolver(registerSchema),
defaultValues: {
email: '',
first_name: '',
last_name: '',
password: '',
confirmPassword: '',
},
});
const onSubmit = async (data: RegisterFormData) => {
try {
// Clear previous errors
setServerError(null);
form.clearErrors();
// Prepare data for API (exclude confirmPassword)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { confirmPassword, ...registerData } = data;
// Attempt registration
await registerMutation.mutateAsync(registerData);
// Success callback
onSuccess?.();
} catch (error) {
// Handle API errors
const errors = error as APIError[];
// Set general error message
const generalError = getGeneralError(errors);
if (generalError) {
setServerError(generalError);
}
// Set field-specific errors
const fieldErrors = getFieldErrors(errors);
Object.entries(fieldErrors).forEach(([field, message]) => {
if (field in form.getValues()) {
form.setError(field as keyof RegisterFormData, { message });
}
});
}
};
const isSubmitting = form.formState.isSubmitting || registerMutation.isPending;
// Watch password to show strength requirements
const password = form.watch('password');
const hasMinLength = password.length >= 8;
const hasNumber = /[0-9]/.test(password);
const hasUppercase = /[A-Z]/.test(password);
return (
<div className={className}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
{/* Server Error Alert */}
{serverError && (
<Alert variant="destructive">
<p className="text-sm">{serverError}</p>
</Alert>
)}
{/* First Name Field */}
<div className="space-y-2">
<Label htmlFor="first_name">
First Name <span className="text-destructive">*</span>
</Label>
<Input
id="first_name"
type="text"
placeholder="John"
autoComplete="given-name"
disabled={isSubmitting}
{...form.register('first_name')}
aria-invalid={!!form.formState.errors.first_name}
aria-describedby={form.formState.errors.first_name ? 'first_name-error' : undefined}
/>
{form.formState.errors.first_name && (
<p id="first_name-error" className="text-sm text-destructive">
{form.formState.errors.first_name.message}
</p>
)}
</div>
{/* Last Name Field */}
<div className="space-y-2">
<Label htmlFor="last_name">Last Name</Label>
<Input
id="last_name"
type="text"
placeholder="Doe (optional)"
autoComplete="family-name"
disabled={isSubmitting}
{...form.register('last_name')}
aria-invalid={!!form.formState.errors.last_name}
aria-describedby={form.formState.errors.last_name ? 'last_name-error' : undefined}
/>
{form.formState.errors.last_name && (
<p id="last_name-error" className="text-sm text-destructive">
{form.formState.errors.last_name.message}
</p>
)}
</div>
{/* Email Field */}
<div className="space-y-2">
<Label htmlFor="email">
Email <span className="text-destructive">*</span>
</Label>
<Input
id="email"
type="email"
placeholder="you@example.com"
autoComplete="email"
disabled={isSubmitting}
{...form.register('email')}
aria-invalid={!!form.formState.errors.email}
aria-describedby={form.formState.errors.email ? 'email-error' : undefined}
/>
{form.formState.errors.email && (
<p id="email-error" className="text-sm text-destructive">
{form.formState.errors.email.message}
</p>
)}
</div>
{/* Password Field */}
<div className="space-y-2">
<Label htmlFor="password">
Password <span className="text-destructive">*</span>
</Label>
<Input
id="password"
type="password"
placeholder="Create a strong password"
autoComplete="new-password"
disabled={isSubmitting}
{...form.register('password')}
aria-invalid={!!form.formState.errors.password}
aria-describedby={form.formState.errors.password ? 'password-error password-requirements' : 'password-requirements'}
/>
{form.formState.errors.password && (
<p id="password-error" className="text-sm text-destructive">
{form.formState.errors.password.message}
</p>
)}
{/* Password Strength Indicator */}
{password.length > 0 && !form.formState.errors.password && (
<div id="password-requirements" className="space-y-1 text-xs">
<p className={hasMinLength ? 'text-green-600 dark:text-green-400' : 'text-muted-foreground'}>
{hasMinLength ? '✓' : '○'} At least 8 characters
</p>
<p className={hasNumber ? 'text-green-600 dark:text-green-400' : 'text-muted-foreground'}>
{hasNumber ? '✓' : '○'} Contains a number
</p>
<p className={hasUppercase ? 'text-green-600 dark:text-green-400' : 'text-muted-foreground'}>
{hasUppercase ? '✓' : '○'} Contains an uppercase letter
</p>
</div>
)}
</div>
{/* Confirm Password Field */}
<div className="space-y-2">
<Label htmlFor="confirmPassword">
Confirm Password <span className="text-destructive">*</span>
</Label>
<Input
id="confirmPassword"
type="password"
placeholder="Confirm your password"
autoComplete="new-password"
disabled={isSubmitting}
{...form.register('confirmPassword')}
aria-invalid={!!form.formState.errors.confirmPassword}
aria-describedby={form.formState.errors.confirmPassword ? 'confirmPassword-error' : undefined}
/>
{form.formState.errors.confirmPassword && (
<p id="confirmPassword-error" className="text-sm text-destructive">
{form.formState.errors.confirmPassword.message}
</p>
)}
</div>
{/* Submit Button */}
<Button
type="submit"
className="w-full"
disabled={isSubmitting}
>
{isSubmitting ? 'Creating account...' : 'Create account'}
</Button>
{/* Login Link */}
{showLoginLink && (
<p className="text-center text-sm text-muted-foreground">
Already have an account?{' '}
<Link
href={config.routes.login}
className="text-primary underline-offset-4 hover:underline font-medium"
>
Sign in
</Link>
</p>
)}
</form>
</div>
);
}

View File

@@ -1,4 +1,10 @@
// Authentication components
// Examples: LoginForm, RegisterForm, PasswordResetForm, etc.
export {};
// Route protection
export { AuthGuard } from './AuthGuard';
// Forms
export { LoginForm } from './LoginForm';
export { RegisterForm } from './RegisterForm';
export { PasswordResetRequestForm } from './PasswordResetRequestForm';
export { PasswordResetConfirmForm } from './PasswordResetConfirmForm';

View File

@@ -0,0 +1,36 @@
/**
* Configure the generated API client
* Integrates @hey-api/openapi-ts client with our auth logic
*
* This file wraps the auto-generated client without modifying generated code
* Note: @hey-api client doesn't support axios-style interceptors
* We configure it to work with existing manual client.ts for now
*/
import { client } from './generated/client.gen';
import config from '@/config/app.config';
/**
* Configure generated client with base URL
* Auth token injection handled via fetch interceptor pattern
*/
export function configureApiClient() {
client.setConfig({
baseURL: config.api.url,
});
}
// Configure client on module load
configureApiClient();
// Re-export configured client for use in hooks
export { client as generatedClient };
// Re-export all SDK functions
export * from './generated/sdk.gen';
// Re-export types
export type * from './generated/types.gen';
// Also export manual client for backward compatibility
export { apiClient } from './client';

View File

@@ -1,5 +1,5 @@
// React Query hooks for API calls
// Examples: useUsers, useAuth, useOrganizations, etc.
// See docs/API_INTEGRATION.md for patterns and examples
export {};
// Authentication hooks
export * from './useAuth';

View File

@@ -0,0 +1,343 @@
/**
* Authentication React Query Hooks
* Integrates with authStore for state management
* Implements all auth endpoints from backend API
*/
import { useEffect } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { apiClient } from '../client';
import { useAuthStore } from '@/stores/authStore';
import type { User } from '@/stores/authStore';
import type { APIError } from '../errors';
import config from '@/config/app.config';
// ============================================================================
// Types
// ============================================================================
export interface LoginCredentials {
email: string;
password: string;
}
export interface RegisterData {
email: string;
password: string;
first_name: string;
last_name?: string;
}
export interface PasswordResetRequest {
email: string;
}
export interface PasswordResetConfirm {
token: string;
new_password: string;
}
export interface PasswordChange {
current_password: string;
new_password: string;
}
export interface AuthResponse {
access_token: string;
refresh_token: string;
token_type: 'bearer';
user: User;
}
export interface SuccessResponse {
success: true;
message: string;
}
// ============================================================================
// Query Keys
// ============================================================================
export const authKeys = {
me: ['auth', 'me'] as const,
all: ['auth'] as const,
};
// ============================================================================
// Queries
// ============================================================================
/**
* Get current user from token
* GET /api/v1/auth/me
* Updates auth store with fetched user data
*/
export function useMe() {
const { isAuthenticated, accessToken } = useAuthStore();
const setUser = useAuthStore((state) => state.setUser);
const query = useQuery({
queryKey: authKeys.me,
queryFn: async (): Promise<User> => {
const response = await apiClient.get<User>('/auth/me');
return response.data;
},
enabled: isAuthenticated && !!accessToken,
staleTime: 5 * 60 * 1000, // 5 minutes
retry: 1, // Only retry once for auth endpoints
});
// Sync user data to auth store when fetched (TanStack Query v5 pattern)
useEffect(() => {
if (query.data) {
setUser(query.data);
}
}, [query.data, setUser]);
return query;
}
// ============================================================================
// Mutations
// ============================================================================
/**
* Login mutation
* POST /api/v1/auth/login
*/
export function useLogin() {
const router = useRouter();
const queryClient = useQueryClient();
const setAuth = useAuthStore((state) => state.setAuth);
return useMutation({
mutationFn: async (credentials: LoginCredentials): Promise<AuthResponse> => {
const response = await apiClient.post<AuthResponse>('/auth/login', credentials);
return response.data;
},
onSuccess: async (data) => {
const { access_token, refresh_token, user } = data;
// Update auth store with user and tokens
await setAuth(user, access_token, refresh_token);
// Invalidate and refetch user data
queryClient.invalidateQueries({ queryKey: authKeys.all });
// Redirect to home or intended destination
// TODO: Add redirect to intended route from query params
router.push('/');
},
onError: (errors: APIError[]) => {
console.error('Login failed:', errors);
// Error toast will be handled in the component
},
});
}
/**
* Register mutation
* POST /api/v1/auth/register
*/
export function useRegister() {
const router = useRouter();
const queryClient = useQueryClient();
const setAuth = useAuthStore((state) => state.setAuth);
return useMutation({
mutationFn: async (data: RegisterData): Promise<AuthResponse> => {
const response = await apiClient.post<AuthResponse>('/auth/register', data);
return response.data;
},
onSuccess: async (data) => {
const { access_token, refresh_token, user } = data;
// Update auth store with user and tokens
await setAuth(user, access_token, refresh_token);
// Invalidate and refetch user data
queryClient.invalidateQueries({ queryKey: authKeys.all });
// Redirect to home
router.push('/');
},
onError: (errors: APIError[]) => {
console.error('Registration failed:', errors);
// Error toast will be handled in the component
},
});
}
/**
* Logout mutation (current device only)
* POST /api/v1/auth/logout
*/
export function useLogout() {
const router = useRouter();
const queryClient = useQueryClient();
const clearAuth = useAuthStore((state) => state.clearAuth);
return useMutation({
mutationFn: async (): Promise<SuccessResponse> => {
const response = await apiClient.post<SuccessResponse>('/auth/logout');
return response.data;
},
onSuccess: async () => {
// Clear auth store
await clearAuth();
// Clear all React Query cache
queryClient.clear();
// Redirect to login
router.push(config.routes.login);
},
onError: async (errors: APIError[]) => {
console.error('Logout failed:', errors);
// Even if logout fails, clear local state
await clearAuth();
queryClient.clear();
router.push(config.routes.login);
},
});
}
/**
* Logout all devices mutation
* POST /api/v1/auth/logout-all
*/
export function useLogoutAll() {
const router = useRouter();
const queryClient = useQueryClient();
const clearAuth = useAuthStore((state) => state.clearAuth);
return useMutation({
mutationFn: async (): Promise<SuccessResponse> => {
const response = await apiClient.post<SuccessResponse>('/auth/logout-all');
return response.data;
},
onSuccess: async () => {
// Clear auth store
await clearAuth();
// Clear all React Query cache
queryClient.clear();
// Redirect to login
router.push(config.routes.login);
},
onError: async (errors: APIError[]) => {
console.error('Logout all failed:', errors);
// Even if logout fails, clear local state
await clearAuth();
queryClient.clear();
router.push(config.routes.login);
},
});
}
/**
* Password reset request mutation
* POST /api/v1/auth/password-reset/request
*/
export function usePasswordResetRequest() {
return useMutation({
mutationFn: async (data: PasswordResetRequest): Promise<SuccessResponse> => {
const response = await apiClient.post<SuccessResponse>(
'/auth/password-reset/request',
data
);
return response.data;
},
onSuccess: (data) => {
console.log('Password reset email sent:', data.message);
// Success toast will be handled in the component
},
onError: (errors: APIError[]) => {
console.error('Password reset request failed:', errors);
// Error toast will be handled in the component
},
});
}
/**
* Password reset confirm mutation
* POST /api/v1/auth/password-reset/confirm
*/
export function usePasswordResetConfirm() {
const router = useRouter();
return useMutation({
mutationFn: async (data: PasswordResetConfirm): Promise<SuccessResponse> => {
const response = await apiClient.post<SuccessResponse>(
'/auth/password-reset/confirm',
data
);
return response.data;
},
onSuccess: (data) => {
console.log('Password reset successful:', data.message);
// Redirect to login
router.push(`${config.routes.login}?reset=success`);
},
onError: (errors: APIError[]) => {
console.error('Password reset confirm failed:', errors);
// Error toast will be handled in the component
},
});
}
/**
* Change password mutation (authenticated users)
* PATCH /api/v1/users/me/password
*/
export function usePasswordChange() {
return useMutation({
mutationFn: async (data: PasswordChange): Promise<SuccessResponse> => {
const response = await apiClient.patch<SuccessResponse>(
'/users/me/password',
data
);
return response.data;
},
onSuccess: (data) => {
console.log('Password changed successfully:', data.message);
// Success toast will be handled in the component
},
onError: (errors: APIError[]) => {
console.error('Password change failed:', errors);
// Error toast will be handled in the component
},
});
}
// ============================================================================
// Convenience Hooks
// ============================================================================
/**
* Check if user is authenticated
* Convenience hook wrapping auth store
*/
export function useIsAuthenticated(): boolean {
return useAuthStore((state) => state.isAuthenticated);
}
/**
* Get current user
* Convenience hook wrapping auth store
*/
export function useCurrentUser(): User | null {
return useAuthStore((state) => state.user);
}
/**
* Check if current user is admin
*/
export function useIsAdmin(): boolean {
const user = useCurrentUser();
return user?.is_superuser === true;
}