updated adapters to automatically verify auth

This commit is contained in:
dswbx
2025-01-25 09:09:09 +01:00
parent f64e5dac03
commit b0c5f6307a
11 changed files with 60 additions and 57 deletions

View File

@@ -13,11 +13,13 @@ export type Options = {
host?: string;
};
export function getApi(Astro: TAstro, options: Options = { mode: "static" }) {
return new Api({
export async function getApi(Astro: TAstro, options: Options = { mode: "static" }) {
const api = new Api({
host: new URL(Astro.request.url).origin,
headers: options.mode === "dynamic" ? Astro.request.headers : undefined
});
await api.verifyAuth();
return api;
}
let app: App;

View File

@@ -29,8 +29,10 @@ export function createApi({ req }: GetServerSidePropsContext) {
}
export function withApi<T>(handler: (ctx: GetServerSidePropsContext & { api: Api }) => T) {
return (ctx: GetServerSidePropsContext & { api: Api }) => {
return handler({ ...ctx, api: createApi(ctx) });
return async (ctx: GetServerSidePropsContext & { api: Api }) => {
const api = createApi(ctx);
await api.verifyAuth();
return handler({ ...ctx, api });
};
}

View File

@@ -1,9 +1,11 @@
import { useAuth } from "bknd/client";
import type { BkndAdminProps } from "bknd/ui";
import { Suspense, lazy, useEffect, useState } from "react";
export function adminPage(props?: BkndAdminProps) {
const Admin = lazy(() => import("bknd/ui").then((mod) => ({ default: mod.Admin })));
return () => {
const auth = useAuth();
const [loaded, setLoaded] = useState(false);
useEffect(() => {
if (typeof window === "undefined") return;
@@ -13,7 +15,7 @@ export function adminPage(props?: BkndAdminProps) {
return (
<Suspense>
<Admin {...props} />
<Admin withProvider={{ user: auth.user }} {...props} />
</Suspense>
);
};

View File

@@ -1,5 +1,6 @@
import { type FrameworkBkndConfig, createFrameworkApp } from "adapter";
import type { App } from "bknd";
import { Api } from "bknd/client";
export type RemixBkndConfig = FrameworkBkndConfig;
@@ -12,3 +13,19 @@ export function serve(config: RemixBkndConfig = {}) {
return app.fetch(args.request);
};
}
export function withApi<Args extends { request: Request; context: { api: Api } }, R>(
handler: (args: Args, api: Api) => Promise<R>
) {
return async (args: Args) => {
if (!args.context.api) {
args.context.api = new Api({
host: new URL(args.request.url).origin,
headers: args.request.headers
});
await args.context.api.verifyAuth();
}
return handler(args, args.context.api);
};
}