website refactor
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Forgot Password Client Component
|
||||
*
|
||||
* Handles client-side forgot password flow.
|
||||
*/
|
||||
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { ForgotPasswordViewData } from '@/lib/builders/view-data/ForgotPasswordViewDataBuilder';
|
||||
import { ForgotPasswordTemplate } from '@/templates/auth/ForgotPasswordTemplate';
|
||||
import { ForgotPasswordMutation } from '@/lib/mutations/auth/ForgotPasswordMutation';
|
||||
import { ForgotPasswordViewModelBuilder } from '@/lib/builders/view-models/ForgotPasswordViewModelBuilder';
|
||||
import { ForgotPasswordViewModel } from '@/lib/view-models/auth/ForgotPasswordViewModel';
|
||||
|
||||
interface ForgotPasswordClientProps {
|
||||
viewData: ForgotPasswordViewData;
|
||||
}
|
||||
|
||||
export function ForgotPasswordClient({ viewData }: ForgotPasswordClientProps) {
|
||||
// Build ViewModel from ViewData
|
||||
const [viewModel, setViewModel] = useState<ForgotPasswordViewModel>(() =>
|
||||
ForgotPasswordViewModelBuilder.build(viewData)
|
||||
);
|
||||
|
||||
const [formData, setFormData] = useState({ email: '' });
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
|
||||
// Update submitting state
|
||||
setViewModel(prev => prev.withMutationState(true, null));
|
||||
|
||||
try {
|
||||
// Execute forgot password mutation
|
||||
const mutation = new ForgotPasswordMutation();
|
||||
const result = await mutation.execute({
|
||||
email: formData.email,
|
||||
});
|
||||
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
setViewModel(prev => prev.withMutationState(false, error));
|
||||
return;
|
||||
}
|
||||
|
||||
// Success
|
||||
const data = result.unwrap();
|
||||
setViewModel(prev => prev.withSuccess(data.message, data.magicLink || null));
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to send reset link';
|
||||
setViewModel(prev => prev.withMutationState(false, errorMessage));
|
||||
}
|
||||
};
|
||||
|
||||
// Build viewData for template
|
||||
const templateViewData: ForgotPasswordViewData = {
|
||||
...viewData,
|
||||
showSuccess: viewModel.showSuccess,
|
||||
successMessage: viewModel.successMessage || undefined,
|
||||
magicLink: viewModel.magicLink || undefined,
|
||||
formState: viewModel.formState,
|
||||
isSubmitting: viewModel.isSubmitting,
|
||||
submitError: viewModel.submitError,
|
||||
};
|
||||
|
||||
return (
|
||||
<ForgotPasswordTemplate
|
||||
viewData={templateViewData}
|
||||
formActions={{
|
||||
setFormData,
|
||||
handleSubmit,
|
||||
setShowSuccess: (show) => {
|
||||
if (!show) {
|
||||
// Reset to initial state
|
||||
setViewModel(prev => ForgotPasswordViewModelBuilder.build(viewData));
|
||||
}
|
||||
},
|
||||
}}
|
||||
mutationState={{
|
||||
isPending: viewModel.mutationPending,
|
||||
error: viewModel.mutationError,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,250 +1,34 @@
|
||||
'use client';
|
||||
/**
|
||||
* Forgot Password Page
|
||||
*
|
||||
* RSC composition pattern:
|
||||
* 1. PageQuery executes to get ViewData
|
||||
* 2. Client component renders with ViewData
|
||||
*/
|
||||
|
||||
import { useState, useEffect, FormEvent, type ChangeEvent } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { useForgotPassword } from "@/lib/hooks/auth/useForgotPassword";
|
||||
import Link from 'next/link';
|
||||
import { motion } from 'framer-motion';
|
||||
import {
|
||||
Mail,
|
||||
ArrowLeft,
|
||||
AlertCircle,
|
||||
Flag,
|
||||
Shield,
|
||||
CheckCircle2,
|
||||
} from 'lucide-react';
|
||||
import { ForgotPasswordPageQuery } from '@/lib/page-queries/auth/ForgotPasswordPageQuery';
|
||||
import { ForgotPasswordClient } from './ForgotPasswordClient';
|
||||
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
export default async function ForgotPasswordPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<URLSearchParams>;
|
||||
}) {
|
||||
// Execute PageQuery
|
||||
const params = await searchParams;
|
||||
const queryResult = await ForgotPasswordPageQuery.execute(params);
|
||||
|
||||
interface FormErrors {
|
||||
email?: string;
|
||||
submit?: string;
|
||||
}
|
||||
|
||||
interface SuccessState {
|
||||
message: string;
|
||||
magicLink?: string;
|
||||
}
|
||||
|
||||
export default function ForgotPasswordPage() {
|
||||
const router = useRouter();
|
||||
const { session } = useAuth();
|
||||
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
const [success, setSuccess] = useState<SuccessState | null>(null);
|
||||
const [formData, setFormData] = useState({
|
||||
email: '',
|
||||
});
|
||||
|
||||
// Check if user is already authenticated
|
||||
useEffect(() => {
|
||||
if (session) {
|
||||
router.replace('/dashboard');
|
||||
}
|
||||
}, [session, router]);
|
||||
|
||||
const validateForm = (): boolean => {
|
||||
const newErrors: FormErrors = {};
|
||||
|
||||
if (!formData.email.trim()) {
|
||||
newErrors.email = 'Email is required';
|
||||
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
|
||||
newErrors.email = 'Invalid email format';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
// Use forgot password mutation hook
|
||||
const forgotPasswordMutation = useForgotPassword({
|
||||
onSuccess: (result) => {
|
||||
setSuccess({
|
||||
message: result.message,
|
||||
magicLink: result.magicLink,
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
setErrors({
|
||||
submit: error.message || 'Failed to send reset link. Please try again.',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (forgotPasswordMutation.isPending) return;
|
||||
|
||||
if (!validateForm()) return;
|
||||
|
||||
setErrors({});
|
||||
setSuccess(null);
|
||||
|
||||
try {
|
||||
await forgotPasswordMutation.mutateAsync({ email: formData.email });
|
||||
} catch (error) {
|
||||
// Error handling is done in the mutation's onError callback
|
||||
}
|
||||
};
|
||||
|
||||
// Loading state from mutation
|
||||
const loading = forgotPasswordMutation.isPending;
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-deep-graphite flex items-center justify-center px-4 py-12">
|
||||
{/* Background Pattern */}
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary-blue/5 via-transparent to-purple-600/5" />
|
||||
<div className="absolute inset-0 opacity-5">
|
||||
<div className="absolute inset-0" style={{
|
||||
backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
|
||||
}} />
|
||||
if (queryResult.isErr()) {
|
||||
// Handle query error
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite flex items-center justify-center">
|
||||
<div className="text-red-400">Failed to load forgot password page</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
<div className="relative w-full max-w-md">
|
||||
{/* Header */}
|
||||
<div className="text-center mb-8">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30 mx-auto mb-4">
|
||||
<Flag className="w-8 h-8 text-primary-blue" />
|
||||
</div>
|
||||
<Heading level={1} className="mb-2">Reset Password</Heading>
|
||||
<p className="text-gray-400">
|
||||
Enter your email and we'll send you a reset link
|
||||
</p>
|
||||
</div>
|
||||
const viewData = queryResult.unwrap();
|
||||
|
||||
<Card className="relative overflow-hidden">
|
||||
{/* Background accent */}
|
||||
<div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-primary-blue/10 to-transparent rounded-bl-full" />
|
||||
|
||||
{!success ? (
|
||||
<form onSubmit={handleSubmit} className="relative space-y-5">
|
||||
{/* Email */}
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Email Address
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, email: e.target.value })}
|
||||
error={!!errors.email}
|
||||
errorMessage={errors.email}
|
||||
placeholder="you@example.com"
|
||||
disabled={loading}
|
||||
className="pl-10"
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{errors.submit && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="flex items-start gap-3 p-3 rounded-lg bg-red-500/10 border border-red-500/30"
|
||||
>
|
||||
<AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
|
||||
<p className="text-sm text-red-400">{errors.submit}</p>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={loading}
|
||||
className="w-full flex items-center justify-center gap-2"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||
Sending...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Shield className="w-4 h-4" />
|
||||
Send Reset Link
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Back to Login */}
|
||||
<div className="text-center">
|
||||
<Link
|
||||
href="/auth/login"
|
||||
className="text-sm text-primary-blue hover:underline flex items-center justify-center gap-1"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
Back to Login
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="relative space-y-4"
|
||||
>
|
||||
<div className="flex items-start gap-3 p-4 rounded-lg bg-performance-green/10 border border-performance-green/30">
|
||||
<CheckCircle2 className="w-6 h-6 text-performance-green flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm text-performance-green font-medium">{success.message}</p>
|
||||
{success.magicLink && (
|
||||
<div className="mt-2">
|
||||
<p className="text-xs text-gray-400 mb-1">Development Mode - Magic Link:</p>
|
||||
<div className="bg-iron-gray p-2 rounded border border-charcoal-outline">
|
||||
<code className="text-xs text-primary-blue break-all">
|
||||
{success.magicLink}
|
||||
</code>
|
||||
</div>
|
||||
<p className="text-[10px] text-gray-500 mt-1">
|
||||
In production, this would be sent via email
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
onClick={() => router.push('/auth/login')}
|
||||
className="w-full"
|
||||
>
|
||||
Return to Login
|
||||
</Button>
|
||||
</motion.div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Trust Indicators */}
|
||||
<div className="mt-6 flex items-center justify-center gap-6 text-sm text-gray-500">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Secure reset process</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle2 className="w-4 h-4" />
|
||||
<span>15 minute expiration</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<p className="mt-6 text-center text-xs text-gray-500">
|
||||
Need help?{' '}
|
||||
<Link href="/support" className="text-gray-400 hover:underline">
|
||||
Contact support
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
// Render client component with ViewData
|
||||
return <ForgotPasswordClient viewData={viewData} />;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { headers } from 'next/headers';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { createRouteGuard } from '@/lib/auth/createRouteGuard';
|
||||
|
||||
interface AuthLayoutProps {
|
||||
@@ -20,11 +21,14 @@ export default async function AuthLayout({ children }: AuthLayoutProps) {
|
||||
const pathname = headerStore.get('x-pathname') || '/';
|
||||
|
||||
const guard = createRouteGuard();
|
||||
await guard.enforce({ pathname });
|
||||
const result = await guard.enforce({ pathname });
|
||||
if (result.type === 'redirect') {
|
||||
redirect(result.to);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite flex items-center justify-center p-4">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
284
apps/website/app/auth/login/LoginClient.tsx
Normal file
284
apps/website/app/auth/login/LoginClient.tsx
Normal file
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* Login Client Component
|
||||
*
|
||||
* Handles client-side login flow using the LoginFlowController.
|
||||
* Deterministic state machine per docs/architecture/website/LOGIN_FLOW_STATE_MACHINE.md
|
||||
*/
|
||||
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect, useMemo } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { LoginFlowController, LoginState } from '@/lib/auth/LoginFlowController';
|
||||
import { LoginViewData } from '@/lib/builders/view-data/LoginViewDataBuilder';
|
||||
import { LoginTemplate } from '@/templates/auth/LoginTemplate';
|
||||
import { LoginMutation } from '@/lib/mutations/auth/LoginMutation';
|
||||
import { validateLoginForm, type LoginFormValues } from '@/lib/utils/validation';
|
||||
import { LoginViewModelBuilder } from '@/lib/builders/view-models/LoginViewModelBuilder';
|
||||
import { LoginViewModel } from '@/lib/view-models/auth/LoginViewModel';
|
||||
|
||||
interface LoginClientProps {
|
||||
viewData: LoginViewData;
|
||||
}
|
||||
|
||||
export function LoginClient({ viewData }: LoginClientProps) {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { refreshSession, session } = useAuth();
|
||||
|
||||
// Build ViewModel from ViewData
|
||||
const [viewModel, setViewModel] = useState<LoginViewModel>(() =>
|
||||
LoginViewModelBuilder.build(viewData)
|
||||
);
|
||||
|
||||
// Login flow controller
|
||||
const controller = useMemo(() => {
|
||||
const returnTo = searchParams.get('returnTo') ?? '/dashboard';
|
||||
return new LoginFlowController(session, returnTo);
|
||||
}, [session, searchParams]);
|
||||
|
||||
// Check controller state on mount and session changes
|
||||
useEffect(() => {
|
||||
const action = controller.getNextAction();
|
||||
|
||||
if (action.type === 'REDIRECT') {
|
||||
router.replace(action.path);
|
||||
}
|
||||
}, [controller, router]);
|
||||
|
||||
// Handle form field changes
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value, type } = e.target;
|
||||
const checked = 'checked' in e.target ? e.target.checked : false;
|
||||
const fieldValue = type === 'checkbox' ? checked : value;
|
||||
|
||||
setViewModel(prev => {
|
||||
const newFormState = {
|
||||
...prev.formState,
|
||||
fields: {
|
||||
...prev.formState.fields,
|
||||
[name]: {
|
||||
...prev.formState.fields[name as keyof typeof prev.formState.fields],
|
||||
value: fieldValue,
|
||||
touched: true,
|
||||
error: undefined,
|
||||
},
|
||||
},
|
||||
};
|
||||
return prev.withFormState(newFormState);
|
||||
});
|
||||
};
|
||||
|
||||
// Handle form submission
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
|
||||
const values: LoginFormValues = {
|
||||
email: viewModel.formState.fields.email.value as string,
|
||||
password: viewModel.formState.fields.password.value as string,
|
||||
rememberMe: viewModel.formState.fields.rememberMe.value as boolean,
|
||||
};
|
||||
|
||||
// Validate form
|
||||
const errors = validateLoginForm(values);
|
||||
const hasErrors = Object.keys(errors).length > 0;
|
||||
|
||||
if (hasErrors) {
|
||||
setViewModel(prev => {
|
||||
const newFormState = {
|
||||
...prev.formState,
|
||||
isValid: false,
|
||||
submitCount: prev.formState.submitCount + 1,
|
||||
fields: {
|
||||
...prev.formState.fields,
|
||||
email: {
|
||||
...prev.formState.fields.email,
|
||||
error: errors.email,
|
||||
touched: true,
|
||||
},
|
||||
password: {
|
||||
...prev.formState.fields.password,
|
||||
error: errors.password,
|
||||
touched: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
return prev.withFormState(newFormState);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Update submitting state
|
||||
setViewModel(prev => prev.withMutationState(true, null));
|
||||
|
||||
try {
|
||||
// Execute login mutation
|
||||
const mutation = new LoginMutation();
|
||||
const result = await mutation.execute({
|
||||
email: values.email,
|
||||
password: values.password,
|
||||
rememberMe: values.rememberMe,
|
||||
});
|
||||
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
setViewModel(prev => {
|
||||
const newFormState = {
|
||||
...prev.formState,
|
||||
isSubmitting: false,
|
||||
submitError: error,
|
||||
};
|
||||
return prev.withFormState(newFormState).withMutationState(false, error);
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showErrorDetails: true,
|
||||
}));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Success - refresh session and transition
|
||||
await refreshSession();
|
||||
|
||||
// Transition to post-auth state
|
||||
controller.transitionToPostAuth();
|
||||
const action = controller.getNextAction();
|
||||
|
||||
if (action.type === 'REDIRECT') {
|
||||
router.push(action.path);
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Login failed';
|
||||
setViewModel(prev => {
|
||||
const newFormState = {
|
||||
...prev.formState,
|
||||
isSubmitting: false,
|
||||
submitError: errorMessage,
|
||||
};
|
||||
return prev.withFormState(newFormState).withMutationState(false, errorMessage);
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showErrorDetails: true,
|
||||
}));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Toggle password visibility
|
||||
const togglePassword = () => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showPassword: !prev.uiState.showPassword,
|
||||
}));
|
||||
};
|
||||
|
||||
// Dismiss error details
|
||||
const dismissErrorDetails = () => {
|
||||
setViewModel(prev => {
|
||||
const newFormState = {
|
||||
...prev.formState,
|
||||
submitError: undefined,
|
||||
};
|
||||
return prev.withFormState(newFormState).withUIState({
|
||||
...prev.uiState,
|
||||
showErrorDetails: false,
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// Get current state from controller
|
||||
const state = controller.getState();
|
||||
|
||||
// If user is authenticated with permissions, show loading
|
||||
if (state === LoginState.AUTHENTICATED_WITH_PERMISSIONS) {
|
||||
return (
|
||||
<main className="min-h-screen bg-deep-graphite flex items-center justify-center">
|
||||
<div className="w-8 h-8 border-2 border-primary-blue border-t-transparent rounded-full animate-spin" />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
// If user has insufficient permissions, show permission error
|
||||
if (state === LoginState.AUTHENTICATED_WITHOUT_PERMISSIONS) {
|
||||
return (
|
||||
<LoginTemplate
|
||||
viewData={{
|
||||
...viewData,
|
||||
hasInsufficientPermissions: true,
|
||||
showPassword: viewModel.showPassword,
|
||||
showErrorDetails: viewModel.showErrorDetails,
|
||||
formState: viewModel.formState,
|
||||
isSubmitting: viewModel.isSubmitting,
|
||||
submitError: viewModel.submitError,
|
||||
}}
|
||||
formActions={{
|
||||
handleChange,
|
||||
handleSubmit,
|
||||
setFormState: (state) => {
|
||||
if (typeof state === 'function') {
|
||||
const newState = state(viewModel.formState);
|
||||
setViewModel(prev => prev.withFormState(newState));
|
||||
} else {
|
||||
setViewModel(prev => prev.withFormState(state));
|
||||
}
|
||||
},
|
||||
setShowPassword: togglePassword,
|
||||
setShowErrorDetails: (show) => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showErrorDetails: show,
|
||||
}));
|
||||
},
|
||||
}}
|
||||
mutationState={{
|
||||
isPending: viewModel.mutationPending,
|
||||
error: viewModel.mutationError,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Show login form
|
||||
return (
|
||||
<LoginTemplate
|
||||
viewData={{
|
||||
...viewData,
|
||||
showPassword: viewModel.showPassword,
|
||||
showErrorDetails: viewModel.showErrorDetails,
|
||||
formState: viewModel.formState,
|
||||
isSubmitting: viewModel.isSubmitting,
|
||||
submitError: viewModel.submitError,
|
||||
}}
|
||||
formActions={{
|
||||
handleChange,
|
||||
handleSubmit,
|
||||
setFormState: (state) => {
|
||||
if (typeof state === 'function') {
|
||||
const newState = state(viewModel.formState);
|
||||
setViewModel(prev => prev.withFormState(newState));
|
||||
} else {
|
||||
setViewModel(prev => prev.withFormState(state));
|
||||
}
|
||||
},
|
||||
setShowPassword: togglePassword,
|
||||
setShowErrorDetails: (show) => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showErrorDetails: show,
|
||||
}));
|
||||
},
|
||||
}}
|
||||
mutationState={{
|
||||
isPending: viewModel.mutationPending,
|
||||
error: viewModel.mutationError,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,426 +1,34 @@
|
||||
'use client';
|
||||
/**
|
||||
* Login Page
|
||||
*
|
||||
* RSC composition pattern:
|
||||
* 1. PageQuery executes to get ViewData
|
||||
* 2. Client component renders with ViewData
|
||||
*/
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import {
|
||||
Mail,
|
||||
Lock,
|
||||
Eye,
|
||||
EyeOff,
|
||||
LogIn,
|
||||
AlertCircle,
|
||||
Flag,
|
||||
Shield,
|
||||
} from 'lucide-react';
|
||||
import { LoginPageQuery } from '@/lib/page-queries/auth/LoginPageQuery';
|
||||
import { LoginClient } from './LoginClient';
|
||||
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { useLogin } from "@/lib/hooks/auth/useLogin";
|
||||
import AuthWorkflowMockup from '@/components/auth/AuthWorkflowMockup';
|
||||
import UserRolesPreview from '@/components/auth/UserRolesPreview';
|
||||
import { EnhancedFormError } from '@/components/errors/EnhancedFormError';
|
||||
import { useEnhancedForm } from '@/lib/hooks/useEnhancedForm';
|
||||
import { validateLoginForm, type LoginFormValues } from '@/lib/utils/validation';
|
||||
import { logErrorWithContext } from '@/lib/utils/errorUtils';
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
export default async function LoginPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<URLSearchParams>;
|
||||
}) {
|
||||
// Execute PageQuery
|
||||
const params = await searchParams;
|
||||
const queryResult = await LoginPageQuery.execute(params);
|
||||
|
||||
// Template component for login UI
|
||||
function LoginTemplate({ data }: { data: { returnTo: string; hasInsufficientPermissions: boolean; showPassword: boolean; showErrorDetails: boolean; formState: any; handleChange: any; handleSubmit: any; setFormState: any; setShowPassword: any; setShowErrorDetails: any; } }) {
|
||||
const {
|
||||
returnTo,
|
||||
hasInsufficientPermissions,
|
||||
showPassword,
|
||||
showErrorDetails,
|
||||
formState,
|
||||
handleChange,
|
||||
handleSubmit,
|
||||
setFormState,
|
||||
setShowPassword,
|
||||
setShowErrorDetails,
|
||||
} = data;
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-deep-graphite flex">
|
||||
{/* Background Pattern */}
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary-blue/5 via-transparent to-purple-600/5" />
|
||||
<div className="absolute inset-0 opacity-5">
|
||||
<div className="absolute inset-0" style={{
|
||||
backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
|
||||
}} />
|
||||
if (queryResult.isErr()) {
|
||||
// Handle query error
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite flex items-center justify-center">
|
||||
<div className="text-red-400">Failed to load login page</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
{/* Left Side - Info Panel (Hidden on mobile) */}
|
||||
<div className="hidden lg:flex lg:w-1/2 relative items-center justify-center p-12">
|
||||
<div className="max-w-lg">
|
||||
{/* Logo */}
|
||||
<div className="flex items-center gap-3 mb-8">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30">
|
||||
<Flag className="w-6 h-6 text-primary-blue" />
|
||||
</div>
|
||||
<span className="text-2xl font-bold text-white">GridPilot</span>
|
||||
</div>
|
||||
const viewData = queryResult.unwrap();
|
||||
|
||||
<Heading level={2} className="text-white mb-4">
|
||||
Your Sim Racing Infrastructure
|
||||
</Heading>
|
||||
|
||||
<p className="text-gray-400 text-lg mb-8">
|
||||
Manage leagues, track performance, join teams, and compete with drivers worldwide. One account, multiple roles.
|
||||
</p>
|
||||
|
||||
{/* Role Cards */}
|
||||
<UserRolesPreview variant="full" />
|
||||
|
||||
{/* Workflow Mockup */}
|
||||
<AuthWorkflowMockup />
|
||||
|
||||
{/* Trust Indicators */}
|
||||
<div className="mt-8 flex items-center gap-6 text-sm text-gray-500">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Secure login</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm">iRacing verified</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Side - Login Form */}
|
||||
<div className="flex-1 flex items-center justify-center px-4 py-12">
|
||||
<div className="relative w-full max-w-md">
|
||||
{/* Mobile Logo/Header */}
|
||||
<div className="text-center mb-8 lg:hidden">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30 mx-auto mb-4">
|
||||
<Flag className="w-8 h-8 text-primary-blue" />
|
||||
</div>
|
||||
<Heading level={1} className="mb-2">Welcome Back</Heading>
|
||||
<p className="text-gray-400">
|
||||
Sign in to continue to GridPilot
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Desktop Header */}
|
||||
<div className="hidden lg:block text-center mb-8">
|
||||
<Heading level={2} className="mb-2">Welcome Back</Heading>
|
||||
<p className="text-gray-400">
|
||||
Sign in to access your racing dashboard
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="relative overflow-hidden">
|
||||
{/* Background accent */}
|
||||
<div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-primary-blue/10 to-transparent rounded-bl-full" />
|
||||
|
||||
<form onSubmit={handleSubmit} className="relative space-y-5">
|
||||
{/* Email */}
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Email Address
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
value={formState.fields.email.value}
|
||||
onChange={handleChange}
|
||||
error={!!formState.fields.email.error}
|
||||
errorMessage={formState.fields.email.error}
|
||||
placeholder="you@example.com"
|
||||
disabled={formState.isSubmitting}
|
||||
className="pl-10"
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Password */}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-300">
|
||||
Password
|
||||
</label>
|
||||
<Link href="/auth/forgot-password" className="text-xs text-primary-blue hover:underline">
|
||||
Forgot password?
|
||||
</Link>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={formState.fields.password.value}
|
||||
onChange={handleChange}
|
||||
error={!!formState.fields.password.error}
|
||||
errorMessage={formState.fields.password.error}
|
||||
placeholder="••••••••"
|
||||
disabled={formState.isSubmitting}
|
||||
className="pl-10 pr-10"
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300"
|
||||
>
|
||||
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Remember Me */}
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
id="rememberMe"
|
||||
name="rememberMe"
|
||||
type="checkbox"
|
||||
checked={formState.fields.rememberMe?.value ?? false}
|
||||
onChange={handleChange}
|
||||
disabled={formState.isSubmitting}
|
||||
className="w-4 h-4 rounded border-charcoal-outline bg-iron-gray text-primary-blue focus:ring-primary-blue focus:ring-offset-0"
|
||||
/>
|
||||
<span className="text-sm text-gray-300">Keep me signed in</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Insufficient Permissions Message */}
|
||||
<AnimatePresence>
|
||||
{hasInsufficientPermissions && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
className="p-4 rounded-lg bg-warning-amber/10 border border-warning-amber/30"
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertCircle className="w-5 h-5 text-warning-amber flex-shrink-0 mt-0.5" />
|
||||
<div className="text-sm text-gray-300">
|
||||
<strong className="text-warning-amber">Insufficient Permissions</strong>
|
||||
<p className="mt-1">
|
||||
You don't have permission to access that page. Please log in with an account that has the required role.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* Enhanced Error Display */}
|
||||
<AnimatePresence>
|
||||
{formState.submitError && (
|
||||
<EnhancedFormError
|
||||
error={new Error(formState.submitError)}
|
||||
onDismiss={() => {
|
||||
// Clear the error by setting submitError to undefined
|
||||
setFormState((prev: typeof formState) => ({ ...prev, submitError: undefined }));
|
||||
}}
|
||||
showDeveloperDetails={showErrorDetails}
|
||||
/>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={formState.isSubmitting}
|
||||
className="w-full flex items-center justify-center gap-2"
|
||||
>
|
||||
{formState.isSubmitting ? (
|
||||
<>
|
||||
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||
Signing in...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<LogIn className="w-4 h-4" />
|
||||
Sign In
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="relative my-6">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-charcoal-outline" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs">
|
||||
<span className="px-4 bg-iron-gray text-gray-500">or continue with</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Sign Up Link */}
|
||||
<p className="mt-6 text-center text-sm text-gray-400">
|
||||
Don't have an account?{' '}
|
||||
<Link
|
||||
href={`/auth/signup${returnTo !== '/dashboard' ? `?returnTo=${encodeURIComponent(returnTo)}` : ''}`}
|
||||
className="text-primary-blue hover:underline font-medium"
|
||||
>
|
||||
Create one
|
||||
</Link>
|
||||
</p>
|
||||
</Card>
|
||||
|
||||
{/* Name Immutability Notice */}
|
||||
<div className="mt-6 p-4 rounded-lg bg-iron-gray/30 border border-charcoal-outline">
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertCircle className="w-5 h-5 text-gray-400 flex-shrink-0 mt-0.5" />
|
||||
<div className="text-xs text-gray-400">
|
||||
<strong>Note:</strong> Your display name cannot be changed after signup. Please ensure it's correct when creating your account.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<p className="mt-6 text-center text-xs text-gray-500">
|
||||
By signing in, you agree to our{' '}
|
||||
<Link href="/terms" className="text-gray-400 hover:underline">Terms of Service</Link>
|
||||
{' '}and{' '}
|
||||
<Link href="/privacy" className="text-gray-400 hover:underline">Privacy Policy</Link>
|
||||
</p>
|
||||
|
||||
{/* Mobile Role Info */}
|
||||
<UserRolesPreview variant="compact" />
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { refreshSession, session } = useAuth();
|
||||
const returnTo = searchParams.get('returnTo') ?? '/dashboard';
|
||||
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showErrorDetails, setShowErrorDetails] = useState(false);
|
||||
const [hasInsufficientPermissions, setHasInsufficientPermissions] = useState(false);
|
||||
|
||||
// Use login mutation hook
|
||||
const loginMutation = useLogin({
|
||||
onSuccess: async () => {
|
||||
// Refresh session in context so header updates immediately
|
||||
await refreshSession();
|
||||
router.push(returnTo);
|
||||
},
|
||||
onError: (error) => {
|
||||
// Show error details toggle in development
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
setShowErrorDetails(true);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// Check if user is already authenticated
|
||||
useEffect(() => {
|
||||
console.log('[LoginPage] useEffect running', {
|
||||
session: session ? 'exists' : 'null',
|
||||
returnTo: searchParams.get('returnTo'),
|
||||
pathname: window.location.pathname,
|
||||
search: window.location.search,
|
||||
});
|
||||
|
||||
if (session) {
|
||||
// Check if this is a returnTo redirect (user lacks permissions)
|
||||
const isPermissionRedirect = searchParams.get('returnTo') !== null;
|
||||
|
||||
console.log('[LoginPage] Authenticated user check', {
|
||||
isPermissionRedirect,
|
||||
returnTo: searchParams.get('returnTo'),
|
||||
});
|
||||
|
||||
if (isPermissionRedirect) {
|
||||
// User was redirected here due to insufficient permissions
|
||||
// Show permission error instead of redirecting
|
||||
console.log('[LoginPage] Showing permission error');
|
||||
setHasInsufficientPermissions(true);
|
||||
} else {
|
||||
// User navigated here directly while authenticated, redirect to dashboard
|
||||
console.log('[LoginPage] Redirecting to dashboard');
|
||||
router.replace('/dashboard');
|
||||
}
|
||||
}
|
||||
}, [session, router, searchParams]);
|
||||
|
||||
// Use enhanced form hook
|
||||
const {
|
||||
formState,
|
||||
setFormState,
|
||||
handleChange,
|
||||
handleSubmit,
|
||||
} = useEnhancedForm<LoginFormValues>({
|
||||
initialValues: {
|
||||
email: '',
|
||||
password: '',
|
||||
rememberMe: false,
|
||||
},
|
||||
validate: validateLoginForm,
|
||||
component: 'LoginPage',
|
||||
onSubmit: async (values) => {
|
||||
// Log the attempt for debugging
|
||||
logErrorWithContext(
|
||||
{ message: 'Login attempt', values: { ...values, password: '[REDACTED]' } },
|
||||
{
|
||||
component: 'LoginPage',
|
||||
action: 'login-submit',
|
||||
formData: { ...values, password: '[REDACTED]' },
|
||||
}
|
||||
);
|
||||
|
||||
await loginMutation.mutateAsync({
|
||||
email: values.email,
|
||||
password: values.password,
|
||||
rememberMe: values.rememberMe,
|
||||
});
|
||||
},
|
||||
onError: (error, values) => {
|
||||
// Error handling is done in the mutation's onError callback
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Reset error details on success
|
||||
setShowErrorDetails(false);
|
||||
},
|
||||
});
|
||||
|
||||
// Prepare template data
|
||||
const templateData = {
|
||||
returnTo,
|
||||
hasInsufficientPermissions,
|
||||
showPassword,
|
||||
showErrorDetails,
|
||||
formState,
|
||||
handleChange,
|
||||
handleSubmit,
|
||||
setFormState,
|
||||
setShowPassword,
|
||||
setShowErrorDetails,
|
||||
};
|
||||
|
||||
// Mutation state for wrapper
|
||||
const isLoading = loginMutation.isPending;
|
||||
const error = loginMutation.error;
|
||||
|
||||
return (
|
||||
<StatefulPageWrapper
|
||||
data={templateData}
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
retry={() => loginMutation.mutate({ email: '', password: '', rememberMe: false })}
|
||||
Template={LoginTemplate}
|
||||
loading={{ variant: 'full-screen', message: 'Loading login...' }}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
/>
|
||||
);
|
||||
// Render client component with ViewData
|
||||
return <LoginClient viewData={viewData} />;
|
||||
}
|
||||
139
apps/website/app/auth/reset-password/ResetPasswordClient.tsx
Normal file
139
apps/website/app/auth/reset-password/ResetPasswordClient.tsx
Normal file
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Reset Password Client Component
|
||||
*
|
||||
* Handles client-side reset password flow.
|
||||
*/
|
||||
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { ResetPasswordViewData } from '@/lib/builders/view-data/ResetPasswordViewDataBuilder';
|
||||
import { ResetPasswordTemplate } from '@/templates/auth/ResetPasswordTemplate';
|
||||
import { ResetPasswordMutation } from '@/lib/mutations/auth/ResetPasswordMutation';
|
||||
import { ResetPasswordViewModelBuilder } from '@/lib/builders/view-models/ResetPasswordViewModelBuilder';
|
||||
import { ResetPasswordViewModel } from '@/lib/view-models/auth/ResetPasswordViewModel';
|
||||
|
||||
interface ResetPasswordClientProps {
|
||||
viewData: ResetPasswordViewData;
|
||||
}
|
||||
|
||||
export function ResetPasswordClient({ viewData }: ResetPasswordClientProps) {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
// Build ViewModel from ViewData
|
||||
const [viewModel, setViewModel] = useState<ResetPasswordViewModel>(() =>
|
||||
ResetPasswordViewModelBuilder.build(viewData)
|
||||
);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
newPassword: '',
|
||||
confirmPassword: ''
|
||||
});
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
|
||||
// Validate passwords match
|
||||
if (formData.newPassword !== formData.confirmPassword) {
|
||||
setViewModel(prev => prev.withMutationState(false, 'Passwords do not match'));
|
||||
return;
|
||||
}
|
||||
|
||||
// Update submitting state
|
||||
setViewModel(prev => prev.withMutationState(true, null));
|
||||
|
||||
try {
|
||||
const token = searchParams.get('token');
|
||||
if (!token) {
|
||||
setViewModel(prev => prev.withMutationState(false, 'Invalid reset link'));
|
||||
return;
|
||||
}
|
||||
|
||||
// Execute reset password mutation
|
||||
const mutation = new ResetPasswordMutation();
|
||||
const result = await mutation.execute({
|
||||
token,
|
||||
newPassword: formData.newPassword,
|
||||
});
|
||||
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
setViewModel(prev => prev.withMutationState(false, error));
|
||||
return;
|
||||
}
|
||||
|
||||
// Success
|
||||
const data = result.unwrap();
|
||||
setViewModel(prev => prev.withSuccess(data.message));
|
||||
|
||||
// Redirect to login after a delay
|
||||
setTimeout(() => {
|
||||
router.push('/auth/login');
|
||||
}, 3000);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to reset password';
|
||||
setViewModel(prev => prev.withMutationState(false, errorMessage));
|
||||
}
|
||||
};
|
||||
|
||||
// Toggle password visibility
|
||||
const togglePassword = () => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showPassword: !prev.uiState.showPassword,
|
||||
}));
|
||||
};
|
||||
|
||||
const toggleConfirmPassword = () => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showConfirmPassword: !prev.uiState.showConfirmPassword,
|
||||
}));
|
||||
};
|
||||
|
||||
// Build viewData for template
|
||||
const templateViewData: ResetPasswordViewData = {
|
||||
...viewData,
|
||||
showSuccess: viewModel.showSuccess,
|
||||
successMessage: viewModel.successMessage || undefined,
|
||||
formState: viewModel.formState,
|
||||
isSubmitting: viewModel.isSubmitting,
|
||||
submitError: viewModel.submitError,
|
||||
};
|
||||
|
||||
return (
|
||||
<ResetPasswordTemplate
|
||||
// Spread the viewData properties
|
||||
token={templateViewData.token}
|
||||
returnTo={templateViewData.returnTo}
|
||||
showSuccess={templateViewData.showSuccess}
|
||||
successMessage={templateViewData.successMessage}
|
||||
formState={templateViewData.formState}
|
||||
isSubmitting={templateViewData.isSubmitting}
|
||||
submitError={templateViewData.submitError}
|
||||
// Add the additional props
|
||||
formActions={{
|
||||
setFormData,
|
||||
handleSubmit,
|
||||
setShowSuccess: (show) => {
|
||||
if (!show) {
|
||||
// Reset to initial state
|
||||
setViewModel(prev => ResetPasswordViewModelBuilder.build(viewData));
|
||||
}
|
||||
},
|
||||
setShowPassword: togglePassword,
|
||||
setShowConfirmPassword: toggleConfirmPassword,
|
||||
}}
|
||||
uiState={{
|
||||
showPassword: viewModel.uiState.showPassword,
|
||||
showConfirmPassword: viewModel.uiState.showConfirmPassword,
|
||||
}}
|
||||
mutationState={{
|
||||
isPending: viewModel.mutationPending,
|
||||
error: viewModel.mutationError,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,371 +1,34 @@
|
||||
'use client';
|
||||
/**
|
||||
* Reset Password Page
|
||||
*
|
||||
* RSC composition pattern:
|
||||
* 1. PageQuery executes to get ViewData
|
||||
* 2. Client component renders with ViewData
|
||||
*/
|
||||
|
||||
import { useState, FormEvent, type ChangeEvent, useEffect } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { motion } from 'framer-motion';
|
||||
import {
|
||||
Lock,
|
||||
Eye,
|
||||
EyeOff,
|
||||
AlertCircle,
|
||||
Flag,
|
||||
Shield,
|
||||
CheckCircle2,
|
||||
ArrowLeft,
|
||||
} from 'lucide-react';
|
||||
import { ResetPasswordPageQuery } from '@/lib/page-queries/auth/ResetPasswordPageQuery';
|
||||
import { ResetPasswordClient } from './ResetPasswordClient';
|
||||
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { useResetPassword } from "@/lib/hooks/auth/useResetPassword";
|
||||
export default async function ResetPasswordPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<URLSearchParams>;
|
||||
}) {
|
||||
// Execute PageQuery
|
||||
const params = await searchParams;
|
||||
const queryResult = await ResetPasswordPageQuery.execute(params);
|
||||
|
||||
interface FormErrors {
|
||||
newPassword?: string;
|
||||
confirmPassword?: string;
|
||||
submit?: string;
|
||||
}
|
||||
|
||||
interface PasswordStrength {
|
||||
score: number;
|
||||
label: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
function checkPasswordStrength(password: string): PasswordStrength {
|
||||
let score = 0;
|
||||
if (password.length >= 8) score++;
|
||||
if (password.length >= 12) score++;
|
||||
if (/[a-z]/.test(password) && /[A-Z]/.test(password)) score++;
|
||||
if (/\d/.test(password)) score++;
|
||||
if (/[^a-zA-Z\d]/.test(password)) score++;
|
||||
|
||||
if (score <= 1) return { score, label: 'Weak', color: 'bg-red-500' };
|
||||
if (score <= 2) return { score, label: 'Fair', color: 'bg-warning-amber' };
|
||||
if (score <= 3) return { score, label: 'Good', color: 'bg-primary-blue' };
|
||||
return { score, label: 'Strong', color: 'bg-performance-green' };
|
||||
}
|
||||
|
||||
export default function ResetPasswordPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { session } = useAuth();
|
||||
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
const [formData, setFormData] = useState({
|
||||
newPassword: '',
|
||||
confirmPassword: '',
|
||||
});
|
||||
const [token, setToken] = useState<string>('');
|
||||
|
||||
// Check if user is already authenticated
|
||||
useEffect(() => {
|
||||
if (session) {
|
||||
router.replace('/dashboard');
|
||||
}
|
||||
}, [session, router]);
|
||||
|
||||
// Extract token from URL on mount
|
||||
useEffect(() => {
|
||||
const tokenParam = searchParams.get('token');
|
||||
if (tokenParam) {
|
||||
setToken(tokenParam);
|
||||
}
|
||||
}, [searchParams]);
|
||||
|
||||
const passwordStrength = checkPasswordStrength(formData.newPassword);
|
||||
|
||||
const passwordRequirements = [
|
||||
{ met: formData.newPassword.length >= 8, label: 'At least 8 characters' },
|
||||
{ met: /[a-z]/.test(formData.newPassword) && /[A-Z]/.test(formData.newPassword), label: 'Upper and lowercase letters' },
|
||||
{ met: /\d/.test(formData.newPassword), label: 'At least one number' },
|
||||
{ met: /[^a-zA-Z\d]/.test(formData.newPassword), label: 'At least one special character' },
|
||||
];
|
||||
|
||||
const validateForm = (): boolean => {
|
||||
const newErrors: FormErrors = {};
|
||||
|
||||
if (!formData.newPassword) {
|
||||
newErrors.newPassword = 'New password is required';
|
||||
} else if (formData.newPassword.length < 8) {
|
||||
newErrors.newPassword = 'Password must be at least 8 characters';
|
||||
} else if (!/[a-z]/.test(formData.newPassword) || !/[A-Z]/.test(formData.newPassword) || !/\d/.test(formData.newPassword)) {
|
||||
newErrors.newPassword = 'Password must contain uppercase, lowercase, and number';
|
||||
}
|
||||
|
||||
if (!formData.confirmPassword) {
|
||||
newErrors.confirmPassword = 'Please confirm your password';
|
||||
} else if (formData.newPassword !== formData.confirmPassword) {
|
||||
newErrors.confirmPassword = 'Passwords do not match';
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
newErrors.submit = 'Invalid reset token. Please request a new reset link.';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
// Use reset password mutation hook
|
||||
const resetPasswordMutation = useResetPassword({
|
||||
onSuccess: (result) => {
|
||||
setSuccess(result.message);
|
||||
},
|
||||
onError: (error) => {
|
||||
setErrors({
|
||||
submit: error.message || 'Failed to reset password. Please try again.',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (resetPasswordMutation.isPending) return;
|
||||
|
||||
if (!validateForm()) return;
|
||||
|
||||
setErrors({});
|
||||
setSuccess(null);
|
||||
|
||||
try {
|
||||
await resetPasswordMutation.mutateAsync({
|
||||
token,
|
||||
newPassword: formData.newPassword,
|
||||
});
|
||||
} catch (error) {
|
||||
// Error handling is done in the mutation's onError callback
|
||||
}
|
||||
};
|
||||
|
||||
// Loading state from mutation
|
||||
const loading = resetPasswordMutation.isPending;
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-deep-graphite flex items-center justify-center px-4 py-12">
|
||||
{/* Background Pattern */}
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary-blue/5 via-transparent to-purple-600/5" />
|
||||
<div className="absolute inset-0 opacity-5">
|
||||
<div className="absolute inset-0" style={{
|
||||
backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
|
||||
}} />
|
||||
if (queryResult.isErr()) {
|
||||
// Handle query error
|
||||
return (
|
||||
<div className="min-h-screen bg-deep-graphite flex items-center justify-center">
|
||||
<div className="text-red-400">Failed to load reset password page</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
<div className="relative w-full max-w-md">
|
||||
{/* Header */}
|
||||
<div className="text-center mb-8">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30 mx-auto mb-4">
|
||||
<Lock className="w-8 h-8 text-primary-blue" />
|
||||
</div>
|
||||
<Heading level={1} className="mb-2">Set New Password</Heading>
|
||||
<p className="text-gray-400">
|
||||
Create a strong password for your account
|
||||
</p>
|
||||
</div>
|
||||
const viewData = queryResult.unwrap();
|
||||
|
||||
<Card className="relative overflow-hidden">
|
||||
{/* Background accent */}
|
||||
<div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-primary-blue/10 to-transparent rounded-bl-full" />
|
||||
|
||||
{!success ? (
|
||||
<form onSubmit={handleSubmit} className="relative space-y-5">
|
||||
{/* New Password */}
|
||||
<div>
|
||||
<label htmlFor="newPassword" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
New Password
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="newPassword"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={formData.newPassword}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, newPassword: e.target.value })}
|
||||
error={!!errors.newPassword}
|
||||
errorMessage={errors.newPassword}
|
||||
placeholder="••••••••"
|
||||
disabled={loading}
|
||||
className="pl-10 pr-10"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300"
|
||||
>
|
||||
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Password Strength */}
|
||||
{formData.newPassword && (
|
||||
<div className="mt-3 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1 h-1.5 rounded-full bg-charcoal-outline overflow-hidden">
|
||||
<motion.div
|
||||
className={`h-full ${passwordStrength.color}`}
|
||||
initial={{ width: 0 }}
|
||||
animate={{ width: `${(passwordStrength.score / 5) * 100}%` }}
|
||||
transition={{ duration: 0.3 }}
|
||||
/>
|
||||
</div>
|
||||
<span className={`text-xs font-medium ${
|
||||
passwordStrength.score <= 1 ? 'text-red-400' :
|
||||
passwordStrength.score <= 2 ? 'text-warning-amber' :
|
||||
passwordStrength.score <= 3 ? 'text-primary-blue' :
|
||||
'text-performance-green'
|
||||
}`}>
|
||||
{passwordStrength.label}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-1">
|
||||
{passwordRequirements.map((req, index) => (
|
||||
<div key={index} className="flex items-center gap-1.5 text-xs">
|
||||
{req.met ? (
|
||||
<CheckCircle2 className="w-3 h-3 text-performance-green" />
|
||||
) : (
|
||||
<AlertCircle className="w-3 h-3 text-gray-500" />
|
||||
)}
|
||||
<span className={req.met ? 'text-gray-300' : 'text-gray-500'}>
|
||||
{req.label}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Confirm Password */}
|
||||
<div>
|
||||
<label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Confirm Password
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type={showConfirmPassword ? 'text' : 'password'}
|
||||
value={formData.confirmPassword}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, confirmPassword: e.target.value })}
|
||||
error={!!errors.confirmPassword}
|
||||
errorMessage={errors.confirmPassword}
|
||||
placeholder="••••••••"
|
||||
disabled={loading}
|
||||
className="pl-10 pr-10"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300"
|
||||
>
|
||||
{showConfirmPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
{formData.confirmPassword && formData.newPassword === formData.confirmPassword && (
|
||||
<p className="mt-1 text-xs text-performance-green flex items-center gap-1">
|
||||
<CheckCircle2 className="w-3 h-3" /> Passwords match
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{errors.submit && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="flex items-start gap-3 p-3 rounded-lg bg-red-500/10 border border-red-500/30"
|
||||
>
|
||||
<AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
|
||||
<p className="text-sm text-red-400">{errors.submit}</p>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={loading}
|
||||
className="w-full flex items-center justify-center gap-2"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||
Resetting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Lock className="w-4 h-4" />
|
||||
Reset Password
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
{/* Back to Login */}
|
||||
<div className="text-center">
|
||||
<Link
|
||||
href="/auth/login"
|
||||
className="text-sm text-primary-blue hover:underline flex items-center justify-center gap-1"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
Back to Login
|
||||
</Link>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="relative space-y-4"
|
||||
>
|
||||
<div className="flex items-start gap-3 p-4 rounded-lg bg-performance-green/10 border border-performance-green/30">
|
||||
<CheckCircle2 className="w-6 h-6 text-performance-green flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-sm text-performance-green font-medium">{success}</p>
|
||||
<p className="text-xs text-gray-400 mt-1">
|
||||
Your password has been successfully reset
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
onClick={() => router.push('/auth/login')}
|
||||
className="w-full"
|
||||
>
|
||||
Login with New Password
|
||||
</Button>
|
||||
</motion.div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Trust Indicators */}
|
||||
<div className="mt-6 flex items-center justify-center gap-6 text-sm text-gray-500">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Encrypted & secure</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle2 className="w-4 h-4" />
|
||||
<span>Instant update</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
<p className="mt-6 text-center text-xs text-gray-500">
|
||||
Need help?{' '}
|
||||
<Link href="/support" className="text-gray-400 hover:underline">
|
||||
Contact support
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
// Render client component with ViewData
|
||||
return <ResetPasswordClient viewData={viewData} />;
|
||||
}
|
||||
123
apps/website/app/auth/signup/SignupClient.tsx
Normal file
123
apps/website/app/auth/signup/SignupClient.tsx
Normal file
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Signup Client Component
|
||||
*
|
||||
* Handles client-side signup flow.
|
||||
*/
|
||||
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { SignupViewData } from '@/lib/builders/view-data/SignupViewDataBuilder';
|
||||
import { SignupTemplate } from '@/templates/auth/SignupTemplate';
|
||||
import { SignupMutation } from '@/lib/mutations/auth/SignupMutation';
|
||||
import { SignupViewModelBuilder } from '@/lib/builders/view-models/SignupViewModelBuilder';
|
||||
import { SignupViewModel } from '@/lib/view-models/auth/SignupViewModel';
|
||||
|
||||
interface SignupClientProps {
|
||||
viewData: SignupViewData;
|
||||
}
|
||||
|
||||
export function SignupClient({ viewData }: SignupClientProps) {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { refreshSession } = useAuth();
|
||||
|
||||
// Build ViewModel from ViewData
|
||||
const [viewModel, setViewModel] = useState<SignupViewModel>(() =>
|
||||
SignupViewModelBuilder.build(viewData)
|
||||
);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
email: '',
|
||||
password: '',
|
||||
confirmPassword: ''
|
||||
});
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
|
||||
// Validate passwords match
|
||||
if (formData.password !== formData.confirmPassword) {
|
||||
setViewModel(prev => prev.withMutationState(false, 'Passwords do not match'));
|
||||
return;
|
||||
}
|
||||
|
||||
// Update submitting state
|
||||
setViewModel(prev => prev.withMutationState(true, null));
|
||||
|
||||
try {
|
||||
// Transform to DTO format
|
||||
const displayName = `${formData.firstName} ${formData.lastName}`.trim();
|
||||
|
||||
// Execute signup mutation
|
||||
const mutation = new SignupMutation();
|
||||
const result = await mutation.execute({
|
||||
email: formData.email,
|
||||
password: formData.password,
|
||||
displayName: displayName || formData.firstName || formData.lastName,
|
||||
});
|
||||
|
||||
if (result.isErr()) {
|
||||
const error = result.getError();
|
||||
setViewModel(prev => prev.withMutationState(false, error));
|
||||
return;
|
||||
}
|
||||
|
||||
// Success - refresh session and redirect
|
||||
await refreshSession();
|
||||
|
||||
const returnTo = searchParams.get('returnTo') ?? '/onboarding';
|
||||
router.push(returnTo);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Signup failed';
|
||||
setViewModel(prev => prev.withMutationState(false, errorMessage));
|
||||
}
|
||||
};
|
||||
|
||||
// Toggle password visibility
|
||||
const togglePassword = () => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showPassword: !prev.uiState.showPassword,
|
||||
}));
|
||||
};
|
||||
|
||||
const toggleConfirmPassword = () => {
|
||||
setViewModel(prev => prev.withUIState({
|
||||
...prev.uiState,
|
||||
showConfirmPassword: !prev.uiState.showConfirmPassword,
|
||||
}));
|
||||
};
|
||||
|
||||
// Build viewData for template
|
||||
const templateViewData: SignupViewData = {
|
||||
...viewData,
|
||||
formState: viewModel.formState,
|
||||
isSubmitting: viewModel.isSubmitting,
|
||||
submitError: viewModel.submitError,
|
||||
};
|
||||
|
||||
return (
|
||||
<SignupTemplate
|
||||
viewData={templateViewData}
|
||||
formActions={{
|
||||
setFormData,
|
||||
handleSubmit,
|
||||
setShowPassword: togglePassword,
|
||||
setShowConfirmPassword: toggleConfirmPassword,
|
||||
}}
|
||||
uiState={{
|
||||
showPassword: viewModel.uiState.showPassword,
|
||||
showConfirmPassword: viewModel.uiState.showConfirmPassword,
|
||||
}}
|
||||
mutationState={{
|
||||
isPending: viewModel.mutationPending,
|
||||
error: viewModel.mutationError,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,651 +1,34 @@
|
||||
'use client';
|
||||
/**
|
||||
* Signup Page
|
||||
*
|
||||
* RSC composition pattern:
|
||||
* 1. PageQuery executes to get ViewData
|
||||
* 2. Client component renders with ViewData
|
||||
*/
|
||||
|
||||
import { useState, useEffect, FormEvent, type ChangeEvent } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import Link from 'next/link';
|
||||
import { motion, AnimatePresence } from 'framer-motion';
|
||||
import {
|
||||
Mail,
|
||||
Lock,
|
||||
Eye,
|
||||
EyeOff,
|
||||
UserPlus,
|
||||
AlertCircle,
|
||||
Flag,
|
||||
User,
|
||||
Check,
|
||||
X,
|
||||
Car,
|
||||
Users,
|
||||
Trophy,
|
||||
Shield,
|
||||
Sparkles,
|
||||
} from 'lucide-react';
|
||||
import { SignupPageQuery } from '@/lib/page-queries/auth/SignupPageQuery';
|
||||
import { SignupClient } from './SignupClient';
|
||||
|
||||
import Card from '@/components/ui/Card';
|
||||
import Button from '@/components/ui/Button';
|
||||
import Input from '@/components/ui/Input';
|
||||
import Heading from '@/components/ui/Heading';
|
||||
import { useAuth } from '@/lib/auth/AuthContext';
|
||||
import { useSignup } from "@/lib/hooks/auth/useSignup";
|
||||
import { StatefulPageWrapper } from '@/components/shared/state/StatefulPageWrapper';
|
||||
export default async function SignupPage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<URLSearchParams>;
|
||||
}) {
|
||||
// Execute PageQuery
|
||||
const params = await searchParams;
|
||||
const queryResult = await SignupPageQuery.execute(params);
|
||||
|
||||
interface FormErrors {
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
password?: string;
|
||||
confirmPassword?: string;
|
||||
submit?: string;
|
||||
}
|
||||
|
||||
interface PasswordStrength {
|
||||
score: number;
|
||||
label: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
interface SignupData {
|
||||
placeholder: string;
|
||||
}
|
||||
|
||||
function checkPasswordStrength(password: string): PasswordStrength {
|
||||
let score = 0;
|
||||
if (password.length >= 8) score++;
|
||||
if (password.length >= 12) score++;
|
||||
if (/[a-z]/.test(password) && /[A-Z]/.test(password)) score++;
|
||||
if (/\d/.test(password)) score++;
|
||||
if (/[^a-zA-Z\d]/.test(password)) score++;
|
||||
|
||||
if (score <= 1) return { score, label: 'Weak', color: 'bg-red-500' };
|
||||
if (score <= 2) return { score, label: 'Fair', color: 'bg-warning-amber' };
|
||||
if (score <= 3) return { score, label: 'Good', color: 'bg-primary-blue' };
|
||||
return { score, label: 'Strong', color: 'bg-performance-green' };
|
||||
}
|
||||
|
||||
const USER_ROLES = [
|
||||
{
|
||||
icon: Car,
|
||||
title: 'Driver',
|
||||
description: 'Race, track stats, join teams',
|
||||
color: 'primary-blue',
|
||||
},
|
||||
{
|
||||
icon: Trophy,
|
||||
title: 'League Admin',
|
||||
description: 'Organize leagues and events',
|
||||
color: 'performance-green',
|
||||
},
|
||||
{
|
||||
icon: Users,
|
||||
title: 'Team Manager',
|
||||
description: 'Manage team and drivers',
|
||||
color: 'purple-400',
|
||||
},
|
||||
];
|
||||
|
||||
const FEATURES = [
|
||||
'Track your racing statistics and progress',
|
||||
'Join or create competitive leagues',
|
||||
'Build or join racing teams',
|
||||
'Connect your iRacing account',
|
||||
'Compete in organized events',
|
||||
'Access detailed performance analytics',
|
||||
];
|
||||
|
||||
const SignupTemplate = ({ data }: { data: SignupData }) => {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { refreshSession } = useAuth();
|
||||
const returnTo = searchParams.get('returnTo') ?? '/onboarding';
|
||||
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
const [formData, setFormData] = useState({
|
||||
firstName: '',
|
||||
lastName: '',
|
||||
email: '',
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
});
|
||||
|
||||
const passwordStrength = checkPasswordStrength(formData.password);
|
||||
|
||||
const passwordRequirements = [
|
||||
{ met: formData.password.length >= 8, label: 'At least 8 characters' },
|
||||
{ met: /[a-z]/.test(formData.password) && /[A-Z]/.test(formData.password), label: 'Upper and lowercase letters' },
|
||||
{ met: /\d/.test(formData.password), label: 'At least one number' },
|
||||
{ met: /[^a-zA-Z\d]/.test(formData.password), label: 'At least one special character' },
|
||||
];
|
||||
|
||||
const validateForm = (): boolean => {
|
||||
const newErrors: FormErrors = {};
|
||||
|
||||
// First name validation
|
||||
const firstName = formData.firstName.trim();
|
||||
if (!firstName) {
|
||||
newErrors.firstName = 'First name is required';
|
||||
} else if (firstName.length < 2) {
|
||||
newErrors.firstName = 'First name must be at least 2 characters';
|
||||
} else if (firstName.length > 25) {
|
||||
newErrors.firstName = 'First name must be no more than 25 characters';
|
||||
} else if (!/^[A-Za-z\-']+$/.test(firstName)) {
|
||||
newErrors.firstName = 'First name can only contain letters, hyphens, and apostrophes';
|
||||
} else if (/^(user|test|demo|guest|player)/i.test(firstName)) {
|
||||
newErrors.firstName = 'Please use your real first name, not a nickname';
|
||||
}
|
||||
|
||||
// Last name validation
|
||||
const lastName = formData.lastName.trim();
|
||||
if (!lastName) {
|
||||
newErrors.lastName = 'Last name is required';
|
||||
} else if (lastName.length < 2) {
|
||||
newErrors.lastName = 'Last name must be at least 2 characters';
|
||||
} else if (lastName.length > 25) {
|
||||
newErrors.lastName = 'Last name must be no more than 25 characters';
|
||||
} else if (!/^[A-Za-z\-']+$/.test(lastName)) {
|
||||
newErrors.lastName = 'Last name can only contain letters, hyphens, and apostrophes';
|
||||
} else if (/^(user|test|demo|guest|player)/i.test(lastName)) {
|
||||
newErrors.lastName = 'Please use your real last name, not a nickname';
|
||||
}
|
||||
|
||||
if (!formData.email.trim()) {
|
||||
newErrors.email = 'Email is required';
|
||||
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
|
||||
newErrors.email = 'Invalid email format';
|
||||
}
|
||||
|
||||
// Password strength validation
|
||||
if (!formData.password) {
|
||||
newErrors.password = 'Password is required';
|
||||
} else if (formData.password.length < 8) {
|
||||
newErrors.password = 'Password must be at least 8 characters';
|
||||
} else if (!/[a-z]/.test(formData.password) || !/[A-Z]/.test(formData.password) || !/\d/.test(formData.password)) {
|
||||
newErrors.password = 'Password must contain uppercase, lowercase, and number';
|
||||
}
|
||||
|
||||
if (!formData.confirmPassword) {
|
||||
newErrors.confirmPassword = 'Please confirm your password';
|
||||
} else if (formData.password !== formData.confirmPassword) {
|
||||
newErrors.confirmPassword = 'Passwords do not match';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
};
|
||||
|
||||
// Use signup mutation hook
|
||||
const signupMutation = useSignup({
|
||||
onSuccess: async () => {
|
||||
// Refresh session in context so header updates immediately
|
||||
try {
|
||||
await refreshSession();
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh session after signup:', error);
|
||||
}
|
||||
// Always redirect to dashboard after signup
|
||||
router.push('/dashboard');
|
||||
},
|
||||
onError: (error) => {
|
||||
setErrors({
|
||||
submit: error.message || 'Signup failed. Please try again.',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (signupMutation.isPending) return;
|
||||
|
||||
if (!validateForm()) return;
|
||||
|
||||
setErrors({});
|
||||
|
||||
try {
|
||||
// Combine first and last name into display name
|
||||
const displayName = `${formData.firstName} ${formData.lastName}`.trim();
|
||||
|
||||
await signupMutation.mutateAsync({
|
||||
email: formData.email,
|
||||
password: formData.password,
|
||||
displayName,
|
||||
});
|
||||
} catch (error) {
|
||||
// Error handling is done in the mutation's onError callback
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-deep-graphite flex">
|
||||
{/* Background Pattern */}
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary-blue/5 via-transparent to-purple-600/5" />
|
||||
<div className="absolute inset-0 opacity-5">
|
||||
<div className="absolute inset-0" style={{
|
||||
backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
|
||||
}} />
|
||||
</div>
|
||||
|
||||
{/* Left Side - Info Panel (Hidden on mobile) */}
|
||||
<div className="hidden lg:flex lg:w-1/2 relative items-center justify-center p-12">
|
||||
<div className="max-w-lg">
|
||||
{/* Logo */}
|
||||
<div className="flex items-center gap-3 mb-8">
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30">
|
||||
<Flag className="w-6 h-6 text-primary-blue" />
|
||||
</div>
|
||||
<span className="text-2xl font-bold text-white">GridPilot</span>
|
||||
</div>
|
||||
|
||||
<Heading level={2} className="text-white mb-4">
|
||||
Start Your Racing Journey
|
||||
</Heading>
|
||||
|
||||
<p className="text-gray-400 text-lg mb-8">
|
||||
Join thousands of sim racers. One account gives you access to all roles - race as a driver, organize leagues, or manage teams.
|
||||
</p>
|
||||
|
||||
{/* Role Cards */}
|
||||
<div className="space-y-3 mb-8">
|
||||
{USER_ROLES.map((role, index) => (
|
||||
<motion.div
|
||||
key={role.title}
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{ delay: index * 0.1 }}
|
||||
className="flex items-center gap-4 p-4 rounded-xl bg-iron-gray/50 border border-charcoal-outline"
|
||||
>
|
||||
<div className={`w-10 h-10 rounded-lg bg-${role.color}/20 flex items-center justify-center`}>
|
||||
<role.icon className={`w-5 h-5 text-${role.color}`} />
|
||||
</div>
|
||||
<div>
|
||||
<h4 className="text-white font-medium">{role.title}</h4>
|
||||
<p className="text-sm text-gray-500">{role.description}</p>
|
||||
</div>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Features List */}
|
||||
<div className="bg-iron-gray/30 rounded-xl border border-charcoal-outline p-5 mb-8">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<Sparkles className="w-4 h-4 text-primary-blue" />
|
||||
<span className="text-sm font-medium text-white">What you'll get</span>
|
||||
</div>
|
||||
<ul className="space-y-2">
|
||||
{FEATURES.map((feature, index) => (
|
||||
<li
|
||||
key={index}
|
||||
className="flex items-center gap-2 text-sm text-gray-400"
|
||||
>
|
||||
<Check className="w-3.5 h-3.5 text-performance-green flex-shrink-0" />
|
||||
{feature}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Trust Indicators */}
|
||||
<div className="flex items-center gap-6 text-sm text-gray-500">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Secure signup</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span>iRacing integration</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Side - Signup Form */}
|
||||
<div className="flex-1 flex items-center justify-center px-4 py-12 overflow-y-auto">
|
||||
<div className="relative w-full max-w-md">
|
||||
{/* Mobile Logo/Header */}
|
||||
<div className="text-center mb-8 lg:hidden">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30 mx-auto mb-4">
|
||||
<Flag className="w-8 h-8 text-primary-blue" />
|
||||
</div>
|
||||
<Heading level={1} className="mb-2">Join GridPilot</Heading>
|
||||
<p className="text-gray-400">
|
||||
Create your account and start racing
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Desktop Header */}
|
||||
<div className="hidden lg:block text-center mb-8">
|
||||
<Heading level={2} className="mb-2">Create Account</Heading>
|
||||
<p className="text-gray-400">
|
||||
Get started with your free account
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="relative overflow-hidden">
|
||||
{/* Background accent */}
|
||||
<div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-primary-blue/10 to-transparent rounded-bl-full" />
|
||||
|
||||
<form onSubmit={handleSubmit} className="relative space-y-4">
|
||||
{/* First Name */}
|
||||
<div>
|
||||
<label htmlFor="firstName" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
First Name
|
||||
</label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="firstName"
|
||||
type="text"
|
||||
value={formData.firstName}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, firstName: e.target.value })}
|
||||
error={!!errors.firstName}
|
||||
errorMessage={errors.firstName}
|
||||
placeholder="John"
|
||||
disabled={signupMutation.isPending}
|
||||
className="pl-10"
|
||||
autoComplete="given-name"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Last Name */}
|
||||
<div>
|
||||
<label htmlFor="lastName" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Last Name
|
||||
</label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="lastName"
|
||||
type="text"
|
||||
value={formData.lastName}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, lastName: e.target.value })}
|
||||
error={!!errors.lastName}
|
||||
errorMessage={errors.lastName}
|
||||
placeholder="Smith"
|
||||
disabled={signupMutation.isPending}
|
||||
className="pl-10"
|
||||
autoComplete="family-name"
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-gray-500">Your name will be used as-is and cannot be changed later</p>
|
||||
</div>
|
||||
|
||||
{/* Name Immutability Warning */}
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-warning-amber/10 border border-warning-amber/30">
|
||||
<AlertCircle className="w-5 h-5 text-warning-amber flex-shrink-0 mt-0.5" />
|
||||
<div className="text-sm text-warning-amber">
|
||||
<strong>Important:</strong> Your name cannot be changed after signup. Please ensure it's correct.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Email */}
|
||||
<div>
|
||||
<label htmlFor="email" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Email Address
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, email: e.target.value })}
|
||||
error={!!errors.email}
|
||||
errorMessage={errors.email}
|
||||
placeholder="you@example.com"
|
||||
disabled={signupMutation.isPending}
|
||||
className="pl-10"
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Password */}
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Password
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="password"
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
value={formData.password}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, password: e.target.value })}
|
||||
error={!!errors.password}
|
||||
errorMessage={errors.password}
|
||||
placeholder="••••••••"
|
||||
disabled={signupMutation.isPending}
|
||||
className="pl-10 pr-10"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300"
|
||||
>
|
||||
{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Password Strength */}
|
||||
{formData.password && (
|
||||
<div className="mt-3 space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1 h-1.5 rounded-full bg-charcoal-outline overflow-hidden">
|
||||
<motion.div
|
||||
className={`h-full ${passwordStrength.color}`}
|
||||
initial={{ width: 0 }}
|
||||
animate={{ width: `${(passwordStrength.score / 5) * 100}%` }}
|
||||
transition={{ duration: 0.3 }}
|
||||
/>
|
||||
</div>
|
||||
<span className={`text-xs font-medium ${
|
||||
passwordStrength.score <= 1 ? 'text-red-400' :
|
||||
passwordStrength.score <= 2 ? 'text-warning-amber' :
|
||||
passwordStrength.score <= 3 ? 'text-primary-blue' :
|
||||
'text-performance-green'
|
||||
}`}>
|
||||
{passwordStrength.label}
|
||||
</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-1">
|
||||
{passwordRequirements.map((req, index) => (
|
||||
<div key={index} className="flex items-center gap-1.5 text-xs">
|
||||
{req.met ? (
|
||||
<Check className="w-3 h-3 text-performance-green" />
|
||||
) : (
|
||||
<X className="w-3 h-3 text-gray-500" />
|
||||
)}
|
||||
<span className={req.met ? 'text-gray-300' : 'text-gray-500'}>
|
||||
{req.label}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Confirm Password */}
|
||||
<div>
|
||||
<label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-300 mb-2">
|
||||
Confirm Password
|
||||
</label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500" />
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type={showConfirmPassword ? 'text' : 'password'}
|
||||
value={formData.confirmPassword}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => setFormData({ ...formData, confirmPassword: e.target.value })}
|
||||
error={!!errors.confirmPassword}
|
||||
errorMessage={errors.confirmPassword}
|
||||
placeholder="••••••••"
|
||||
disabled={signupMutation.isPending}
|
||||
className="pl-10 pr-10"
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-300"
|
||||
>
|
||||
{showConfirmPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
{formData.confirmPassword && formData.password === formData.confirmPassword && (
|
||||
<p className="mt-1 text-xs text-performance-green flex items-center gap-1">
|
||||
<Check className="w-3 h-3" /> Passwords match
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Submit Button */}
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={signupMutation.isPending}
|
||||
className="w-full flex items-center justify-center gap-2"
|
||||
>
|
||||
{signupMutation.isPending ? (
|
||||
<>
|
||||
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
|
||||
Creating account...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<UserPlus className="w-4 h-4" />
|
||||
Create Account
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="relative my-6">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t border-charcoal-outline" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs">
|
||||
<span className="px-4 bg-iron-gray text-gray-500">or continue with</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Login Link */}
|
||||
<p className="mt-6 text-center text-sm text-gray-400">
|
||||
Already have an account?{' '}
|
||||
<Link
|
||||
href={`/auth/login${returnTo !== '/onboarding' ? `?returnTo=${encodeURIComponent(returnTo)}` : ''}`}
|
||||
className="text-primary-blue hover:underline font-medium"
|
||||
>
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</Card>
|
||||
|
||||
{/* Footer */}
|
||||
<p className="mt-6 text-center text-xs text-gray-500">
|
||||
By creating an account, you agree to our{' '}
|
||||
<Link href="/terms" className="text-gray-400 hover:underline">Terms of Service</Link>
|
||||
{' '}and{' '}
|
||||
<Link href="/privacy" className="text-gray-400 hover:underline">Privacy Policy</Link>
|
||||
</p>
|
||||
|
||||
{/* Mobile Role Info */}
|
||||
<div className="mt-8 lg:hidden">
|
||||
<p className="text-center text-xs text-gray-500 mb-4">One account for all roles</p>
|
||||
<div className="flex justify-center gap-6">
|
||||
{USER_ROLES.map((role) => (
|
||||
<div key={role.title} className="flex flex-col items-center">
|
||||
<div className={`w-8 h-8 rounded-lg bg-${role.color}/20 flex items-center justify-center mb-1`}>
|
||||
<role.icon className={`w-4 h-4 text-${role.color}`} />
|
||||
</div>
|
||||
<span className="text-xs text-gray-500">{role.title}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
|
||||
export default function SignupPage() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const { refreshSession, session } = useAuth();
|
||||
const returnTo = searchParams.get('returnTo') ?? '/onboarding';
|
||||
|
||||
const [checkingAuth, setCheckingAuth] = useState(true);
|
||||
|
||||
// Check if already authenticated
|
||||
useEffect(() => {
|
||||
if (session) {
|
||||
// Already logged in, redirect to dashboard or return URL
|
||||
router.replace(returnTo === '/onboarding' ? '/dashboard' : returnTo);
|
||||
return;
|
||||
}
|
||||
|
||||
// If no session, still check via API for consistency
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const response = await fetch('/api/auth/session');
|
||||
const data = await response.json();
|
||||
if (data.authenticated) {
|
||||
// Already logged in, redirect to dashboard or return URL
|
||||
router.replace(returnTo === '/onboarding' ? '/dashboard' : returnTo);
|
||||
}
|
||||
} catch {
|
||||
// Not authenticated, continue showing signup page
|
||||
} finally {
|
||||
setCheckingAuth(false);
|
||||
}
|
||||
}
|
||||
checkAuth();
|
||||
}, [session, router, returnTo]);
|
||||
|
||||
// Use signup mutation hook for state management
|
||||
const signupMutation = useSignup({
|
||||
onSuccess: async () => {
|
||||
// Refresh session in context so header updates immediately
|
||||
try {
|
||||
await refreshSession();
|
||||
} catch (error) {
|
||||
console.error('Failed to refresh session after signup:', error);
|
||||
}
|
||||
// Always redirect to dashboard after signup
|
||||
router.push('/dashboard');
|
||||
},
|
||||
onError: (error) => {
|
||||
// Error will be handled in the template
|
||||
console.error('Signup error:', error);
|
||||
},
|
||||
});
|
||||
|
||||
// Loading state from mutation
|
||||
const loading = signupMutation.isPending;
|
||||
|
||||
// Show loading while checking auth
|
||||
if (checkingAuth) {
|
||||
if (queryResult.isErr()) {
|
||||
// Handle query error
|
||||
return (
|
||||
<main className="min-h-screen bg-deep-graphite flex items-center justify-center">
|
||||
<div className="w-8 h-8 border-2 border-primary-blue border-t-transparent rounded-full animate-spin" />
|
||||
</main>
|
||||
<div className="min-h-screen bg-deep-graphite flex items-center justify-center">
|
||||
<div className="text-red-400">Failed to load signup page</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Map mutation states to StatefulPageWrapper
|
||||
return (
|
||||
<StatefulPageWrapper
|
||||
data={{ placeholder: 'data' } as SignupData}
|
||||
isLoading={loading}
|
||||
error={signupMutation.error}
|
||||
retry={() => signupMutation.mutate({ email: '', password: '', displayName: '' })}
|
||||
Template={SignupTemplate}
|
||||
loading={{ variant: 'full-screen', message: 'Processing signup...' }}
|
||||
errorConfig={{ variant: 'full-screen' }}
|
||||
/>
|
||||
);
|
||||
const viewData = queryResult.unwrap();
|
||||
|
||||
// Render client component with ViewData
|
||||
return <SignupClient viewData={viewData} />;
|
||||
}
|
||||
Reference in New Issue
Block a user