panels-origin/web-saas/composables/useApi.ts
2026-08-21 16:55:01 -05:00

63 lines
1.8 KiB
TypeScript

export function useApi() {
async function api<T>(path: string, opts: RequestInit & { json?: unknown } = {}): Promise<T> {
const headers = new Headers(opts.headers);
if (opts.json !== undefined) headers.set("Content-Type", "application/json");
const res = await fetch(path, {
...opts,
headers,
credentials: "include",
body: opts.json !== undefined ? JSON.stringify(opts.json) : opts.body,
});
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }));
throw Object.assign(new Error(err.error || "Error"), { status: res.status, data: err });
}
const ct = res.headers.get("content-type") || "";
if (ct.includes("application/json")) return await res.json() as T;
return (await res.blob()) as T;
}
return { api };
}
export type SaasUser = {
id: number;
username: string;
display_name: string;
role?: string;
realm?: string;
};
export const useAuth = () => {
const user = useState<SaasUser | null>("saas-auth-user", () => null);
const { api } = useApi();
async function fetchMe() {
try {
const r = await api<{ user: SaasUser }>("/v1/auth/me");
user.value = r.user;
} catch {
user.value = null;
}
}
async function login(username: string, password: string) {
const r = await api<{ user: SaasUser }>("/v1/auth/login", {
method: "POST",
json: { username, password },
});
if (r.user.role !== "platform_admin" || r.user.realm !== "platform") {
await api("/v1/auth/logout", { method: "POST" });
user.value = null;
throw new Error("Esta consola es solo para administradores SaaS");
}
user.value = r.user;
}
async function logout() {
await api("/v1/auth/logout", { method: "POST" });
user.value = null;
await navigateTo("/login");
}
return { user, fetchMe, login, logout };
};