Refactor login method to improve error handling and logging

This commit is contained in:
javiermengual 2026-01-23 19:52:01 +01:00
parent 6021b351a3
commit 39406597d9
1 changed files with 26 additions and 9 deletions

View File

@ -4,28 +4,45 @@ export class Auth {
this.isAuthenticated = false;
}
async login(email, password) {
if (!email || !password) return false;
async login(identifier, password) {
if (!identifier || !password) return false;
try {
const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/Auth/login`, {
const apiUrl = `${import.meta.env.VITE_API_BASE_URL}/api/Auth/login`;
const body = { Username: identifier, Password: password };
console.log('🔐 Login attempt - Datos enviados:', body);
const response = await fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
body: JSON.stringify(body)
});
if (!response.ok) return false;
console.log('📡 Response status:', response.status, response.ok);
const { token, user } = await response.json();
if (!token) return false;
if (!response.ok) {
const errorData = await response.json().catch(() => null);
console.error('❌ Error del servidor:', errorData);
return false;
}
this.currentUser = user || { email };
const data = await response.json();
console.log('✅ Respuesta exitosa:', data);
const { token, user } = data;
if (!token) {
console.error('❌ No token in response');
return false;
}
this.currentUser = user || { identifier };
this.isAuthenticated = true;
localStorage.setItem('user', JSON.stringify(this.currentUser));
localStorage.setItem('token', token);
console.log('✅ Login successful, guardado en localStorage');
return true;
} catch (error) {
console.error('Login failed', error);
console.error('❌ Login error:', error);
return false;
}
}