forked from cardosofelipe/fast-next-template
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:
114
frontend/src/components/auth/AuthGuard.tsx
Normal file
114
frontend/src/components/auth/AuthGuard.tsx
Normal 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}</>;
|
||||
}
|
||||
209
frontend/src/components/auth/LoginForm.tsx
Normal file
209
frontend/src/components/auth/LoginForm.tsx
Normal 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'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>
|
||||
);
|
||||
}
|
||||
315
frontend/src/components/auth/PasswordResetConfirmForm.tsx
Normal file
315
frontend/src/components/auth/PasswordResetConfirmForm.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
192
frontend/src/components/auth/PasswordResetRequestForm.tsx
Normal file
192
frontend/src/components/auth/PasswordResetRequestForm.tsx
Normal 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'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>
|
||||
);
|
||||
}
|
||||
311
frontend/src/components/auth/RegisterForm.tsx
Normal file
311
frontend/src/components/auth/RegisterForm.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -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';
|
||||
|
||||
Reference in New Issue
Block a user