feat: Implement automatic MFA verification modal

This commit is contained in:
gpt-engineer-app[bot]
2025-11-05 00:48:39 +00:00
parent c4f975ff12
commit df9f997c64
9 changed files with 348 additions and 232 deletions

View File

@@ -1,6 +1,6 @@
import { ReactNode, useCallback } from 'react';
import { AdminLayout } from '@/components/layout/AdminLayout';
import { MFARequiredAlert } from '@/components/auth/MFARequiredAlert';
import { MFAGuard } from '@/components/auth/MFAGuard';
import { QueueSkeleton } from '@/components/moderation/QueueSkeleton';
import { useAdminGuard } from '@/hooks/useAdminGuard';
import { useAdminSettings } from '@/hooks/useAdminSettings';
@@ -104,15 +104,6 @@ export function AdminPageLayout({
return null;
}
// MFA required
if (needsMFA) {
return (
<AdminLayout>
<MFARequiredAlert />
</AdminLayout>
);
}
// Main content
return (
<AdminLayout
@@ -121,6 +112,7 @@ export function AdminPageLayout({
pollInterval={showRefreshControls ? pollInterval : undefined}
lastUpdated={showRefreshControls ? (lastUpdated as Date) : undefined}
>
<MFAGuard>
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">{title}</h1>
@@ -128,6 +120,7 @@ export function AdminPageLayout({
</div>
{children}
</div>
</MFAGuard>
</AdminLayout>
);
}

View File

@@ -0,0 +1,106 @@
import { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { MFAChallenge } from './MFAChallenge';
import { Shield, AlertCircle, Loader2 } from 'lucide-react';
import { getEnrolledFactors } from '@/lib/authService';
import { useAuth } from '@/hooks/useAuth';
interface AutoMFAVerificationModalProps {
open: boolean;
onSuccess: () => void;
onCancel: () => void;
}
export function AutoMFAVerificationModal({
open,
onSuccess,
onCancel
}: AutoMFAVerificationModalProps) {
const { session } = useAuth();
const [factorId, setFactorId] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// Fetch enrolled factor automatically when modal opens
useEffect(() => {
if (!open || !session) return;
const fetchFactor = async () => {
setLoading(true);
setError(null);
try {
const factors = await getEnrolledFactors();
if (factors.length === 0) {
setError('No MFA method enrolled. Please set up MFA in settings.');
return;
}
// Use the first verified TOTP factor
const totpFactor = factors.find(f => f.factor_type === 'totp');
if (totpFactor) {
setFactorId(totpFactor.id);
} else {
setError('No valid MFA method found. Please check your security settings.');
}
} catch (err) {
setError('Failed to load MFA settings. Please try again.');
console.error('Failed to fetch MFA factors:', err);
} finally {
setLoading(false);
}
};
fetchFactor();
}, [open, session]);
return (
<Dialog
open={open}
onOpenChange={(isOpen) => {
if (!isOpen) {
onCancel();
}
}}
>
<DialogContent
className="sm:max-w-md"
onInteractOutside={(e) => e.preventDefault()}
onEscapeKeyDown={(e) => e.preventDefault()}
>
<DialogHeader>
<div className="flex items-center gap-2 justify-center mb-2">
<Shield className="h-6 w-6 text-primary" />
<DialogTitle>Verification Required</DialogTitle>
</div>
<DialogDescription className="text-center">
Your session requires Multi-Factor Authentication to access this area.
</DialogDescription>
</DialogHeader>
{loading && (
<div className="flex flex-col items-center justify-center py-8 space-y-3">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<p className="text-sm text-muted-foreground">Loading verification...</p>
</div>
)}
{error && (
<div className="flex flex-col items-center justify-center py-6 space-y-3">
<AlertCircle className="h-8 w-8 text-destructive" />
<p className="text-sm text-center text-muted-foreground">{error}</p>
</div>
)}
{!loading && !error && factorId && (
<MFAChallenge
factorId={factorId}
onSuccess={onSuccess}
onCancel={onCancel}
/>
)}
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,26 @@
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Shield } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
export function MFAEnrollmentRequired() {
const navigate = useNavigate();
return (
<Alert variant="destructive" className="my-4">
<Shield className="h-4 w-4" />
<AlertTitle>Multi-Factor Authentication Setup Required</AlertTitle>
<AlertDescription className="mt-2 space-y-3">
<p>
Your role requires Multi-Factor Authentication. Please set up MFA to access this area.
</p>
<Button
onClick={() => navigate('/settings?tab=security')}
size="sm"
>
Set up Multi-Factor Authentication
</Button>
</AlertDescription>
</Alert>
);
}

View File

@@ -0,0 +1,65 @@
import { useRequireMFA } from '@/hooks/useRequireMFA';
import { AutoMFAVerificationModal } from './AutoMFAVerificationModal';
import { MFAEnrollmentRequired } from './MFAEnrollmentRequired';
import { useAuth } from '@/hooks/useAuth';
import { useToast } from '@/hooks/use-toast';
interface MFAGuardProps {
children: React.ReactNode;
}
/**
* Smart MFA guard that automatically shows verification modal or enrollment alert
*
* Usage:
* ```tsx
* <MFAGuard>
* <YourProtectedContent />
* </MFAGuard>
* ```
*/
export function MFAGuard({ children }: MFAGuardProps) {
const { needsEnrollment, needsVerification, loading } = useRequireMFA();
const { verifySession } = useAuth();
const { toast } = useToast();
const handleVerificationSuccess = async () => {
// Refresh the session to get updated AAL level
await verifySession();
toast({
title: 'Verification Successful',
description: 'You can now access this area.',
});
};
const handleVerificationCancel = () => {
// Redirect back to main dashboard
window.location.href = '/';
};
// Show verification modal automatically when needed
if (needsVerification) {
return (
<>
<AutoMFAVerificationModal
open={true}
onSuccess={handleVerificationSuccess}
onCancel={handleVerificationCancel}
/>
{/* Show blurred content behind modal */}
<div className="pointer-events-none opacity-50 blur-sm">
{children}
</div>
</>
);
}
// Show enrollment alert when user hasn't set up MFA
if (needsEnrollment) {
return <MFAEnrollmentRequired />;
}
// User has MFA and is verified - show content
return <>{children}</>;
}

View File

@@ -1,49 +0,0 @@
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Shield } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/hooks/useAuth';
import { useEffect, useState } from 'react';
export function MFARequiredAlert() {
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 (
<Alert variant="destructive" className="my-4">
<Shield className="h-4 w-4" />
<AlertTitle>Multi-Factor Authentication Required</AlertTitle>
<AlertDescription className="mt-2 space-y-3">
<p>
{needsVerification
? 'Please verify your identity with Multi-Factor Authentication to access this area.'
: 'Your role requires Multi-Factor Authentication to access this area.'}
</p>
<Button
onClick={handleAction}
size="sm"
>
{needsVerification ? 'Verify Now' : 'Set up Multi-Factor Authentication'}
</Button>
</AlertDescription>
</Alert>
);
}

View File

@@ -4,7 +4,7 @@ import { FileText, Flag, AlertCircle, Activity, ShieldAlert } from 'lucide-react
import { useUserRole } from '@/hooks/useUserRole';
import { useAuth } from '@/hooks/useAuth';
import { useRequireMFA } from '@/hooks/useRequireMFA';
import { MFARequiredAlert } from '@/components/auth/MFARequiredAlert';
import { MFAGuard } from '@/components/auth/MFAGuard';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
@@ -159,15 +159,6 @@ export default function AdminDashboard() {
return null;
}
// MFA enforcement
if (needsEnrollment) {
return (
<AdminLayout>
<MFARequiredAlert />
</AdminLayout>
);
}
const statCards = [
{
label: 'Pending Submissions',
@@ -200,6 +191,7 @@ export default function AdminDashboard() {
lastUpdated={lastUpdated ?? undefined}
isRefreshing={isRefreshing}
>
<MFAGuard>
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">Admin Dashboard</h1>
@@ -307,6 +299,7 @@ export default function AdminDashboard() {
</TabsContent>
</Tabs>
</div>
</MFAGuard>
</AdminLayout>
);
}

View File

@@ -1,6 +1,6 @@
import { useRef, useCallback } from 'react';
import { useAdminGuard } from '@/hooks/useAdminGuard';
import { MFARequiredAlert } from '@/components/auth/MFARequiredAlert';
import { MFAGuard } from '@/components/auth/MFAGuard';
import { AdminLayout } from '@/components/layout/AdminLayout';
import { ModerationQueue, ModerationQueueRef } from '@/components/moderation/ModerationQueue';
import { QueueSkeleton } from '@/components/moderation/QueueSkeleton';
@@ -57,14 +57,6 @@ export default function AdminModeration() {
return null;
}
if (needsMFA) {
return (
<AdminLayout>
<MFARequiredAlert />
</AdminLayout>
);
}
return (
<AdminLayout
onRefresh={handleRefresh}
@@ -72,6 +64,7 @@ export default function AdminModeration() {
pollInterval={pollInterval}
lastUpdated={lastUpdated ?? undefined}
>
<MFAGuard>
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">Moderation Queue</h1>
@@ -82,6 +75,7 @@ export default function AdminModeration() {
<ModerationQueue ref={moderationQueueRef} />
</div>
</MFAGuard>
</AdminLayout>
);
}

View File

@@ -1,6 +1,6 @@
import { useRef, useCallback } from 'react';
import { useAdminGuard } from '@/hooks/useAdminGuard';
import { MFARequiredAlert } from '@/components/auth/MFARequiredAlert';
import { MFAGuard } from '@/components/auth/MFAGuard';
import { AdminLayout } from '@/components/layout/AdminLayout';
import { ReportsQueue, ReportsQueueRef } from '@/components/moderation/ReportsQueue';
import { QueueSkeleton } from '@/components/moderation/QueueSkeleton';
@@ -58,14 +58,6 @@ export default function AdminReports() {
return null;
}
if (needsMFA) {
return (
<AdminLayout>
<MFARequiredAlert />
</AdminLayout>
);
}
return (
<AdminLayout
onRefresh={handleRefresh}
@@ -73,6 +65,7 @@ export default function AdminReports() {
pollInterval={pollInterval}
lastUpdated={lastUpdated ?? undefined}
>
<MFAGuard>
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">User Reports</h1>
@@ -83,6 +76,7 @@ export default function AdminReports() {
<ReportsQueue ref={reportsQueueRef} />
</div>
</MFAGuard>
</AdminLayout>
);
}

View File

@@ -1,5 +1,5 @@
import { useAdminGuard } from '@/hooks/useAdminGuard';
import { MFARequiredAlert } from '@/components/auth/MFARequiredAlert';
import { MFAGuard } from '@/components/auth/MFAGuard';
import { AdminLayout } from '@/components/layout/AdminLayout';
import { UserManagement } from '@/components/admin/UserManagement';
import { Skeleton } from '@/components/ui/skeleton';
@@ -44,16 +44,9 @@ export default function AdminUsers() {
return null;
}
if (needsMFA) {
return (
<AdminLayout>
<MFARequiredAlert />
</AdminLayout>
);
}
return (
<AdminLayout>
<MFAGuard>
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">User Management</h1>
@@ -64,6 +57,7 @@ export default function AdminUsers() {
<UserManagement />
</div>
</MFAGuard>
</AdminLayout>
);
}