380 lines
15 KiB
TypeScript
380 lines
15 KiB
TypeScript
'use client';
|
|
|
|
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 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 '@/hooks/auth/useLogin';
|
|
import AuthWorkflowMockup from '@/components/auth/AuthWorkflowMockup';
|
|
import UserRolesPreview from '@/components/auth/UserRolesPreview';
|
|
import { EnhancedFormError, FormErrorSummary } from '@/components/errors/EnhancedFormError';
|
|
import { useEnhancedForm } from '@/lib/hooks/useEnhancedForm';
|
|
import { validateLoginForm, type LoginFormValues } from '@/lib/utils/validation';
|
|
import { logErrorWithContext } from '@/lib/utils/errorUtils';
|
|
|
|
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,
|
|
setFormError,
|
|
} = 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);
|
|
},
|
|
});
|
|
|
|
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">
|
|
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 => ({ ...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>
|
|
);
|
|
} |