mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-23 19:11:12 -05:00
feat: Implement TOTP and update settings page
This commit is contained in:
328
src/components/auth/TOTPSetup.tsx
Normal file
328
src/components/auth/TOTPSetup.tsx
Normal file
@@ -0,0 +1,328 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { useToast } from '@/hooks/use-toast';
|
||||
import { useAuth } from '@/hooks/useAuth';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { Smartphone, Shield, Copy, Eye, EyeOff, Trash2, AlertCircle } from 'lucide-react';
|
||||
|
||||
interface TOTPFactor {
|
||||
id: string;
|
||||
friendly_name?: string;
|
||||
factor_type: string;
|
||||
status: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export function TOTPSetup() {
|
||||
const { user } = useAuth();
|
||||
const { toast } = useToast();
|
||||
const [factors, setFactors] = useState<TOTPFactor[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [enrolling, setEnrolling] = useState(false);
|
||||
const [qrCode, setQrCode] = useState('');
|
||||
const [secret, setSecret] = useState('');
|
||||
const [factorId, setFactorId] = useState('');
|
||||
const [verificationCode, setVerificationCode] = useState('');
|
||||
const [showSecret, setShowSecret] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetchTOTPFactors();
|
||||
}, [user]);
|
||||
|
||||
const fetchTOTPFactors = async () => {
|
||||
if (!user) return;
|
||||
|
||||
try {
|
||||
const { data, error } = await supabase.auth.mfa.listFactors();
|
||||
if (error) throw error;
|
||||
|
||||
const totpFactors = (data.totp || []).map(factor => ({
|
||||
id: factor.id,
|
||||
friendly_name: factor.friendly_name || 'Authenticator App',
|
||||
factor_type: factor.factor_type || 'totp',
|
||||
status: factor.status,
|
||||
created_at: factor.created_at
|
||||
}));
|
||||
setFactors(totpFactors);
|
||||
} catch (error: any) {
|
||||
console.error('Error fetching TOTP factors:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const startEnrollment = async () => {
|
||||
if (!user) return;
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const { data, error } = await supabase.auth.mfa.enroll({
|
||||
factorType: 'totp',
|
||||
friendlyName: 'Authenticator App'
|
||||
});
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
setQrCode(data.totp.qr_code);
|
||||
setSecret(data.totp.secret);
|
||||
setFactorId(data.id);
|
||||
setEnrolling(true);
|
||||
} catch (error: any) {
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: error.message || 'Failed to start TOTP enrollment',
|
||||
variant: 'destructive'
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const verifyAndEnable = async () => {
|
||||
if (!factorId || !verificationCode.trim()) {
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: 'Please enter the verification code',
|
||||
variant: 'destructive'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const { error } = await supabase.auth.mfa.verify({
|
||||
factorId,
|
||||
challengeId: factorId, // For enrollment, challengeId is the same as factorId
|
||||
code: verificationCode.trim()
|
||||
});
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
toast({
|
||||
title: 'TOTP Enabled',
|
||||
description: 'Two-factor authentication has been successfully enabled for your account.'
|
||||
});
|
||||
|
||||
// Reset state and refresh factors
|
||||
setEnrolling(false);
|
||||
setQrCode('');
|
||||
setSecret('');
|
||||
setFactorId('');
|
||||
setVerificationCode('');
|
||||
fetchTOTPFactors();
|
||||
} catch (error: any) {
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: error.message || 'Invalid verification code. Please try again.',
|
||||
variant: 'destructive'
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const unenrollFactor = async (factorId: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const { error } = await supabase.auth.mfa.unenroll({
|
||||
factorId
|
||||
});
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
toast({
|
||||
title: 'TOTP Disabled',
|
||||
description: 'Two-factor authentication has been disabled for your account.'
|
||||
});
|
||||
|
||||
fetchTOTPFactors();
|
||||
} catch (error: any) {
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: error.message || 'Failed to disable TOTP',
|
||||
variant: 'destructive'
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const copySecret = () => {
|
||||
navigator.clipboard.writeText(secret);
|
||||
toast({
|
||||
title: 'Copied',
|
||||
description: 'Secret key copied to clipboard'
|
||||
});
|
||||
};
|
||||
|
||||
const cancelEnrollment = () => {
|
||||
setEnrolling(false);
|
||||
setQrCode('');
|
||||
setSecret('');
|
||||
setFactorId('');
|
||||
setVerificationCode('');
|
||||
};
|
||||
|
||||
const activeFactor = factors.find(f => f.status === 'verified');
|
||||
|
||||
if (enrolling) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Smartphone className="w-5 h-5" />
|
||||
Set Up Authenticator App
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Scan the QR code with your authenticator app, then enter the verification code below.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* QR Code */}
|
||||
<div className="flex justify-center">
|
||||
<div className="p-4 bg-white rounded-lg border">
|
||||
<img src={qrCode} alt="TOTP QR Code" className="w-48 h-48" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Manual Entry */}
|
||||
<div className="space-y-2">
|
||||
<Label>Can't scan? Enter this key manually:</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
value={secret}
|
||||
readOnly
|
||||
type={showSecret ? 'text' : 'password'}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setShowSecret(!showSecret)}
|
||||
>
|
||||
{showSecret ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={copySecret}>
|
||||
<Copy className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Verification */}
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="verificationCode">Enter verification code from your app:</Label>
|
||||
<Input
|
||||
id="verificationCode"
|
||||
value={verificationCode}
|
||||
onChange={(e) => setVerificationCode(e.target.value)}
|
||||
placeholder="000000"
|
||||
maxLength={6}
|
||||
className="text-center text-lg tracking-widest font-mono"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button variant="outline" onClick={cancelEnrollment}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={verifyAndEnable} disabled={loading || !verificationCode.trim()}>
|
||||
{loading ? 'Verifying...' : 'Enable TOTP'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardDescription>
|
||||
Add an extra layer of security to your account with two-factor authentication.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{activeFactor ? (
|
||||
<div className="space-y-4">
|
||||
<Alert>
|
||||
<Shield className="w-4 h-4" />
|
||||
<AlertDescription>
|
||||
Two-factor authentication is enabled for your account. You'll be prompted for a verification code when signing in.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<div className="flex items-center justify-between p-4 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-green-50 dark:bg-green-950 rounded-full flex items-center justify-center">
|
||||
<Smartphone className="w-4 h-4 text-green-600 dark:text-green-400" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{activeFactor.friendly_name || 'Authenticator App'}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Enabled {new Date(activeFactor.created_at).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="bg-green-50 dark:bg-green-950 text-green-700 dark:text-green-300">
|
||||
Active
|
||||
</Badge>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="outline" size="sm">
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Disable
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2">
|
||||
<AlertCircle className="w-5 h-5 text-destructive" />
|
||||
Disable Two-Factor Authentication
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to disable two-factor authentication? This will make your account less secure.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => unenrollFactor(activeFactor.id)}
|
||||
className="bg-destructive hover:bg-destructive/90"
|
||||
>
|
||||
Disable TOTP
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-between p-4 border rounded-lg">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-muted rounded-full flex items-center justify-center">
|
||||
<Smartphone className="w-4 h-4 text-muted-foreground" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Authenticator App</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Use an authenticator app to generate verification codes
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<Button onClick={startEnrollment} disabled={loading}>
|
||||
{loading ? 'Setting up...' : 'Set Up'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user