fertig-classic-games/public/src/services/auth.js

51 lines
1.0 KiB
JavaScript

import { api } from './api.js';
class AuthStore {
constructor() {
this.user = null;
this.listeners = new Set();
}
subscribe(fn) {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
}
emit() {
for (const fn of this.listeners) fn(this.user);
}
async refresh() {
try {
const { user } = await api.get('/auth/me');
this.user = user;
} catch {
this.user = null;
}
this.emit();
return this.user;
}
async login(identifier, password) {
const { user } = await api.post('/auth/login', { identifier, password });
this.user = user;
this.emit();
return user;
}
async register({ email, username, password }) {
const result = await api.post('/auth/register', { email, username, password });
this.user = result.user;
this.emit();
return result;
}
async logout() {
try { await api.post('/auth/logout'); } catch { /* ignore */ }
this.user = null;
this.emit();
}
}
export const auth = new AuthStore();