2026-03-23 00:31:34 +00:00
|
|
|
import { getServerUrl } from "./server-url"
|
|
|
|
|
|
|
|
|
|
function authBase() {
|
2026-04-04 16:16:03 +01:00
|
|
|
return `${getServerUrl()}/api/auth`
|
2026-03-23 00:31:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface AuthUser {
|
2026-04-04 16:16:03 +01:00
|
|
|
id: string
|
|
|
|
|
name: string
|
|
|
|
|
email: string
|
|
|
|
|
image: string | null
|
2026-03-23 00:31:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface AuthSession {
|
2026-04-04 16:16:03 +01:00
|
|
|
user: AuthUser
|
|
|
|
|
session: { id: string; token: string }
|
2026-03-23 00:31:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function getSession(): Promise<AuthSession | null> {
|
2026-04-04 16:16:03 +01:00
|
|
|
const res = await fetch(`${authBase()}/get-session`, {
|
|
|
|
|
credentials: "include",
|
|
|
|
|
})
|
|
|
|
|
if (!res.ok) return null
|
|
|
|
|
const data = (await res.json()) as AuthSession | null
|
|
|
|
|
return data
|
2026-03-23 00:31:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function signIn(email: string, password: string): Promise<AuthSession> {
|
2026-04-04 16:16:03 +01:00
|
|
|
const res = await fetch(`${authBase()}/sign-in/email`, {
|
|
|
|
|
method: "POST",
|
|
|
|
|
headers: { "Content-Type": "application/json" },
|
|
|
|
|
credentials: "include",
|
|
|
|
|
body: JSON.stringify({ email, password }),
|
|
|
|
|
})
|
|
|
|
|
if (!res.ok) {
|
|
|
|
|
const data = (await res.json()) as { message?: string }
|
|
|
|
|
throw new Error(data.message ?? `Sign in failed: ${res.status}`)
|
|
|
|
|
}
|
|
|
|
|
return (await res.json()) as AuthSession
|
2026-03-23 00:31:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function signOut(): Promise<void> {
|
2026-04-04 16:16:03 +01:00
|
|
|
await fetch(`${authBase()}/sign-out`, {
|
|
|
|
|
method: "POST",
|
|
|
|
|
credentials: "include",
|
|
|
|
|
})
|
2026-03-23 00:31:34 +00:00
|
|
|
}
|