mirror of
https://github.com/FJurmanovic/sugarr.git
synced 2026-11-11 07:41:08 +00:00
Add core server Controller base, auth hook, and buildServer
This commit is contained in:
19
src/core/server/authHook.ts
Normal file
19
src/core/server/authHook.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
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' });
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user