femto-webapp/src/app/auth/authService.ts
2025-05-16 16:09:35 +02:00

51 lines
1.2 KiB
TypeScript

import { User } from '../user/userStore.ts'
import { dispatchMessage } from '../messageBus/messageBus.ts'
import client from '../api/client.ts'
export class AuthService {
constructor(private readonly user: User | null) {}
async login(username: string, password: string) {
if (this.user != null) {
throw new Error('already logged in')
}
const res = await client.POST('/auth/login', {
body: { username, password },
credentials: 'include',
})
if (!res.data) {
throw new Error('invalid credentials')
}
dispatchMessage('auth:logged-in', { ...res.data })
}
async signup(username: string, password: string, signupCode: string) {
if (this.user != null) {
throw new Error('already logged in')
}
const res = await client.POST('/auth/register', {
body: { username, password, signupCode, email: null },
credentials: 'include',
})
if (!res.data) {
throw new Error('invalid credentials')
}
dispatchMessage('auth:registered', { ...res.data })
}
async logout() {
if (this.user == null) {
return
}
await client.DELETE('/auth/session', { credentials: 'include' })
dispatchMessage('auth:logged-out', null)
}
}