Refactor authentication logic in Auth service; implement async login with error handling and add token management
This commit is contained in:
parent
5944a4fb09
commit
a13613a660
|
|
@ -0,0 +1,2 @@
|
|||
# API Configuration
|
||||
VITE_API_BASE_URL=http://localhost:5269
|
||||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
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();
|
||||
|
|
|
|||
Loading…
Reference in New Issue