Overview
StockPro uses Firebase Authentication for user management, session handling, and route protection. This page documents all authentication functions and patterns used across the application.
Core Authentication Imports
import { auth } from "./firebase.js";
import {
onAuthStateChanged,
signOut,
signInWithEmailAndPassword,
sendPasswordResetEmail,
createUserWithEmailAndPassword,
fetchSignInMethodsForEmail
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js";
Authentication Functions
onAuthStateChanged
Monitors authentication state changes and executes callback when user signs in or out.
Source: public/js/auth.js:7, public/js/login.js:66, public/js/ventas.js:8
onAuthStateChanged(auth, async (usuario) => {
if (!usuario) {
// User is signed out - redirect to login
window.location.href = "login.html";
} else {
// User is signed in - usuario object available
}
});
Firebase Auth instance from firebase.js
Callback function that receives the user object (or null if signed out)
Firebase User object containing uid, email, and other user properties. Null if not authenticated.
Route Protection Pattern
The application uses onAuthStateChanged to protect multiple routes:
const pagina = window.location.pathname.split("/").pop();
onAuthStateChanged(auth, async (usuario) => {
if (!usuario) {
if (pagina === "panel_configuracion.html") return window.location.href = "login.html";
if (pagina === "index.html") return window.location.href = "login.html";
if (pagina === "panel_inventario.html") return window.location.href = "login.html";
if (pagina === "panel_nueva-venta.html") return window.location.href = "login.html";
if (pagina === "panel_nuevo_producto.html") return window.location.href = "login.html";
if (pagina === "panel_reportes.html") return window.location.href = "login.html";
if (pagina === "panel_ventas.html") return window.location.href = "login.html";
}
});
signInWithEmailAndPassword
Authenticates users with email and password credentials.
Source: public/js/login.js:36
try {
const credenciales = await signInWithEmailAndPassword(auth, email, password);
if (credenciales) {
console.log("Correo:", credenciales.user.email);
window.location.href = "index.html";
}
} catch (error) {
passwordError.textContent = "Correo o contraseña incorrecta";
}
Contains the authenticated user object and additional credential information
Firebase User object with properties like uid, email, displayName
const form = document.getElementById("inicio_sesion");
const emailInput = document.getElementById("email");
const passwordInput = document.getElementById("contrasena");
const passwordError = document.getElementById("contrasenaError");
form.addEventListener("submit", async (e) => {
e.preventDefault();
const email = emailInput.value;
const password = passwordInput.value;
// Clear error messages
emailError.textContent = "";
passwordError.textContent = "";
let valido = true;
if (!email) {
emailError.textContent = "Este campo es obligatorio";
valido = false;
}
if (!password) {
passwordError.textContent = "Este campo es obligatorio";
valido = false;
}
if (!valido) return;
try {
const credenciales = await signInWithEmailAndPassword(auth, email, password);
if (credenciales) {
console.log("Correo:", credenciales.user.email);
window.location.href = "index.html";
}
} catch (error) {
passwordError.textContent = "Correo o contraseña incorrecta";
}
});
signOut
Signs out the current user and clears authentication state.
Source: public/js/auth.js:24, public/js/ventas.js:4
document.getElementById("cerrar_sesion").addEventListener("click", async () => {
await signOut(auth);
});
Resolves when sign-out is complete. The onAuthStateChanged listener will be triggered with null user.
sendPasswordResetEmail
Sends a password reset email to the specified email address.
Source: public/js/restaurar_contraseña.js:13
try {
await sendPasswordResetEmail(auth, emailInput);
console.log("Correo Enviado");
// Password reset email sent successfully
} catch (error) {
console.error("Error: ", error);
}
User’s email address to send the reset link
Resolves when the email is sent. User will receive a link to reset their password.
public/js/restaurar_contraseña.js
import { auth } from "./firebase.js";
import { sendPasswordResetEmail } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js";
const form = document.getElementById("inicio_sesion");
form.addEventListener("submit", async (e) => {
e.preventDefault();
const emailInput = document.getElementById("email").value.trim();
if (!emailInput) return console.log("Sin correo");
try {
await sendPasswordResetEmail(auth, emailInput);
console.log("Correo Enviado");
} catch (error) {
console.error("Error: ", error);
}
});
createUserWithEmailAndPassword
Creates a new user account with email and password.
Source: public/js/agregar_empleado.js:29
try {
const credenciales = await createUserWithEmailAndPassword(auth, email, password);
const user = credenciales.user;
// Store additional user data in Firestore
const usuario = {
uid: user.uid,
name: name,
email: email,
tipo: tipo
};
await addDoc(collection(db, "usuarios"), usuario);
alert(`Registrado como: Usuario ${name}, Tipo: ${tipo}`);
} catch (error) {
console.error("Error al agregar usuario:", error);
}
New user’s password (minimum 6 characters)
Contains the newly created user object
Firebase User object with uid, email, and other properties
fetchSignInMethodsForEmail
Checks if an email is already registered in the system.
Source: public/js/agregar_empleado.js:16
const emailToCheck = email;
fetchSignInMethodsForEmail(auth, emailToCheck)
.then((signInMethods) => {
if (signInMethods && signInMethods.length > 0) {
console.log(`El correo ${emailToCheck} ya registrado.`);
} else {
console.log(`El correo ${emailToCheck} no está registrado.`);
}
})
.catch((error) => {
console.error("Error al verificar el correo:", error);
});
Array of sign-in methods for this email. Empty array if email is not registered.
Common Authentication Patterns
Auto-redirect for Authenticated Users
Prevents logged-in users from accessing the login page:
onAuthStateChanged(auth, (usuario) => {
if (usuario) {
window.location.href = "index.html";
}
});
Password Toggle Visibility
const togglePassword = document.querySelector("#togglePassword");
togglePassword.addEventListener("click", () => {
const type = passwordInput.type === "password" ? "text" : "password";
passwordInput.type = type;
togglePassword.classList.toggle("fa-eye");
togglePassword.classList.toggle("fa-eye-slash");
});
Error Handling
Authentication errors should be caught and displayed to users:
try {
await signInWithEmailAndPassword(auth, email, password);
// Success - redirect or show success message
} catch (error) {
// Display user-friendly error message
passwordError.textContent = "Correo o contraseña incorrecta";
}