happy-server/sources/app/api/utils/enableAuthentication.ts
2025-09-01 14:38:48 -07:00

28 lines
1.3 KiB
TypeScript

import { Fastify } from "../types";
import { log } from "@/utils/log";
import { auth } from "@/app/auth/auth";
export function enableAuthentication(app: Fastify) {
app.decorate('authenticate', async function (request: any, reply: any) {
try {
const authHeader = request.headers.authorization;
log({ module: 'auth-decorator' }, `Auth check - path: ${request.url}, has header: ${!!authHeader}, header start: ${authHeader?.substring(0, 50)}...`);
if (!authHeader || !authHeader.startsWith('Bearer ')) {
log({ module: 'auth-decorator' }, `Auth failed - missing or invalid header`);
return reply.code(401).send({ error: 'Missing authorization header' });
}
const token = authHeader.substring(7);
const verified = await auth.verifyToken(token);
if (!verified) {
log({ module: 'auth-decorator' }, `Auth failed - invalid token`);
return reply.code(401).send({ error: 'Invalid token' });
}
log({ module: 'auth-decorator' }, `Auth success - user: ${verified.userId}`);
request.userId = verified.userId;
} catch (error) {
return reply.code(401).send({ error: 'Authentication failed' });
}
});
}