84 lines
3.7 KiB
TypeScript
84 lines
3.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, 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);
|
|
|
|
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 signedInUser = isRegistering ? await register(name, email, password) : await login(email, password);
|
|
|
|
if (!signedInUser) {
|
|
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;
|
|
}
|
|
|
|
navigate(homeFor(signedInUser.role), { replace: true });
|
|
};
|
|
|
|
return (
|
|
<main className="wrap page auth-page enter">
|
|
<div className="auth">
|
|
<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>
|
|
);
|
|
};
|