283 lines
9.8 KiB
TypeScript
283 lines
9.8 KiB
TypeScript
import React, { useEffect, useState } from 'react';
|
|
import { CircleNotchIcon, ShieldCheckIcon } from '@phosphor-icons/react';
|
|
import { authApi, TwoFactorStatus } from '../../services/api';
|
|
import { useToast } from '../../context/ToastContext';
|
|
|
|
type SetupData = { secret: string; otpauthUrl: string; qrCode: string };
|
|
|
|
export const TwoFactorSettings: React.FC = () => {
|
|
const { showToast } = useToast();
|
|
const [status, setStatus] = useState<TwoFactorStatus | null>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
const [busy, setBusy] = useState(false);
|
|
const [setup, setSetup] = useState<SetupData | null>(null);
|
|
const [code, setCode] = useState('');
|
|
const [password, setPassword] = useState('');
|
|
const [mode, setMode] = useState<'idle' | 'regenerate' | 'disable'>('idle');
|
|
const [backupCodes, setBackupCodes] = useState<string[]>([]);
|
|
|
|
const load = async () => {
|
|
setLoading(true);
|
|
try {
|
|
const response = await authApi.twoFactorStatus();
|
|
setStatus(response.data);
|
|
} catch {
|
|
setStatus(null);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
void load();
|
|
}, []);
|
|
|
|
const startSetup = async () => {
|
|
setBusy(true);
|
|
try {
|
|
const response = await authApi.setupTwoFactor();
|
|
setSetup(response.data);
|
|
setCode('');
|
|
setBackupCodes([]);
|
|
} catch {
|
|
showToast('Não foi possível iniciar a configuração do 2FA.', 'error');
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
const enable = async (event: React.FormEvent) => {
|
|
event.preventDefault();
|
|
setBusy(true);
|
|
try {
|
|
const response = await authApi.enableTwoFactor(code.trim());
|
|
setBackupCodes(response.data.backupCodes);
|
|
setSetup(null);
|
|
setCode('');
|
|
await load();
|
|
showToast('Verificação em duas etapas ativada.', 'success');
|
|
} catch {
|
|
showToast('Código inválido. Confira o aplicativo autenticador.', 'error');
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
const regenerate = async (event: React.FormEvent) => {
|
|
event.preventDefault();
|
|
setBusy(true);
|
|
try {
|
|
const response = await authApi.regenerateBackupCodes(code.trim());
|
|
setBackupCodes(response.data.backupCodes);
|
|
setCode('');
|
|
setMode('idle');
|
|
await load();
|
|
showToast('Novos códigos de recuperação gerados.', 'success');
|
|
} catch {
|
|
showToast('Código inválido. Tente novamente.', 'error');
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
const disable = async (event: React.FormEvent) => {
|
|
event.preventDefault();
|
|
setBusy(true);
|
|
try {
|
|
await authApi.disableTwoFactor(code.trim(), password);
|
|
setCode('');
|
|
setPassword('');
|
|
setMode('idle');
|
|
setBackupCodes([]);
|
|
await load();
|
|
showToast('Verificação em duas etapas desativada.', 'success');
|
|
} catch {
|
|
showToast('Não foi possível desativar o 2FA. Verifique senha e código.', 'error');
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<section className="form twofa-section">
|
|
<h2>Segurança</h2>
|
|
<div className="box twofa-card">
|
|
<div className="twofa-head">
|
|
<span className="twofa-icon">
|
|
<ShieldCheckIcon className="ph" />
|
|
</span>
|
|
<div>
|
|
<h3>Verificação em duas etapas</h3>
|
|
<p className="small">Proteja sua conta de administrador com um código do autenticador.</p>
|
|
</div>
|
|
</div>
|
|
{loading ? (
|
|
<div className="loading">
|
|
<CircleNotchIcon className="ph spin" />
|
|
</div>
|
|
) : !status ? (
|
|
<p className="small bad-text">Não foi possível consultar o status do 2FA.</p>
|
|
) : status.enabled ? (
|
|
<>
|
|
<p className="formmsg ok">
|
|
2FA ativo · {status.backupCodesRemaining}{' '}
|
|
{status.backupCodesRemaining === 1 ? 'código de recuperação restante' : 'códigos de recuperação restantes'}
|
|
</p>
|
|
{mode === 'regenerate' ? (
|
|
<form className="twofa-form" onSubmit={regenerate}>
|
|
<div className="field">
|
|
<label htmlFor="twofa-regenerate-code">Código atual do autenticador</label>
|
|
<input
|
|
id="twofa-regenerate-code"
|
|
value={code}
|
|
onChange={(event) => setCode(event.target.value)}
|
|
autoComplete="one-time-code"
|
|
required
|
|
/>
|
|
</div>
|
|
<div className="review-actions">
|
|
<button className="btn" type="submit" disabled={busy}>
|
|
{busy ? 'Gerando…' : 'Gerar novos códigos'}
|
|
</button>
|
|
<button
|
|
className="link"
|
|
type="button"
|
|
onClick={() => {
|
|
setMode('idle');
|
|
setCode('');
|
|
}}
|
|
>
|
|
Cancelar
|
|
</button>
|
|
</div>
|
|
</form>
|
|
) : mode === 'disable' ? (
|
|
<form className="twofa-form" onSubmit={disable}>
|
|
<p className="small">Confirme sua senha e um código atual para desativar.</p>
|
|
<div className="field">
|
|
<label htmlFor="twofa-disable-code">Código do autenticador ou recuperação</label>
|
|
<input
|
|
id="twofa-disable-code"
|
|
value={code}
|
|
onChange={(event) => setCode(event.target.value)}
|
|
autoComplete="one-time-code"
|
|
required
|
|
/>
|
|
</div>
|
|
<div className="field">
|
|
<label htmlFor="twofa-disable-password">Senha atual</label>
|
|
<input
|
|
id="twofa-disable-password"
|
|
type="password"
|
|
value={password}
|
|
onChange={(event) => setPassword(event.target.value)}
|
|
autoComplete="current-password"
|
|
required
|
|
/>
|
|
</div>
|
|
<div className="review-actions">
|
|
<button className="btn sec bad-text" type="submit" disabled={busy}>
|
|
{busy ? 'Desativando…' : 'Desativar 2FA'}
|
|
</button>
|
|
<button
|
|
className="link"
|
|
type="button"
|
|
onClick={() => {
|
|
setMode('idle');
|
|
setCode('');
|
|
setPassword('');
|
|
}}
|
|
>
|
|
Cancelar
|
|
</button>
|
|
</div>
|
|
</form>
|
|
) : (
|
|
<div className="review-actions">
|
|
<button
|
|
className="btn sec"
|
|
type="button"
|
|
onClick={() => {
|
|
setMode('regenerate');
|
|
setCode('');
|
|
}}
|
|
>
|
|
Gerar novos códigos
|
|
</button>
|
|
<button
|
|
className="link bad-text"
|
|
type="button"
|
|
onClick={() => {
|
|
setMode('disable');
|
|
setCode('');
|
|
setPassword('');
|
|
}}
|
|
>
|
|
Desativar 2FA
|
|
</button>
|
|
</div>
|
|
)}
|
|
</>
|
|
) : setup ? (
|
|
<>
|
|
<p className="small">Escaneie o QR code com Google Authenticator, 1Password ou outro aplicativo TOTP.</p>
|
|
<div className="twofa-setup">
|
|
<img src={setup.qrCode} alt="QR code para configurar a verificação em duas etapas" width={220} height={220} />
|
|
<div>
|
|
<p className="small">Se preferir, digite esta chave manualmente:</p>
|
|
<code className="twofa-secret">{setup.secret}</code>
|
|
<form className="twofa-form" onSubmit={enable}>
|
|
<div className="field">
|
|
<label htmlFor="twofa-enable-code">Código de 6 dígitos</label>
|
|
<input
|
|
id="twofa-enable-code"
|
|
value={code}
|
|
onChange={(event) => setCode(event.target.value)}
|
|
autoComplete="one-time-code"
|
|
autoFocus
|
|
required
|
|
/>
|
|
</div>
|
|
<div className="review-actions">
|
|
<button className="btn" type="submit" disabled={busy}>
|
|
{busy ? 'Ativando…' : 'Ativar 2FA'}
|
|
</button>
|
|
<button
|
|
className="link"
|
|
type="button"
|
|
onClick={() => {
|
|
setSetup(null);
|
|
setCode('');
|
|
}}
|
|
>
|
|
Cancelar
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
</>
|
|
) : (
|
|
<button className="btn" type="button" onClick={() => void startSetup()} disabled={busy}>
|
|
{busy ? 'Preparando…' : 'Configurar 2FA'}
|
|
</button>
|
|
)}
|
|
</div>
|
|
{backupCodes.length > 0 && (
|
|
<div className="box twofa-codes">
|
|
<h3>Guarde seus códigos de recuperação</h3>
|
|
<p className="small">Cada código funciona uma vez. Eles não serão exibidos novamente.</p>
|
|
<div className="twofa-code-grid">
|
|
{backupCodes.map((backupCode) => (
|
|
<code key={backupCode}>{backupCode}</code>
|
|
))}
|
|
</div>
|
|
<button className="btn sec" type="button" onClick={() => setBackupCodes([])}>
|
|
Já salvei os códigos
|
|
</button>
|
|
</div>
|
|
)}
|
|
</section>
|
|
);
|
|
};
|