games_app/prediqo_web/src/features/profile/components/TwoFactorPanel.tsx
2026-07-07 15:03:17 +02:00

258 lines
8.9 KiB
TypeScript

/**
* Two-factor authentication setup panel for the profile security section.
*/
import {
Alert,
Box,
Button,
CircularProgress,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Stack,
TextField,
Typography,
} from '@mui/material';
import { useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import { api } from '../../../shared/services/api';
import type { TotpSetupResponse } from '../types';
type TwoFactorPanelProps = {
totpEnabled: boolean;
onSuccess: (message: string) => void;
onError: (message: string) => void;
};
export function TwoFactorPanel({ totpEnabled, onSuccess, onError }: TwoFactorPanelProps) {
const { t } = useTranslation();
const qc = useQueryClient();
const [setupData, setSetupData] = useState<TotpSetupResponse | null>(null);
const [loadingSetup, setLoadingSetup] = useState(false);
const [code, setCode] = useState('');
const [enabling, setEnabling] = useState(false);
const [recoveryCodes, setRecoveryCodes] = useState<string[] | null>(null);
const [disableOpen, setDisableOpen] = useState(false);
const [disablePassword, setDisablePassword] = useState('');
const [disableCode, setDisableCode] = useState('');
const [disabling, setDisabling] = useState(false);
const [regenCode, setRegenCode] = useState('');
const [regenerating, setRegenerating] = useState(false);
const startSetup = async () => {
setLoadingSetup(true);
setSetupData(null);
try {
const res = await api.post<TotpSetupResponse>('/api/v1/2fa/setup');
setSetupData(res.data);
} catch (e: unknown) {
const err = e as { response?: { data?: { error?: string } }; message?: string };
onError(err?.response?.data?.error ?? err?.message ?? t('profileTwoFactor.setupFailed'));
} finally {
setLoadingSetup(false);
}
};
const enable = async () => {
if (code.trim().length !== 6) {
onError(t('profileTwoFactor.enterCode'));
return;
}
setEnabling(true);
try {
const res = await api.post<{ recoveryCodes: string[] }>('/api/v1/2fa/enable', {
code: code.trim(),
});
setSetupData(null);
setCode('');
setRecoveryCodes(res.data.recoveryCodes ?? []);
await qc.invalidateQueries({ queryKey: ['user-profile'] });
onSuccess(t('profileTwoFactor.enabledSuccess'));
} catch (e: unknown) {
const err = e as { response?: { data?: { error?: string } }; message?: string };
onError(
err?.response?.data?.error ?? err?.message ?? t('profileTwoFactor.invalidCode')
);
} finally {
setEnabling(false);
}
};
const disable2fa = async () => {
if (!disablePassword || !disableCode.trim()) {
onError(t('profileTwoFactor.disableMissing'));
return;
}
setDisabling(true);
try {
await api.post('/api/v1/2fa/disable', {
password: disablePassword,
code: disableCode.trim(),
});
setDisableOpen(false);
setDisablePassword('');
setDisableCode('');
setRecoveryCodes(null);
await qc.invalidateQueries({ queryKey: ['user-profile'] });
onSuccess(t('profileTwoFactor.disabledSuccess'));
} catch (e: unknown) {
const err = e as { response?: { data?: { error?: string } }; message?: string };
onError(err?.response?.data?.error ?? err?.message ?? t('profileTwoFactor.disableFailed'));
} finally {
setDisabling(false);
}
};
const regenerateCodes = async () => {
if (regenCode.trim().length !== 6) {
onError(t('profileTwoFactor.enterCode'));
return;
}
setRegenerating(true);
try {
const res = await api.post<{ recoveryCodes: string[] }>('/api/v1/2fa/recovery/regenerate', {
code: regenCode.trim(),
});
setRegenCode('');
setRecoveryCodes(res.data.recoveryCodes ?? []);
onSuccess(t('profileTwoFactor.recoveryRegenerated'));
} catch (e: unknown) {
const err = e as { response?: { data?: { error?: string } }; message?: string };
onError(err?.response?.data?.error ?? err?.message ?? t('profileTwoFactor.regenFailed'));
} finally {
setRegenerating(false);
}
};
if (totpEnabled) {
return (
<Stack spacing={2}>
<Alert severity="success" sx={{ borderRadius: 2 }}>
<Trans i18nKey="profileTwoFactor.enabled" components={{ b: <b /> }} />
</Alert>
{recoveryCodes && recoveryCodes.length > 0 && (
<Alert severity="warning" sx={{ borderRadius: 2 }}>
<Typography variant="subtitle2" sx={{ fontWeight: 800, mb: 1 }}>
{t('profileTwoFactor.recoveryTitle')}
</Typography>
<Typography variant="body2" sx={{ mb: 1 }}>
{t('profileTwoFactor.recoveryHint')}
</Typography>
<Box
component="ul"
sx={{ m: 0, pl: 2.5, fontFamily: 'monospace', fontSize: '0.9rem' }}
>
{recoveryCodes.map((c) => (
<li key={c}>{c}</li>
))}
</Box>
</Alert>
)}
<Stack direction={{ xs: 'column', sm: 'row' }} spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>
<TextField
size="small"
label={t('profileTwoFactor.verificationCode')}
value={regenCode}
onChange={(e) => setRegenCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
inputMode="numeric"
sx={{ minWidth: 160 }}
/>
<Button variant="outlined" onClick={regenerateCodes} disabled={regenerating}>
{regenerating ? t('profileTwoFactor.regenerating') : t('profileTwoFactor.regenerateCodes')}
</Button>
<Button color="error" variant="outlined" onClick={() => setDisableOpen(true)}>
{t('profileTwoFactor.disable')}
</Button>
</Stack>
<Dialog open={disableOpen} onClose={() => setDisableOpen(false)} maxWidth="xs" fullWidth>
<DialogTitle>{t('profileTwoFactor.disableTitle')}</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ mt: 1 }}>
<TextField
type="password"
label={t('profilePassword.current')}
fullWidth
value={disablePassword}
onChange={(e) => setDisablePassword(e.target.value)}
/>
<TextField
label={t('profileTwoFactor.codeOrRecovery')}
fullWidth
value={disableCode}
onChange={(e) => setDisableCode(e.target.value)}
/>
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={() => setDisableOpen(false)}>{t('common.cancel')}</Button>
<Button color="error" variant="contained" onClick={disable2fa} disabled={disabling}>
{disabling ? t('profileTwoFactor.disabling') : t('profileTwoFactor.confirmDisable')}
</Button>
</DialogActions>
</Dialog>
</Stack>
);
}
return (
<Stack spacing={2}>
<Typography variant="body2" sx={{ opacity: 0.75 }}>
{t('profileTwoFactor.setupHint')}
</Typography>
{!setupData ? (
<Button variant="outlined" onClick={startSetup} disabled={loadingSetup}>
{loadingSetup ? <CircularProgress size={22} /> : t('profileTwoFactor.setupButton')}
</Button>
) : (
<Stack spacing={2} sx={{ alignItems: 'center' }}>
<Typography variant="subtitle2" sx={{ alignSelf: 'flex-start' }}>
{t('profileTwoFactor.scanQr')}
</Typography>
<Box
component="img"
src={setupData.qrCodeUrl}
alt={t('profileTwoFactor.qrAlt')}
sx={{
width: 200,
height: 200,
borderRadius: 2,
bgcolor: '#fff',
p: 1,
border: '1px solid rgba(255,255,255,0.12)',
}}
/>
<Typography
variant="caption"
sx={{
fontFamily: 'monospace',
opacity: 0.7,
wordBreak: 'break-all',
textAlign: 'center',
}}
>
{t('profileTwoFactor.manualKey', { secret: setupData.secret })}
</Typography>
<TextField
label={t('profileTwoFactor.verificationCode')}
fullWidth
value={code}
onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
inputMode="numeric"
placeholder="000000"
/>
<Stack direction="row" spacing={1}>
<Button onClick={() => setSetupData(null)}>{t('common.cancel')}</Button>
<Button variant="contained" onClick={enable} disabled={enabling}>
{enabling ? t('profileTwoFactor.enabling') : t('profileTwoFactor.enable')}
</Button>
</Stack>
</Stack>
)}
</Stack>
);
}