feat: Implement modal-based MFA step-up

This commit is contained in:
gpt-engineer-app[bot]
2025-10-17 19:17:46 +00:00
parent 152a90ae9d
commit 0eac7f3d7d
6 changed files with 123 additions and 116 deletions

View File

@@ -50,7 +50,6 @@ import BlogPost from "./pages/BlogPost";
import AdminBlog from "./pages/AdminBlog";
import ForceLogout from "./pages/ForceLogout";
import AuthCallback from "./pages/AuthCallback";
import MFAStepUp from "./pages/MFAStepUp";
const queryClient = new QueryClient({
defaultOptions: {
@@ -101,7 +100,6 @@ function AppContent() {
<Route path="/operators/:operatorSlug/parks" element={<OperatorParks />} />
<Route path="/auth" element={<Auth />} />
<Route path="/auth/callback" element={<AuthCallback />} />
<Route path="/auth/mfa-step-up" element={<MFAStepUp />} />
<Route path="/profile" element={<Profile />} />
<Route path="/profile/:username" element={<Profile />} />
<Route path="/settings" element={<UserSettings />} />

View File

@@ -94,6 +94,24 @@ export function AuthModal({ open, onOpenChange, defaultTab = 'signin' }: AuthMod
// Track auth method for audit logging
setAuthMethod('password');
// Check if MFA step-up is required
const { handlePostAuthFlow } = await import('@/lib/authService');
const postAuthResult = await handlePostAuthFlow(data.session, 'password');
if (postAuthResult.success && postAuthResult.data.shouldRedirect) {
console.log('[AuthModal] MFA step-up required');
// Get the TOTP factor ID
const { data: factors } = await supabase.auth.mfa.listFactors();
const totpFactor = factors?.totp?.find(f => f.status === 'verified');
if (totpFactor) {
setMfaFactorId(totpFactor.id);
setLoading(false);
return; // Stay in modal, show MFA challenge
}
}
toast({
title: "Welcome back!",
description: "You've been signed in successfully."

View File

@@ -0,0 +1,34 @@
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { MFAChallenge } from './MFAChallenge';
import { Shield } from 'lucide-react';
interface MFAStepUpModalProps {
open: boolean;
factorId: string;
onSuccess: () => void;
onCancel: () => void;
}
export function MFAStepUpModal({ open, factorId, onSuccess, onCancel }: MFAStepUpModalProps) {
return (
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onCancel()}>
<DialogContent className="sm:max-w-md" onInteractOutside={(e) => e.preventDefault()}>
<DialogHeader>
<div className="flex items-center gap-2 justify-center mb-2">
<Shield className="h-6 w-6 text-primary" />
<DialogTitle>Additional Verification Required</DialogTitle>
</div>
<DialogDescription className="text-center">
Your role requires two-factor authentication. Please verify your identity to continue.
</DialogDescription>
</DialogHeader>
<MFAChallenge
factorId={factorId}
onSuccess={onSuccess}
onCancel={onCancel}
/>
</DialogContent>
</Dialog>
);
}

View File

@@ -122,6 +122,24 @@ export default function Auth() {
// Track auth method for audit logging
setAuthMethod('password');
// Check if MFA step-up is required
const { handlePostAuthFlow } = await import('@/lib/authService');
const postAuthResult = await handlePostAuthFlow(data.session, 'password');
if (postAuthResult.success && postAuthResult.data.shouldRedirect) {
console.log('[Auth] MFA step-up required');
// Get the TOTP factor ID
const { data: factors } = await supabase.auth.mfa.listFactors();
const totpFactor = factors?.totp?.find(f => f.status === 'verified');
if (totpFactor) {
setMfaFactorId(totpFactor.id);
setLoading(false);
return; // Stay on page, show MFA modal
}
}
console.log('[Auth] Sign in successful', {
user: data.user?.email,
session: !!data.session,

View File

@@ -4,18 +4,20 @@ import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { Loader2, CheckCircle2 } from 'lucide-react';
import { Header } from '@/components/layout/Header';
import { handlePostAuthFlow } from '@/lib/authService';
import { handlePostAuthFlow, verifyMfaUpgrade } from '@/lib/authService';
import type { AuthMethod } from '@/types/auth';
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { getErrorMessage } from '@/lib/errorHandler';
import { MFAStepUpModal } from '@/components/auth/MFAStepUpModal';
export default function AuthCallback() {
const navigate = useNavigate();
const { toast } = useToast();
const [status, setStatus] = useState<'processing' | 'success' | 'error'>('processing');
const [status, setStatus] = useState<'processing' | 'success' | 'error' | 'mfa_required'>('processing');
const [mfaFactorId, setMfaFactorId] = useState<string | null>(null);
const [isRecoveryMode, setIsRecoveryMode] = useState(false);
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
@@ -105,9 +107,17 @@ export default function AuthCallback() {
const result = await handlePostAuthFlow(session, authMethod);
if (result.success && result.data?.shouldRedirect) {
console.log('[AuthCallback] Redirecting to:', result.data.redirectTo);
navigate(result.data.redirectTo);
return;
console.log('[AuthCallback] MFA step-up required - showing modal');
// Get factor ID and show modal instead of redirecting
const { data: factors } = await supabase.auth.mfa.listFactors();
const totpFactor = factors?.totp?.find(f => f.status === 'verified');
if (totpFactor) {
setMfaFactorId(totpFactor.id);
setStatus('mfa_required');
return;
}
}
setStatus('success');
@@ -146,6 +156,32 @@ export default function AuthCallback() {
processOAuthCallback();
}, [navigate, toast]);
const handleMfaSuccess = async () => {
const { data: { session } } = await supabase.auth.getSession();
const verification = await verifyMfaUpgrade(session);
if (!verification.success) {
toast({
variant: "destructive",
title: "MFA Verification Failed",
description: verification.error || "Failed to upgrade session."
});
await supabase.auth.signOut();
navigate('/auth');
return;
}
setMfaFactorId(null);
setStatus('success');
toast({
title: 'Welcome to ThrillWiki!',
description: 'You have been signed in successfully.',
});
setTimeout(() => navigate('/'), 500);
};
const handlePasswordReset = async (e: React.FormEvent) => {
e.preventDefault();
@@ -288,6 +324,18 @@ export default function AuthCallback() {
)}
</div>
</main>
{status === 'mfa_required' && mfaFactorId && (
<MFAStepUpModal
open={true}
factorId={mfaFactorId}
onSuccess={handleMfaSuccess}
onCancel={() => {
setMfaFactorId(null);
navigate('/auth');
}}
/>
)}
</div>
);
}

View File

@@ -1,109 +0,0 @@
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { Header } from '@/components/layout/Header';
import { MFAChallenge } from '@/components/auth/MFAChallenge';
import { Shield } from 'lucide-react';
import { getStepUpRequired, getIntendedPath, clearStepUpFlags } from '@/lib/sessionFlags';
import { getEnrolledFactors } from '@/lib/authService';
export default function MFAStepUp() {
const navigate = useNavigate();
const { toast } = useToast();
const [factorId, setFactorId] = useState<string | null>(null);
useEffect(() => {
const checkStepUpRequired = async () => {
// Check if this page was accessed via proper flow
if (!getStepUpRequired()) {
console.log('[MFAStepUp] No step-up flag found, redirecting to auth');
navigate('/auth');
return;
}
// Get enrolled MFA factors
const factors = await getEnrolledFactors();
if (factors.length === 0) {
console.log('[MFAStepUp] No verified TOTP factor found');
toast({
variant: 'destructive',
title: 'MFA not enrolled',
description: 'Please enroll in two-factor authentication first.',
});
clearStepUpFlags();
navigate('/settings?tab=security');
return;
}
setFactorId(factors[0].id);
};
checkStepUpRequired();
}, [navigate, toast]);
const handleSuccess = async () => {
console.log('[MFAStepUp] MFA verification successful');
toast({
title: 'Verification successful',
description: 'You now have full access to all features.',
});
// Redirect to home or intended destination
const intendedPath = getIntendedPath();
clearStepUpFlags();
navigate(intendedPath);
};
const handleCancel = async () => {
console.log('[MFAStepUp] MFA verification cancelled');
// Clear flags and redirect to sign-in (less harsh than forcing sign-out)
clearStepUpFlags();
toast({
title: 'Verification cancelled',
description: 'Please sign in again to continue.',
});
navigate('/auth');
};
return (
<div className="min-h-screen bg-background">
<Header />
<main className="container mx-auto px-4 py-16">
<div className="max-w-md mx-auto">
<div className="bg-card border rounded-lg p-6 space-y-6">
<div className="text-center space-y-2">
<div className="flex justify-center">
<div className="h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center">
<Shield className="h-6 w-6 text-primary" />
</div>
</div>
<h2 className="text-2xl font-bold">Additional Verification Required</h2>
<p className="text-muted-foreground">
Your role requires two-factor authentication. Please verify your identity to continue.
</p>
</div>
{factorId ? (
<MFAChallenge
factorId={factorId}
onSuccess={handleSuccess}
onCancel={handleCancel}
/>
) : (
<div className="flex justify-center py-4">
<div className="animate-spin h-6 w-6 border-2 border-primary border-t-transparent rounded-full" />
</div>
)}
</div>
</div>
</main>
</div>
);
}