UNPKG

better-auth-dashboard

Version:

A better-Auth powered admin dashboard.

68 lines (67 loc) 2.48 kB
import { APIError, createAuthEndpoint, getSessionFromCtx, getEndpoints, } from "better-auth/api"; export function dashboardPlugin(config = {}) { const plugin = { id: "better-auth-dashboard", schema: { routeProtection: { fields: { route: { type: "string", unique: true, required: true, input: true, }, isRoleProtected: { type: "boolean", input: true, required: true, }, roleProtection: { type: "string", input: true, required: true, }, isAuthenticatedProtected: { type: "boolean", input: true, required: true, }, }, }, }, endpoints: { routeProtection: createAuthEndpoint("/dashboard/route-protection", { method: "GET", }, async (ctx) => { const session = await getSessionFromCtx(ctx); if (!session || session.user.role != "admin") { throw new APIError("UNAUTHORIZED", { message: `Invalid or missing session.`, }); } return ctx.json({ message: "Hello World", }); }), getEndpoints: createAuthEndpoint(`/dashboard/get-endpoints`, { method: "GET", }, async (ctx) => { const session = await getSessionFromCtx(ctx); if (!session || session.user.role != "admin") { throw new APIError("UNAUTHORIZED", { message: `Invalid or missing session.`, }); } const endpoints = getEndpoints(ctx.context, ctx.context.options); const paths = endpoints.middlewares.map((x) => x.path); return ctx.json({ paths, }); }), }, }; return plugin; } function hasAdminPlugin(context) { return Boolean(context.options.plugins?.find((x) => x.id === "admin")); }