Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 | 192x 192x 192x 192x 192x 192x 192x 192x 192x 192x 192x 192x 192x 192x 192x 192x 192x 45x 1x 1x 45x 192x 41x 41x 41x 41x 41x 4x 4x 37x 14x 14x 14x 11x 10x 10x 10x 10x 1x 3x 1x 2x 14x 23x 23x 23x 23x 23x 192x 38x 38x 3x 3x 35x 7x 2x 2x 28x 19x 4x 4x 29x 29x 29x 9x 9x 9x 5x 3x 2x 2x 2x 2x 2x 1x 3x 15x 5x 3x 3x 3x 3x 3x 2x 5x 12x 10x 10x 6x 4x 2x 29x 192x 3x 3x 3x 3x 3x 3x 3x 1x 3x 192x 1x 6x 5x 2x 8x 18x | import Accordion from "@mui/material/Accordion"; import AccordionSummary from "@mui/material/AccordionSummary"; import Box from "@mui/material/Box"; import { useState, type JSX } from "react"; import { useTranslation } from "react-i18next"; import ExpandMoreIcon from '@mui/icons-material/ExpandMore'; import Typography from "@mui/material/Typography"; import FormControlLabel from "@mui/material/FormControlLabel"; import Switch from "@mui/material/Switch"; import AccordionDetails from "@mui/material/AccordionDetails"; import Dialog from "@mui/material/Dialog"; import DialogTitle from "@mui/material/DialogTitle"; import DialogContent from "@mui/material/DialogContent"; import TextField from "@mui/material/TextField"; import DialogActions from "@mui/material/DialogActions"; import Button from "@mui/material/Button"; import CircularProgress from "@mui/material/CircularProgress"; import { enableTwoFA, confirmTwoFA, disableTwoFA } from "../../services/userService"; import { useAuthStore } from "../../stores/useAuthStore"; import { useNavigate } from "react-router-dom"; import { getErrorMessage } from "../../utils/errorUtils"; import axios from "axios"; import { QRCodeSVG } from 'qrcode.react'; import useMediaQuery from "@mui/material/useMediaQuery"; interface TwoFASectionProps { enabled: boolean; onToggle: (enabled: boolean) => void; } export function TwoFASection({ enabled, onToggle }: TwoFASectionProps): JSX.Element { const { t } = useTranslation('userDashboard'); const token = useAuthStore((state) => state.authToken); const navigate = useNavigate(); const isMobile = useMediaQuery((theme) => theme.breakpoints.down('sm')); const [expanded, setExpanded] = useState<boolean>(false); const [loading, setLoading] = useState<boolean>(false); const [errorMsg, setErrorMsg] = useState<string | null>(null); const [successMsg, setSuccessMsg] = useState<string | null>(null); // Dialog générique pour enable ou disable ou confirm const [dialogOpen, setDialogOpen] = useState<boolean>(false); const [dialogMode, setDialogMode] = useState<"enable_prepare"|"enable_confirm"|"disable"|"enable_success">("enable_prepare"); // Pour activation : données de préparation const [qrCodeUrl, setQrCodeUrl] = useState<string | null>(null); const [secret, setSecret] = useState<string | null>(null); // Pour saisie OTP lors de confirm activation ou disable const [otpCode, setOtpCode] = useState<string>(''); const [dialogErrorMsg, setDialogErrorMsg] = useState<string | null>(null); // Pour afficher recovery codes après confirmation const [recoveryCodes, setRecoveryCodes] = useState<string[] | null>(null); // Pour gérer la désactivation avec un OTP ou un code de récupération const [codeType, setCodeType] = useState<"otp"|"recovery">("otp"); const handleAccordionChange = () => { if (expanded) { setErrorMsg(null); setSuccessMsg(null); } setExpanded(prev => !prev); }; const handleToggleClick = async () => { setErrorMsg(null); setSuccessMsg(null); setDialogErrorMsg(null); setRecoveryCodes(null); if (!token) { navigate('/login', { replace: true }); return; } if (!enabled) { // Début de l'activation : étape 1 = préparation setLoading(true); try { const resp = await enableTwoFA(token); // suppose status 200 et data { qrCodeUrl, secret, expires_at } if (resp.status === 200 && resp.data.qrCodeUrl) { // On ouvre le dialog en mode prepare setQrCodeUrl(resp.data.qrCodeUrl); setSecret(resp.data.secret || null); setDialogMode("enable_prepare"); setDialogOpen(true); } else { setErrorMsg(getErrorMessage(t, 'generic_error')); } } catch (err: any) { if (axios.isAxiosError(err) && err.response?.data?.code) { setErrorMsg(getErrorMessage(t, err.response.data.code)); } else { setErrorMsg(getErrorMessage(t, 'network_error')); } } finally { setLoading(false); } } else { // Désactivation : ouvrir dialog en mode disable setDialogMode("disable"); setCodeType("otp"); setOtpCode(''); setDialogErrorMsg(null); setDialogOpen(true); } }; const handleConfirm = async () => { setDialogErrorMsg(null); if (!token) { navigate('/login', { replace: true }); return; } // Validation locale : OTP requis if (dialogMode === "enable_confirm") { if (!otpCode) { setDialogErrorMsg(t('errors.otpRequired')); return; } } else if (dialogMode === "disable") { // Selon codeType, on exige otpCode non vide if (!otpCode) { setDialogErrorMsg( codeType === "otp" ? t('errors.otpRequired') : t('errors.recoveryCodeRequired') ); return; } } setLoading(true); try { switch (dialogMode) { case "enable_prepare": // Après avoir affiché QR+secret, on passe à la saisie OTP setDialogMode("enable_confirm"); setOtpCode(''); break; case "enable_confirm": { // Appel confirm const resp = await confirmTwoFA(token, otpCode); if (resp.status === 200 && resp.data?.recovery_codes) { // Activation réussie onToggle(true); setSuccessMsg(t('dashboard.2faEnabled')); setRecoveryCodes(resp.data.recovery_codes); // on peut fermer le dialog ou afficher recovery codes dedans // Ici on garde le dialog ouvert et on affiche la liste setDialogErrorMsg(null); setDialogMode("enable_success"); } else { setErrorMsg(getErrorMessage(t, 'generic_error')); } } break; case "disable": { const resp = await disableTwoFA(token, otpCode); if (resp.status === 204) { // Désactivation réussie onToggle(false); setSuccessMsg(t('dashboard.2faDisabled')); setDialogOpen(false); setOtpCode(''); setExpanded(false); } else { // Réponse inattendue setErrorMsg(getErrorMessage(t, 'generic_error')); } } break; } } catch (err: any) { // Gestion des erreurs réseau ou backend if (axios.isAxiosError(err) && err.response?.data?.code) { const errCode = err.response.data.code; // Pour disable, si invalid code, on peut différencier le message selon codeType if (dialogMode === "disable" && errCode === 'twofa_invalid_code') { setDialogErrorMsg( codeType === "otp" ? t('errors.invalidOtp') : t('errors.invalidRecoveryCode') ); } else { setDialogErrorMsg(getErrorMessage(t, errCode)); } } else { setDialogErrorMsg(getErrorMessage(t, 'network_error')); } } finally { setLoading(false); } }; const handleDialogClose = () => { setDialogOpen(false); setOtpCode(''); setDialogErrorMsg(null); setQrCodeUrl(null); setSecret(null); setRecoveryCodes(null); // Si on fermet en plein flow d'activation, on désactive le switch car non confirmé if (dialogMode === "enable_prepare" || dialogMode === "enable_confirm") { onToggle(false); } setDialogMode("enable_prepare"); }; return ( <> <Accordion expanded={expanded} onChange={handleAccordionChange}> <AccordionSummary expandIcon={<ExpandMoreIcon />}> <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', gap: { xs: 1, sm: 0 } }}> <Typography sx={{ fontSize: { xs: '0.85rem', sm: '1.2rem' } }}> {t('dashboard.twoFA')} </Typography> {isMobile ? ( <Switch size="small" checked={enabled} onChange={handleToggleClick} disabled={loading} /> ) : ( <FormControlLabel control={<Switch size="small" checked={enabled} onChange={handleToggleClick} disabled={loading} />} label={enabled ? t('dashboard.enabled') : t('dashboard.disabled')} /> )} </Box> </AccordionSummary> <AccordionDetails> {errorMsg && <Typography color="error">{errorMsg}</Typography>} {successMsg && <Typography color="success.main">{successMsg}</Typography>} <Typography variant="body2"> {enabled ? t('dashboard.2faEnabled') : t('dashboard.2faDisabled')} </Typography> </AccordionDetails> </Accordion> <Dialog open={dialogOpen} onClose={handleDialogClose}> <DialogTitle> {dialogMode === "disable" && t('dashboard.disable2faTitle')} {dialogMode === "enable_prepare" && t('dashboard.enable2faTitle')} {dialogMode === "enable_confirm" && t('dashboard.confirm2faTitle')} </DialogTitle> <DialogContent> {/* Activation : étape préparation */} {dialogMode === "enable_prepare" && qrCodeUrl && ( <Box sx={{ textAlign: 'center', mb: 2 }}> <Typography variant="body2" gutterBottom> {t('dashboard.scanQRCodeWithoutConfirm')} </Typography> <Box sx={{ mx: 'auto', width: 200, height: 200, backgroundColor: '#fff', p: 1 }}> <QRCodeSVG value={qrCodeUrl} size={180} /> </Box> {secret && ( <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center', mt: 1 }}> <Typography variant="caption" sx={{ fontFamily: 'monospace', mr: 1 }}> {t('dashboard.secret')}: {secret} </Typography> <Button size="small" onClick={() => { navigator.clipboard.writeText(secret); }}> {t('dashboard.copy')} </Button> </Box> )} <Typography variant="body2" sx={{ mt: 2 }}> {t('dashboard.enterOtpAfterScan')} </Typography> </Box> )} {/* Activation : étape confirmation OTP */} {dialogMode === "enable_confirm" && ( <Box> <Typography variant="body2" gutterBottom> {t('dashboard.enterCodeToConfirm')} </Typography> <TextField label={isMobile ? t('dashboard.otpCodeMobile') : t('dashboard.otpCode')} value={otpCode} onChange={(e) => setOtpCode(e.target.value.trim())} fullWidth type="text" margin="normal" slotProps={{ input: { inputProps: { maxLength: 6, } } }} placeholder="123456" /> {dialogErrorMsg && <Typography color="error" sx={{ mt: 1 }}>{dialogErrorMsg}</Typography>} </Box> )} {/* Si activation réussie, affiche recovery codes */} {dialogMode === "enable_success" && recoveryCodes && ( <Box> <Typography variant="subtitle2" gutterBottom> {t('dashboard.recoveryCodesTitle')} </Typography> {recoveryCodes.map(code => ( <Typography key={code} variant="body2" sx={{ fontFamily: 'monospace' }}> {code} </Typography> ))} <Typography variant="caption" sx={{ display: 'block', mt: 1 }}> {t('dashboard.recoveryCodesNote')} </Typography> </Box> )} {/* Désactivation */} {dialogMode === "disable" && ( <Box> {/* Instruction change selon type */} <Typography variant="body2" gutterBottom> {codeType === "otp" ? t('dashboard.enterCodeToDisable') : t('dashboard.enterRecoveryCodeToDisable')} </Typography> {/* Boutons pour choisir le type de code */} <Box sx={{ display: 'flex', gap: 1, mb: 1 }}> <Button variant={codeType === "otp" ? "contained" : "outlined"} onClick={() => { setCodeType("otp"); setOtpCode(''); setDialogErrorMsg(null); }} disabled={loading} size="small" sx={{fontSize: {xs: '0.6rem', sm: '0.875rem'} }} > {t('dashboard.useOtp')} </Button> <Button variant={codeType === "recovery" ? "contained" : "outlined"} onClick={() => { setCodeType("recovery"); setOtpCode(''); setDialogErrorMsg(null); }} disabled={loading} size="small" sx={{fontSize: {xs: '0.6rem', sm: '0.875rem'} }} > {t('dashboard.useRecoveryCode')} </Button> </Box> {/* Champ de saisie, label et placeholder selon type */} <TextField label={ isMobile ? (codeType === "otp" ? t('dashboard.otpCodeMobile') : t('dashboard.recoveryCodeMobile')) : (codeType === "otp" ? t('dashboard.otpCode') : t('dashboard.recoveryCode')) } value={otpCode} onChange={(e) => setOtpCode(e.target.value.trim())} fullWidth type="text" margin="normal" slotProps={{ input: { inputProps: { maxLength: codeType === "otp" ? 6 : 20, }, } }} placeholder={codeType === "otp" ? "123456" : "ABCDEFGHIJ"} /> {dialogErrorMsg && <Typography color="error" sx={{ mt: 1 }}>{dialogErrorMsg}</Typography>} </Box> )} </DialogContent> <DialogActions> <Button onClick={handleDialogClose} disabled={loading}> {t('dashboard.cancel')} </Button> {dialogMode === "enable_prepare" && ( <Button variant="contained" onClick={handleConfirm} disabled={loading} startIcon={loading ? <CircularProgress size={16} /> : null} > {t('dashboard.next')} </Button> )} {(dialogMode === "enable_confirm" || dialogMode === "disable") && ( <Button variant="contained" onClick={handleConfirm} disabled={loading || !otpCode} startIcon={loading ? <CircularProgress size={16} /> : null} > {t('dashboard.confirm')} </Button> )} {dialogMode === "enable_success" && ( <Button variant="contained" onClick={handleDialogClose}> {t('dashboard.done')} </Button> )} </DialogActions> </Dialog> </> ); } |