34 lines
1.0 KiB
TypeScript
34 lines
1.0 KiB
TypeScript
// Access the provided Zitadel auth instance + a small JSON helper for /api calls.
|
|
// `auth.fetch` auto-attaches the Bearer access token.
|
|
export function useAuth() {
|
|
const { $auth } = useNuxtApp() as unknown as {
|
|
$auth: {
|
|
isAuthenticated: Ref<boolean>;
|
|
isLoading: Ref<boolean>;
|
|
user: Ref<{ sub: string; name: string; email: string } | null>;
|
|
error: Ref<string | null>;
|
|
login: () => void;
|
|
logout: () => Promise<void>;
|
|
fetch: (url: string, init?: RequestInit) => Promise<Response>;
|
|
};
|
|
};
|
|
|
|
async function api<T = unknown>(path: string, init?: RequestInit): Promise<T> {
|
|
const res = await $auth.fetch(`/api${path}`, init);
|
|
if (!res.ok) {
|
|
let message = `${res.status}`;
|
|
try {
|
|
const body = await res.json();
|
|
message = body?.statusMessage || body?.message || message;
|
|
} catch {
|
|
// non-JSON error body
|
|
}
|
|
throw new Error(message);
|
|
}
|
|
if (res.status === 204) return undefined as T;
|
|
return (await res.json()) as T;
|
|
}
|
|
|
|
return { auth: $auth, api };
|
|
}
|