Files
sugarr/src/core/server/authHook.ts

20 lines
656 B
TypeScript

import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
export function registerAuthHook(
app: FastifyInstance,
secretKey: string,
exemptPaths: string[] = ['/health']
): void {
app.addHook('onRequest', async (request: FastifyRequest, reply: FastifyReply) => {
const path = request.url.split('?')[0];
if (!secretKey || exemptPaths.includes(path)) {
return;
}
const header = request.headers.authorization ?? '';
const token = header.startsWith('Bearer ') ? header.slice('Bearer '.length) : undefined;
if (token !== secretKey) {
reply.code(401).send({ error: 'unauthorized' });
}
});
}