feat: add 2FA, secure cookies and publishing tools
All checks were successful
CI / Validate frontend and API (push) Successful in 3m5s
CI / Build and publish Docker images (push) Successful in 1m42s

This commit is contained in:
Cauê Faleiros
2026-11-06 10:29:37 -03:00
parent fff63f5efa
commit 50905eefd7
40 changed files with 3493 additions and 215 deletions

View File

@@ -2,8 +2,6 @@ import React from 'react';
import {
PlayCircleIcon as PlayCircle,
DownloadSimpleIcon as Download,
FileTextIcon as FileText,
CheckCircleIcon as CheckCircle2
} from '@phosphor-icons/react';
import { Course, SectionVariant } from '../types';
import { CourseCoverImage } from './CourseCoverImage';
@@ -20,7 +18,6 @@ export const CourseCard: React.FC<CourseCardProps> = ({
course,
variant,
onClick,
onOpenMaterials
}) => {
const navigate = useNavigate();
const widthClass = variant === 'landscape'

View File

@@ -3,7 +3,6 @@ import {
FileTextIcon as FileText,
FileXlsIcon as FileSpreadsheet,
FileArchiveIcon as FileArchive,
FileCodeIcon as FileCode,
ImageIcon as ImageIcon,
LinkIcon as LinkIcon,
DownloadSimpleIcon as Download,

View File

@@ -0,0 +1,282 @@
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>
);
};

View File

@@ -1,6 +1,5 @@
import React, { useEffect, useRef, useState } from 'react';
import { adminApi, HomeBanner } from '../../services/api';
import { instructorApi } from '../../services/api';
import { adminApi, HomeBanner, instructorApi } from '../../services/api';
import { useToast } from '../../context/ToastContext';
import { CourseCoverImage } from '../CourseCoverImage';
import { Select } from '../ui/Select';

View File

@@ -2,11 +2,15 @@ import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { Sidebar } from './Sidebar';
import { MobileBack, MobileTabBar } from './MobileNavigation';
import { useAuth } from '../../context/AuthContext';
import { useIsMobile } from '../../hooks/useMediaQuery';
import { paths } from '../../lib/routes';
export const AppShell: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const location = useLocation();
const isMobile = useIsMobile();
const { user, stopImpersonation } = useAuth();
const impersonating = Boolean(user?.impersonatedBy);
useEffect(() => {
window.scrollTo(0, 0);
@@ -16,6 +20,10 @@ export const AppShell: React.FC<{ children: React.ReactNode }> = ({ children })
return (
<>
{impersonating && <div className="impersonation-banner" role="status">
<span>Você está vendo a plataforma como <b>{user?.name}</b>.</span>
<button type="button" onClick={async () => { if (await stopImpersonation()) window.location.assign(paths.admin); }}>Sair da impersonação</button>
</div>}
{!isMobile && <Sidebar />}
{isMobile && <MobileBack />}
{/* Keyed by path: the arrival animation only plays when navigating to a new page. */}

View File

@@ -115,9 +115,9 @@ export const Sidebar: React.FC = () => {
return !value;
});
const signOut = () => {
const signOut = async () => {
setMenuOpen(false);
logout();
await logout();
navigate(paths.explore);
};