Files
Aislo/A06_Login/A06_Login_Api_Fetch.ts
T

57 lines
1.6 KiB
TypeScript

import { API_BASE_URL } from "@config/config_frontend";
export interface ApiResult {
status: string;
detail?: string;
reason?: string;
}
export interface SessionUser {
id: string;
email: string;
name?: string;
role?: string;
company_id?: number | null;
is_master?: boolean;
}
async function post(path: string, body?: object): Promise<ApiResult> {
const response = await fetch(`${API_BASE_URL}${path}`, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
body: body ? JSON.stringify(body) : undefined,
});
const result = (await response.json()) as ApiResult;
if (!response.ok) throw new Error(result.detail ?? "Request failed");
return result;
}
export function requestLogin(email: string, password: string): Promise<ApiResult> {
return post("/auth/login/request", { email, password });
}
export function verifyLogin(email: string, otpCode: string): Promise<ApiResult> {
return post("/auth/login/verify", { email, otp_code: otpCode });
}
export async function fetchSession(): Promise<boolean> {
const response = await fetch(`${API_BASE_URL}/auth/session`, { credentials: "include" });
return response.ok;
}
export async function fetchSessionUser(): Promise<SessionUser | null> {
try {
const response = await fetch(`${API_BASE_URL}/auth/session`, { credentials: "include" });
if (!response.ok) return null;
const data = (await response.json()) as { status: string; user?: SessionUser };
return data.user ?? null;
} catch {
return null;
}
}
export function logout(): Promise<ApiResult> {
return post("/auth/logout");
}