64 lines
1.5 KiB
JavaScript
64 lines
1.5 KiB
JavaScript
export class Auth {
|
|
constructor() {
|
|
this.currentUser = null;
|
|
this.isAuthenticated = false;
|
|
}
|
|
|
|
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');
|
|
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;
|
|
}
|
|
|
|
getUser() {
|
|
return this.currentUser;
|
|
}
|
|
|
|
getToken() {
|
|
return localStorage.getItem('token');
|
|
}
|
|
}
|
|
|
|
export const auth = new Auth();
|