Files
compor-academy/pages/AuthPage.tsx
Cauê Faleiros 50905eefd7
All checks were successful
CI / Validate frontend and API (push) Successful in 3m5s
CI / Build and publish Docker images (push) Successful in 1m42s
feat: add 2FA, secure cookies and publishing tools
2026-11-06 10:29:37 -03:00

130 lines
5.7 KiB
TypeScript

import React, { useState } from 'react';
import { Link, Navigate, useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { UserRole } from '../types';
import { paths } from '../lib/routes';
export const homeFor = (role: UserRole) => (role === 'superadmin' ? paths.admin : role === 'professor' ? paths.manage : paths.explore);
interface AuthPageProps {
mode: 'signin' | 'signup';
}
export const AuthPage: React.FC<AuthPageProps> = ({ mode }) => {
const isRegistering = mode === 'signup';
const { user, login, verifyTwoFactor, register } = useAuth();
const navigate = useNavigate();
const location = useLocation();
const lead = (location.state as { message?: string } | null)?.message;
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [name, setName] = useState('');
const [error, setError] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [challengeToken, setChallengeToken] = useState('');
const [twoFactorCode, setTwoFactorCode] = useState('');
const isTwoFactor = Boolean(challengeToken);
if (user && !isSubmitting) return <Navigate to={homeFor(user.role)} replace />;
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
setError('');
if (!email.trim() || !/^\S+@\S+\.\S+$/.test(email)) {
setError('Informe um e-mail válido.');
return;
}
if (isRegistering && name.trim().length < 2) {
setError('Informe seu nome.');
return;
}
if (password.length < 8) {
setError('A senha deve ter pelo menos 8 caracteres.');
return;
}
setIsSubmitting(true);
const response = isRegistering ? await register(name, email, password) : await login(email, password);
if (!response) {
setIsSubmitting(false);
setError(isRegistering
? 'Não foi possível criar sua conta. Use um e-mail válido e uma senha com pelo menos 8 caracteres.'
: 'Credenciais inválidas. Verifique seu e-mail e senha.');
return;
}
if ('twoFactorRequired' in response) {
setChallengeToken(response.challengeToken);
setTwoFactorCode('');
setError('');
setIsSubmitting(false);
return;
}
const signedInUser = 'user' in response ? response.user : response;
navigate(homeFor(signedInUser.role), { replace: true });
};
const handleTwoFactor = async (event: React.FormEvent) => {
event.preventDefault();
setError('');
if (twoFactorCode.trim().length < 6) { setError('Informe o código de verificação.'); return; }
setIsSubmitting(true);
const verified = await verifyTwoFactor(challengeToken, twoFactorCode.trim());
setIsSubmitting(false);
if (!verified) {
setError('Código inválido ou expirado. Tente novamente.');
return;
}
navigate(homeFor(verified.role), { replace: true });
};
const backToCredentials = () => {
setChallengeToken('');
setTwoFactorCode('');
setError('');
};
return (
<main className="wrap page auth-page enter">
<div className="auth">
{isTwoFactor ? <>
<h1>Verificação em duas etapas</h1>
<p>Digite o código do seu autenticador ou um código de recuperação.</p>
<form noValidate onSubmit={handleTwoFactor}>
<div className="field">
<label htmlFor="auth-2fa">Código de verificação</label>
<input id="auth-2fa" value={twoFactorCode} onChange={(event) => setTwoFactorCode(event.target.value)} autoComplete="one-time-code" autoFocus required />
</div>
{error && <p className="formmsg bad" role="alert">{error}</p>}
<button className="btn" type="submit" disabled={isSubmitting}>{isSubmitting ? 'Verificando…' : 'Verificar'}</button>
</form>
<p className="alt"><button className="link" type="button" onClick={backToCredentials}>Voltar</button></p>
</> : <>
<h1>{isRegistering ? 'Criar conta' : 'Entrar'}</h1>
<p>{lead || (isRegistering ? 'Gratuita. Dá acesso a todos os cursos e materiais.' : 'Use o e-mail da sua conta Compor.')}</p>
<form noValidate onSubmit={handleSubmit}>
{isRegistering && (
<div className="field"><label htmlFor="auth-name">Nome</label><input id="auth-name" value={name} onChange={(event) => setName(event.target.value)} autoComplete="name" required /></div>
)}
<div className="field"><label htmlFor="auth-email">E-mail</label><input id="auth-email" type="email" value={email} onChange={(event) => setEmail(event.target.value)} autoComplete="email" autoCapitalize="none" required /></div>
<div className="field">
<label htmlFor="auth-password">Senha</label>
<input id="auth-password" type="password" value={password} onChange={(event) => setPassword(event.target.value)} autoComplete={isRegistering ? 'new-password' : 'current-password'} required />
{isRegistering && <small>Pelo menos 8 caracteres.</small>}
</div>
{error && <p className="formmsg bad" role="alert">{error}</p>}
<button className="btn" type="submit" disabled={isSubmitting}>{isSubmitting ? 'Aguarde…' : isRegistering ? 'Criar conta' : 'Entrar'}</button>
</form>
<p className="alt">
{isRegistering
? <>Já tem conta? <Link className="link" to={paths.signIn}>Entrar</Link></>
: <>Não tem conta? <Link className="link" to={paths.signUp}>Criar conta</Link></>}
</p>
{!isRegistering && <p className="alt"><Link className="link" to={paths.forgotPassword}>Esqueci minha senha</Link></p>}
</>}
</div>
</main>
);
};