mirror of
https://github.com/FJurmanovic/sugarr.git
synced 2026-11-11 07:41:08 +00:00
20 lines
656 B
TypeScript
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' });
|
|
}
|
|
});
|
|
}
|