Root cause: the router-guard adapter let index.vue mount and call the API before auth resolved, so auth.fetch returned a synthetic 401 (the banner) and the package's redirect-loop guard could strand the user. Now use the core ZitadelAuth and gate in an async plugin (Nuxt awaits it before mount), mirroring the working krypto-kuns app.
27 lines
926 B
TypeScript
27 lines
926 B
TypeScript
import type { ZitadelAuth } from "@kuns/zitadel-auth";
|
|
|
|
// Access the bootstrap-provided Zitadel auth instance + a small JSON helper for /api calls.
|
|
// By the time any component mounts, the plugin has gated auth, so `auth` is authenticated.
|
|
// `auth.fetch` auto-attaches the Bearer access token.
|
|
export function useAuth() {
|
|
const { $auth } = useNuxtApp() as unknown as { $auth: ZitadelAuth };
|
|
|
|
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 };
|
|
}
|