Refactor security functions

This commit is contained in:
gpt-engineer-app[bot]
2025-10-14 19:38:36 +00:00
parent 1554254c82
commit 95972a0b22
9 changed files with 638 additions and 89 deletions

View File

@@ -12,7 +12,8 @@ import {
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/use-toast';
import { handleError, handleSuccess, AppError } from '@/lib/errorHandler';
import { logger } from '@/lib/logger';
import { supabase } from '@/integrations/supabase/client';
import { Loader2, Shield, CheckCircle2 } from 'lucide-react';
import { InputOTP, InputOTPGroup, InputOTPSlot } from '@/components/ui/input-otp';
@@ -33,7 +34,6 @@ interface PasswordUpdateDialogProps {
type Step = 'password' | 'mfa' | 'success';
export function PasswordUpdateDialog({ open, onOpenChange, onSuccess }: PasswordUpdateDialogProps) {
const { toast } = useToast();
const { theme } = useTheme();
const [step, setStep] = useState<Step>('password');
const [loading, setLoading] = useState(false);
@@ -43,6 +43,7 @@ export function PasswordUpdateDialog({ open, onOpenChange, onSuccess }: Password
const [totpCode, setTotpCode] = useState('');
const [captchaToken, setCaptchaToken] = useState<string>('');
const [captchaKey, setCaptchaKey] = useState(0);
const [userId, setUserId] = useState<string>('');
const form = useForm<PasswordFormData>({
resolver: zodResolver(passwordSchema),
@@ -53,10 +54,13 @@ export function PasswordUpdateDialog({ open, onOpenChange, onSuccess }: Password
}
});
// Check if user has MFA enabled
// Check if user has MFA enabled and get user ID
useEffect(() => {
if (open) {
checkMFAStatus();
supabase.auth.getUser().then(({ data }) => {
if (data.user) setUserId(data.user.id);
});
}
}, [open]);
@@ -68,17 +72,23 @@ export function PasswordUpdateDialog({ open, onOpenChange, onSuccess }: Password
const hasVerifiedTotp = data?.totp?.some(factor => factor.status === 'verified') || false;
setHasMFA(hasVerifiedTotp);
} catch (error) {
console.error('Error checking MFA status:', error);
logger.error('Failed to check MFA status', {
action: 'check_mfa_status',
error: error instanceof Error ? error.message : String(error)
});
}
};
const onSubmit = async (data: PasswordFormData) => {
if (!captchaToken) {
toast({
title: 'CAPTCHA Required',
description: 'Please complete the CAPTCHA verification.',
variant: 'destructive'
});
handleError(
new AppError('Please complete the CAPTCHA verification.', 'CAPTCHA_REQUIRED'),
{
action: 'Change password',
userId,
metadata: { step: 'captcha_validation' }
}
);
return;
}
@@ -97,6 +107,14 @@ export function PasswordUpdateDialog({ open, onOpenChange, onSuccess }: Password
// Reset CAPTCHA on authentication failure
setCaptchaToken('');
setCaptchaKey(prev => prev + 1);
logger.error('Password authentication failed', {
userId,
action: 'password_change_auth',
error: signInError.message,
errorCode: signInError.code
});
throw signInError;
}
@@ -117,18 +135,37 @@ export function PasswordUpdateDialog({ open, onOpenChange, onSuccess }: Password
await updatePasswordWithNonce(data.newPassword, generatedNonce);
}
} catch (error: any) {
// Handle rate limiting specifically
logger.error('Password change failed', {
userId,
action: 'password_change',
error: error instanceof Error ? error.message : String(error),
errorCode: error.code,
errorStatus: error.status
});
if (error.message?.includes('rate limit') || error.status === 429) {
toast({
title: 'Too Many Attempts',
description: 'Please wait a few minutes before trying again.',
variant: 'destructive'
});
handleError(
new AppError(
'Please wait a few minutes before trying again.',
'RATE_LIMIT',
'Too many password change attempts'
),
{ action: 'Change password', userId, metadata: { step: 'authentication' } }
);
} else if (error.message?.includes('Invalid login credentials')) {
handleError(
new AppError(
'The password you entered is incorrect.',
'INVALID_PASSWORD',
'Incorrect current password'
),
{ action: 'Verify password', userId }
);
} else {
toast({
title: 'Authentication Error',
description: error.message || 'Incorrect password. Please try again.',
variant: 'destructive'
handleError(error, {
action: 'Change password',
userId,
metadata: { step: 'authentication' }
});
}
} finally {
@@ -138,11 +175,10 @@ export function PasswordUpdateDialog({ open, onOpenChange, onSuccess }: Password
const verifyMFAAndUpdate = async () => {
if (totpCode.length !== 6) {
toast({
title: 'Invalid Code',
description: 'Please enter a valid 6-digit code',
variant: 'destructive'
});
handleError(
new AppError('Please enter a valid 6-digit code', 'INVALID_MFA_CODE'),
{ action: 'Verify MFA', userId, metadata: { step: 'mfa_verification' } }
);
return;
}
@@ -153,7 +189,15 @@ export function PasswordUpdateDialog({ open, onOpenChange, onSuccess }: Password
factorId: (await supabase.auth.mfa.listFactors()).data?.totp?.[0]?.id || ''
});
if (challengeError) throw challengeError;
if (challengeError) {
logger.error('MFA challenge creation failed', {
userId,
action: 'password_change_mfa_challenge',
error: challengeError.message,
errorCode: challengeError.code
});
throw challengeError;
}
const { error: verifyError } = await supabase.auth.mfa.verify({
factorId: challengeData.id,
@@ -161,16 +205,33 @@ export function PasswordUpdateDialog({ open, onOpenChange, onSuccess }: Password
code: totpCode
});
if (verifyError) throw verifyError;
if (verifyError) {
logger.error('MFA verification failed', {
userId,
action: 'password_change_mfa',
error: verifyError.message,
errorCode: verifyError.code
});
throw verifyError;
}
// TOTP verified, now update password
await updatePasswordWithNonce(newPassword, nonce);
} catch (error: any) {
toast({
title: 'Verification Failed',
description: error.message || 'Invalid authentication code',
variant: 'destructive'
logger.error('MFA verification failed', {
userId,
action: 'password_change_mfa',
error: error instanceof Error ? error.message : String(error)
});
handleError(
new AppError(
error.message || 'Invalid authentication code',
'MFA_VERIFICATION_FAILED',
'TOTP code verification failed'
),
{ action: 'Verify MFA', userId, metadata: { step: 'mfa_verification' } }
);
} finally {
setLoading(false);
}
@@ -213,7 +274,11 @@ export function PasswordUpdateDialog({ open, onOpenChange, onSuccess }: Password
}
});
} catch (notifError) {
console.error('Failed to send notification:', notifError);
logger.error('Failed to send password change notification', {
userId: user!.id,
action: 'password_change_notification',
error: notifError instanceof Error ? notifError.message : String(notifError)
});
// Don't fail the password update if notification fails
}
}