antes de alterar login

This commit is contained in:
2026-05-26 16:40:01 +01:00
parent ef265ceeef
commit 3aa6e5468d
12 changed files with 316 additions and 92 deletions

View File

@@ -23,11 +23,51 @@ export default function LoginPage() {
setLoading(true);
try {
await signInWithEmailAndPassword(auth, email, password);
const userCredential = await signInWithEmailAndPassword(auth, email, password);
// Verify the user has a restaurant record before redirecting
if (!userCredential.user?.email) {
setError("Erro: Utilizador sem email válido.");
return;
}
// Success — redirect to dashboard
router.push("/");
} catch (err: any) {
console.error(err);
setError("Credenciais inválidas. Verifique o seu email e palavra-passe.");
console.error("[Login Error]", err.code, err.message);
// Map Firebase Auth error codes to user-friendly messages in Portuguese
switch (err.code) {
case "auth/user-not-found":
setError("Esta conta não existe. Verifique o email ou registe-se.");
break;
case "auth/wrong-password":
setError("Palavra-passe incorrecta. Tente novamente.");
break;
case "auth/invalid-email":
setError("Email inválido. Verifique o formato do email.");
break;
case "auth/invalid-credential":
setError("Credenciais inválidas. Verifique o email e a palavra-passe.");
break;
case "auth/too-many-requests":
setError("Demasiadas tentativas falhadas. Aguarde alguns minutos e tente novamente.");
break;
case "auth/invalid-verification-id":
setError("Sessão expirada. Por favor, recarregue a página e tente novamente.");
break;
case "auth/network-request-failed":
setError("Erro de conexão. Verifique a sua ligação à internet.");
break;
case "auth/weak-password":
setError("A palavra-passe é demasiado curta. Deve ter pelo menos 6 caracteres.");
break;
case "auth/popup-closed-by-user":
// User closed the popup — no error needed
break;
default:
setError("Erro ao entrar. Verifique as suas credenciais e tente novamente.");
}
} finally {
setLoading(false);
}

View File

@@ -37,6 +37,23 @@ export default function RegisterPage() {
setError("");
setLoading(true);
// Validate inputs before attempting registration
if (!formData.email || !formData.email.includes("@")) {
setError("Por favor, insira um email válido.");
setLoading(false);
return;
}
if (formData.password.length < 6) {
setError("A palavra-passe deve ter pelo menos 6 caracteres.");
setLoading(false);
return;
}
if (!formData.establishmentName.trim()) {
setError("Por favor, insira o nome do restaurante.");
setLoading(false);
return;
}
try {
// 1. Criar utilizador na Firebase Auth
const userCredential = await createUserWithEmailAndPassword(auth, formData.email, formData.password);
@@ -62,10 +79,37 @@ export default function RegisterPage() {
// 3. Gravar na Realtime Database em /Restaurantes
await set(ref(db, `Restaurantes/${documentId}`), payload);
// 4. Success — redirect to dashboard
router.push("/");
} catch (err: any) {
console.error(err);
setError(err.message || "Ocorreu um erro ao registar o restaurante.");
console.error("[Register Error]", err.code, err.message);
// Map Firebase Auth error codes to user-friendly messages in Portuguese
switch (err.code) {
case "auth/email-already-in-use":
setError("Este email já está registado. Tente fazer login.");
break;
case "auth/weak-password":
setError("A palavra-passe deve ter pelo menos 6 caracteres.");
break;
case "auth/invalid-email":
setError("Email inválido. Verifique o formato do email.");
break;
case "auth/operation-not-allowed":
setError("Registo de contas está desactivado. Contacte o suporte.");
break;
case "auth/network-request-failed":
setError("Erro de conexão. Verifique a sua ligação à internet.");
break;
case "auth/too-many-requests":
setError("Demasiadas tentativas. Aguarde alguns minutos e tente novamente.");
break;
case "auth/invalid-credential":
setError("Credenciais inválidas.");
break;
default:
setError(`Erro ao criar conta: ${err.message || "Tente novamente."}`);
}
} finally {
setLoading(false);
}

View File

@@ -21,6 +21,15 @@ export default function DashboardHomePage() {
const { mesas, loading: loadingMesas } = useMesas();
const { staff } = useStaff();
// Guard against missing user data
if (!user) {
return (
<div className="flex items-center justify-center min-h-[60vh]">
<div className="text-primary font-display text-2xl animate-pulse">A carregar...</div>
</div>
);
}
// 1. Calculate top stats
const todayStr = new Date().toISOString().split('T')[0];
const todayReservas = reservas.filter(r => r.data === todayStr || r.estado.startsWith("Confirmada"));