23 lines
653 B
TypeScript
23 lines
653 B
TypeScript
|
|
import type { FastifyRequest } from "fastify";
|
||
|
|
import { env } from "./env.js";
|
||
|
|
|
||
|
|
export function requireAdmin(req: FastifyRequest) {
|
||
|
|
// If ADMIN_TOKEN isn't set, run in "open" mode (dev).
|
||
|
|
if (!env.ADMIN_TOKEN) return;
|
||
|
|
|
||
|
|
const auth = req.headers.authorization;
|
||
|
|
if (!auth?.startsWith("Bearer ")) {
|
||
|
|
const err = new Error("missing bearer token");
|
||
|
|
// @ts-expect-error attach status
|
||
|
|
err.statusCode = 401;
|
||
|
|
throw err;
|
||
|
|
}
|
||
|
|
const token = auth.slice("Bearer ".length);
|
||
|
|
if (token !== env.ADMIN_TOKEN) {
|
||
|
|
const err = new Error("invalid bearer token");
|
||
|
|
// @ts-expect-error attach status
|
||
|
|
err.statusCode = 403;
|
||
|
|
throw err;
|
||
|
|
}
|
||
|
|
}
|