67 lines
2.5 KiB
TypeScript
67 lines
2.5 KiB
TypeScript
import { api } from '@/api/client'
|
|
import { setAuthTokenProvider } from '@/api/client'
|
|
import type { User } from '@/domain/types'
|
|
|
|
let cachedUser: User | null = null
|
|
let authToken: string | null = null
|
|
setAuthTokenProvider(() => authToken)
|
|
|
|
export async function currentUser(): Promise<User | null> {
|
|
if (cachedUser) return cachedUser
|
|
try {
|
|
const res = await api.POST('/api/v1/auth/refresh', { params: { cookie: { user_id: 0 } } })
|
|
if (!res.response.ok) return null
|
|
// refresh returns legacy Person; adapt minimally to User shape
|
|
const p = res.data as unknown as { id: number; name: string } | null
|
|
cachedUser = p ? ({ id: p.id, email: '', displayName: p.name } as User) : null
|
|
} catch (_) {
|
|
cachedUser = null
|
|
}
|
|
return cachedUser
|
|
}
|
|
|
|
export async function login(username: string): Promise<User> {
|
|
// Legacy compatibility shim: avoid network call; will be removed with new LoginPage
|
|
cachedUser = { id: -1, email: '', displayName: username } as User
|
|
return cachedUser
|
|
}
|
|
|
|
// New multitenant-ready API surface
|
|
export async function loginWithPassword(email: string, password: string): Promise<User> {
|
|
const res = await api.POST('/api/v1/auth/login', { body: { email, password } })
|
|
if (!res.response.ok) {
|
|
const err = res.error
|
|
throw ((err instanceof Error && err) || new Error(`${res.response.status} ${res.response.statusText || 'HTTP error'}`))
|
|
}
|
|
const token = res.data?.accessToken ?? null
|
|
const user = res.data?.user ?? null
|
|
if (!token || !user) throw new Error('Invalid token response')
|
|
authToken = token
|
|
cachedUser = user as User
|
|
return cachedUser
|
|
}
|
|
|
|
export async function createAccount(email: string, displayName: string, password: string): Promise<User> {
|
|
const res = await api.POST('/api/v1/auth/register', { body: { email, password, displayName } })
|
|
if (!res.response.ok) {
|
|
const err = res.error
|
|
throw ((err instanceof Error && err) || new Error(`${res.response.status} ${res.response.statusText || 'HTTP error'}`))
|
|
}
|
|
const token = res.data?.accessToken ?? null
|
|
const user = res.data?.user ?? null
|
|
if (!token || !user) throw new Error('Invalid token response')
|
|
authToken = token
|
|
cachedUser = user as User
|
|
return cachedUser
|
|
}
|
|
|
|
export async function handleGoogleLogin(_token: string): Promise<never> {
|
|
// Placeholder until Google OAuth flow is wired
|
|
throw new Error('handleGoogleLogin not implemented yet')
|
|
}
|
|
|
|
export async function logout(): Promise<void> {
|
|
// Clear local cache; server session is cookie-based and will be refreshed on next call
|
|
cachedUser = null
|
|
authToken = null
|
|
}
|