mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-21 18:31:12 -05:00
feat: Implement MFA Step-Up for OAuth
This commit is contained in:
@@ -46,6 +46,7 @@ import BlogPost from "./pages/BlogPost";
|
|||||||
import AdminBlog from "./pages/AdminBlog";
|
import AdminBlog from "./pages/AdminBlog";
|
||||||
import ForceLogout from "./pages/ForceLogout";
|
import ForceLogout from "./pages/ForceLogout";
|
||||||
import AuthCallback from "./pages/AuthCallback";
|
import AuthCallback from "./pages/AuthCallback";
|
||||||
|
import MFAStepUp from "./pages/MFAStepUp";
|
||||||
|
|
||||||
const queryClient = new QueryClient({
|
const queryClient = new QueryClient({
|
||||||
defaultOptions: {
|
defaultOptions: {
|
||||||
@@ -93,6 +94,7 @@ function AppContent() {
|
|||||||
<Route path="/operators/:operatorSlug/parks" element={<OperatorParks />} />
|
<Route path="/operators/:operatorSlug/parks" element={<OperatorParks />} />
|
||||||
<Route path="/auth" element={<Auth />} />
|
<Route path="/auth" element={<Auth />} />
|
||||||
<Route path="/auth/callback" element={<AuthCallback />} />
|
<Route path="/auth/callback" element={<AuthCallback />} />
|
||||||
|
<Route path="/auth/mfa-step-up" element={<MFAStepUp />} />
|
||||||
<Route path="/profile" element={<Profile />} />
|
<Route path="/profile" element={<Profile />} />
|
||||||
<Route path="/profile/:username" element={<Profile />} />
|
<Route path="/profile/:username" element={<Profile />} />
|
||||||
<Route path="/settings" element={<UserSettings />} />
|
<Route path="/settings" element={<UserSettings />} />
|
||||||
|
|||||||
@@ -2,21 +2,46 @@ import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Shield } from 'lucide-react';
|
import { Shield } from 'lucide-react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { useAuth } from '@/hooks/useAuth';
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
export function MFARequiredAlert() {
|
export function MFARequiredAlert() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const { checkAalStepUp } = useAuth();
|
||||||
|
const [needsVerification, setNeedsVerification] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
checkAalStepUp().then(result => {
|
||||||
|
setNeedsVerification(result.needsStepUp);
|
||||||
|
});
|
||||||
|
}, [checkAalStepUp]);
|
||||||
|
|
||||||
|
const handleAction = () => {
|
||||||
|
if (needsVerification) {
|
||||||
|
// User has MFA enrolled but needs to verify
|
||||||
|
sessionStorage.setItem('mfa_step_up_required', 'true');
|
||||||
|
navigate('/auth/mfa-step-up');
|
||||||
|
} else {
|
||||||
|
// User needs to enroll in MFA
|
||||||
|
navigate('/settings?tab=security');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Alert variant="destructive" className="my-4">
|
<Alert variant="destructive" className="my-4">
|
||||||
<Shield className="h-4 w-4" />
|
<Shield className="h-4 w-4" />
|
||||||
<AlertTitle>Two-Factor Authentication Required</AlertTitle>
|
<AlertTitle>Two-Factor Authentication Required</AlertTitle>
|
||||||
<AlertDescription className="mt-2 space-y-3">
|
<AlertDescription className="mt-2 space-y-3">
|
||||||
<p>Your role requires two-factor authentication to access this area.</p>
|
<p>
|
||||||
|
{needsVerification
|
||||||
|
? 'Please verify your identity with two-factor authentication to access this area.'
|
||||||
|
: 'Your role requires two-factor authentication to access this area.'}
|
||||||
|
</p>
|
||||||
<Button
|
<Button
|
||||||
onClick={() => navigate('/settings?tab=security')}
|
onClick={handleAction}
|
||||||
size="sm"
|
size="sm"
|
||||||
>
|
>
|
||||||
Set up MFA
|
{needsVerification ? 'Verify Now' : 'Set up MFA'}
|
||||||
</Button>
|
</Button>
|
||||||
</AlertDescription>
|
</AlertDescription>
|
||||||
</Alert>
|
</Alert>
|
||||||
|
|||||||
@@ -111,16 +111,31 @@ export function TOTPSetup() {
|
|||||||
|
|
||||||
if (verifyError) throw verifyError;
|
if (verifyError) throw verifyError;
|
||||||
|
|
||||||
|
// Check if user signed in via OAuth
|
||||||
|
const { data: { session } } = await supabase.auth.getSession();
|
||||||
|
const provider = session?.user?.app_metadata?.provider;
|
||||||
|
const isOAuthUser = provider === 'google' || provider === 'discord';
|
||||||
|
|
||||||
toast({
|
toast({
|
||||||
title: 'TOTP Enabled',
|
title: 'TOTP Enabled',
|
||||||
description: 'Please sign in again to activate MFA protection.'
|
description: isOAuthUser
|
||||||
|
? 'Please verify with your authenticator code to continue.'
|
||||||
|
: 'Please sign in again to activate MFA protection.'
|
||||||
});
|
});
|
||||||
|
|
||||||
// Force sign out to get new session with AAL2
|
if (isOAuthUser) {
|
||||||
|
// For OAuth users, trigger step-up flow immediately
|
||||||
|
setTimeout(() => {
|
||||||
|
sessionStorage.setItem('mfa_step_up_required', 'true');
|
||||||
|
window.location.href = '/auth/mfa-step-up';
|
||||||
|
}, 1500);
|
||||||
|
} else {
|
||||||
|
// For email/password users, force sign out to require MFA on next login
|
||||||
setTimeout(async () => {
|
setTimeout(async () => {
|
||||||
await supabase.auth.signOut();
|
await supabase.auth.signOut();
|
||||||
window.location.href = '/auth';
|
window.location.href = '/auth';
|
||||||
}, 2000);
|
}, 2000);
|
||||||
|
}
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
toast({
|
toast({
|
||||||
title: 'Error',
|
title: 'Error',
|
||||||
|
|||||||
@@ -5,6 +5,12 @@ import type { Profile } from '@/types/database';
|
|||||||
import { toast } from '@/hooks/use-toast';
|
import { toast } from '@/hooks/use-toast';
|
||||||
import { authLog, authWarn, authError } from '@/lib/authLogger';
|
import { authLog, authWarn, authError } from '@/lib/authLogger';
|
||||||
|
|
||||||
|
export interface CheckAalResult {
|
||||||
|
needsStepUp: boolean;
|
||||||
|
hasMfaEnrolled: boolean;
|
||||||
|
currentLevel: 'aal1' | 'aal2' | null;
|
||||||
|
}
|
||||||
|
|
||||||
interface AuthContextType {
|
interface AuthContextType {
|
||||||
user: User | null;
|
user: User | null;
|
||||||
session: Session | null;
|
session: Session | null;
|
||||||
@@ -15,6 +21,7 @@ interface AuthContextType {
|
|||||||
signOut: () => Promise<void>;
|
signOut: () => Promise<void>;
|
||||||
verifySession: () => Promise<boolean>;
|
verifySession: () => Promise<boolean>;
|
||||||
clearPendingEmail: () => void;
|
clearPendingEmail: () => void;
|
||||||
|
checkAalStepUp: () => Promise<CheckAalResult>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||||
@@ -221,6 +228,29 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
|||||||
setPendingEmail(null);
|
setPendingEmail(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const checkAalStepUp = async (): Promise<CheckAalResult> => {
|
||||||
|
if (!session?.user) {
|
||||||
|
return { needsStepUp: false, hasMfaEnrolled: false, currentLevel: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { data: { currentLevel } } =
|
||||||
|
await supabase.auth.mfa.getAuthenticatorAssuranceLevel();
|
||||||
|
|
||||||
|
const { data: factors } = await supabase.auth.mfa.listFactors();
|
||||||
|
const hasMfaEnrolled = factors?.totp?.some(f => f.status === 'verified') || false;
|
||||||
|
|
||||||
|
return {
|
||||||
|
needsStepUp: hasMfaEnrolled && currentLevel === 'aal1',
|
||||||
|
hasMfaEnrolled,
|
||||||
|
currentLevel: currentLevel as 'aal1' | 'aal2' | null,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
authError('[Auth] Failed to check AAL status:', error);
|
||||||
|
return { needsStepUp: false, hasMfaEnrolled: false, currentLevel: null };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const value = {
|
const value = {
|
||||||
user,
|
user,
|
||||||
session,
|
session,
|
||||||
@@ -231,6 +261,7 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) {
|
|||||||
signOut,
|
signOut,
|
||||||
verifySession,
|
verifySession,
|
||||||
clearPendingEmail,
|
clearPendingEmail,
|
||||||
|
checkAalStepUp,
|
||||||
};
|
};
|
||||||
|
|
||||||
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
||||||
|
|||||||
@@ -71,6 +71,33 @@ export default function AuthCallback() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check if MFA step-up is required for OAuth users
|
||||||
|
if (isOAuthUser) {
|
||||||
|
console.log('[AuthCallback] Checking MFA requirements for OAuth user...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { data: factors } = await supabase.auth.mfa.listFactors();
|
||||||
|
const hasMfaEnrolled = factors?.totp?.some(f => f.status === 'verified');
|
||||||
|
|
||||||
|
const { data: { currentLevel } } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel();
|
||||||
|
|
||||||
|
console.log('[AuthCallback] MFA status:', {
|
||||||
|
hasMfaEnrolled,
|
||||||
|
currentLevel,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (hasMfaEnrolled && currentLevel === 'aal1') {
|
||||||
|
console.log('[AuthCallback] MFA step-up required, redirecting...');
|
||||||
|
sessionStorage.setItem('mfa_step_up_required', 'true');
|
||||||
|
navigate('/auth/mfa-step-up');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[AuthCallback] Failed to check MFA status:', error);
|
||||||
|
// Continue anyway - don't block sign-in
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
setStatus('success');
|
setStatus('success');
|
||||||
|
|
||||||
// Show success message
|
// Show success message
|
||||||
|
|||||||
116
src/pages/MFAStepUp.tsx
Normal file
116
src/pages/MFAStepUp.tsx
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
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';
|
||||||
|
|
||||||
|
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
|
||||||
|
const needsStepUp = sessionStorage.getItem('mfa_step_up_required');
|
||||||
|
if (!needsStepUp) {
|
||||||
|
console.log('[MFAStepUp] No step-up flag found, redirecting to auth');
|
||||||
|
navigate('/auth');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the verified TOTP factor
|
||||||
|
const { data: factors } = await supabase.auth.mfa.listFactors();
|
||||||
|
const totpFactor = factors?.totp?.find(f => f.status === 'verified');
|
||||||
|
|
||||||
|
if (!totpFactor) {
|
||||||
|
console.log('[MFAStepUp] No verified TOTP factor found');
|
||||||
|
toast({
|
||||||
|
variant: 'destructive',
|
||||||
|
title: 'MFA not enrolled',
|
||||||
|
description: 'Please enroll in two-factor authentication first.',
|
||||||
|
});
|
||||||
|
sessionStorage.removeItem('mfa_step_up_required');
|
||||||
|
navigate('/settings?tab=security');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setFactorId(totpFactor.id);
|
||||||
|
};
|
||||||
|
|
||||||
|
checkStepUpRequired();
|
||||||
|
}, [navigate, toast]);
|
||||||
|
|
||||||
|
const handleSuccess = async () => {
|
||||||
|
console.log('[MFAStepUp] MFA verification successful');
|
||||||
|
|
||||||
|
// Clear the step-up flag
|
||||||
|
sessionStorage.removeItem('mfa_step_up_required');
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: 'Verification successful',
|
||||||
|
description: 'You now have full access to all features.',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Redirect to home or intended destination
|
||||||
|
const intendedPath = sessionStorage.getItem('mfa_intended_path') || '/';
|
||||||
|
sessionStorage.removeItem('mfa_intended_path');
|
||||||
|
navigate(intendedPath);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleCancel = async () => {
|
||||||
|
console.log('[MFAStepUp] MFA verification cancelled');
|
||||||
|
|
||||||
|
// Clear flags
|
||||||
|
sessionStorage.removeItem('mfa_step_up_required');
|
||||||
|
sessionStorage.removeItem('mfa_intended_path');
|
||||||
|
|
||||||
|
// Sign out for security
|
||||||
|
await supabase.auth.signOut();
|
||||||
|
|
||||||
|
toast({
|
||||||
|
title: 'Verification cancelled',
|
||||||
|
description: 'You have been signed out.',
|
||||||
|
});
|
||||||
|
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user