femto-webapp/src/app/auth/authService.ts
2025-05-18 19:11:32 +02:00

53 lines
1.3 KiB
TypeScript

import { User } from '../user/userStore.ts'
import { dispatchMessage } from '../messageBus/messageBus.ts'
import client from '../api/client.ts'
import { ProblemDetails } from '../../types'
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) {
console.error(res.error)
throw new Error((res.error as ProblemDetails)?.detail ?? '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)
}
}