UNPKG

better-auth

Version:

The most comprehensive authentication framework for TypeScript.

66 lines (65 loc) 2.26 kB
import { parseSetCookieHeader, toCookieOptions } from "../../cookies/cookie-utils.mjs"; import { getSessionQuerySchema } from "../../cookies/session-store.mjs"; import { getSession } from "../../api/routes/session.mjs"; import { PACKAGE_VERSION } from "../../version.mjs"; import { getEndpointResponse } from "../../utils/plugin-helper.mjs"; import { createAuthEndpoint, createAuthMiddleware } from "@better-auth/core/api"; //#region src/plugins/custom-session/index.ts const customSession = (fn, options, pluginOptions) => { return { id: "custom-session", version: PACKAGE_VERSION, hooks: { after: [{ matcher: (ctx) => ctx.path === "/multi-session/list-device-sessions" && (pluginOptions?.shouldMutateListDeviceSessionsEndpoint ?? false), handler: createAuthMiddleware(async (ctx) => { const response = await getEndpointResponse(ctx); if (!response) return; const newResponse = await Promise.all(response.map(async (v) => await fn(v, ctx))); return ctx.json(newResponse); }) }] }, endpoints: { getSession: createAuthEndpoint("/get-session", { method: "GET", query: getSessionQuerySchema, metadata: { CUSTOM_SESSION: true, openapi: { description: "Get custom session data", responses: { "200": { description: "Success", content: { "application/json": { schema: { type: "array", nullable: true, items: { $ref: "#/components/schemas/Session" } } } } } } } }, requireHeaders: true }, async (ctx) => { const session = await getSession()({ ...ctx, method: "GET", asResponse: false, headers: ctx.headers, returnHeaders: true }).catch((e) => { return null; }); if (!session?.response) return ctx.json(null); const fnResult = await fn(session.response, ctx); for (const cookieStr of session.headers.getSetCookie()) parseSetCookieHeader(cookieStr).forEach((attrs, name) => { ctx.setCookie(name, attrs.value, toCookieOptions(attrs)); }); session.headers.delete("set-cookie"); session.headers.forEach((value, key) => { ctx.setHeader(key, value); }); return ctx.json(fnResult); }) }, $Infer: { Session: {} }, options: pluginOptions }; }; //#endregion export { customSession };