Refactor authentication logic in Auth service; implement async login with error handling and add token management

This commit is contained in:
javiermengual 2026-01-16 19:04:42 +01:00
parent 5944a4fb09
commit a13613a660
3 changed files with 34 additions and 6 deletions

2
.env Normal file
View File

@ -0,0 +1,2 @@
# API Configuration
VITE_API_BASE_URL=http://localhost:5269

View File

@ -5,7 +5,7 @@ export function renderDashboard() {
const container = document.createElement('div');
container.className = 'dashboard';
container.innerHTML = `
container.innerHTML = /*html*/`
<div class="dashboard-header">
<h1>Bienvenido, ${user?.email || 'Usuario'}</h1>
<button id="logout-button" class="logout-button">Cerrar Sesión</button>

View File

@ -4,27 +4,49 @@ export class Auth {
this.isAuthenticated = false;
}
login(email, password) {
if (email && password) {
this.currentUser = { email };
async login(email, password) {
if (!email || !password) return false;
try {
const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/Auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});
if (!response.ok) return false;
const { token, user } = await response.json();
if (!token) return false;
this.currentUser = user || { email };
this.isAuthenticated = true;
localStorage.setItem('user', JSON.stringify(this.currentUser));
localStorage.setItem('token', token);
return true;
}
} catch (error) {
console.error('Login failed', error);
return false;
}
}
logout() {
this.currentUser = null;
this.isAuthenticated = false;
localStorage.removeItem('user');
localStorage.removeItem('token');
}
checkAuth() {
const user = localStorage.getItem('user');
if (user) {
const token = localStorage.getItem('token');
if (user && token) {
this.currentUser = JSON.parse(user);
this.isAuthenticated = true;
} else {
this.isAuthenticated = false;
this.currentUser = null;
}
return this.isAuthenticated;
}
@ -32,6 +54,10 @@ export class Auth {
getUser() {
return this.currentUser;
}
getToken() {
return localStorage.getItem('token');
}
}
export const auth = new Auth();