import { dispatchMessage } from '../messageBus/messageBus.ts' import { ProblemDetails } from '../../types' import { SignupCode } from './signupCode.ts' import { ApiClient } from '../api/client.ts' export class AuthService { constructor(private readonly client: ApiClient) {} async login(username: string, password: string, rememberMe: boolean = false) { const res = await this.client.POST('/auth/login', { body: { username, password, rememberMe }, credentials: 'include', }) if (!res.data) { throw new Error('invalid credentials') } dispatchMessage('auth:logged-in', null) } async signup(username: string, password: string, signupCode: string, rememberMe: boolean = false) { const res = await this.client.POST('/auth/register', { body: { username, password, signupCode, email: null, rememberMe }, credentials: 'include', }) if (!res.data) { console.error(res.error) throw new Error((res.error as ProblemDetails)?.detail ?? 'invalid credentials') } dispatchMessage('auth:registered', null) } async logout() { await this.client.DELETE('/auth/session', { credentials: 'include' }) dispatchMessage('auth:logged-out', null) } async createSignupCode(code: string, email: string, name: string) { const res = await this.client.POST('/auth/signup-codes', { body: { code, email, name }, credentials: 'include', }) if (!res.data) { console.error(res.error) throw new Error('failed to create signup code') } } async listSignupCodes() { const res = await this.client.GET('/auth/signup-codes', { credentials: 'include', }) if (!res.data) { console.error(res.error) throw new Error('error') } return res.data.signupCodes.map(SignupCode.fromDto) } async refreshUser(userId: string) { await this.client.GET(`/auth/user/{userId}`, { params: { path: { userId }, }, credentials: 'include', }) dispatchMessage('auth:refreshed', null) } }