This commit is contained in:
2025-08-31 18:29:29 +02:00
parent aeaba64865
commit 97a095b422
21 changed files with 1990 additions and 0 deletions

54
src/plugins/auth.ts Normal file
View File

@@ -0,0 +1,54 @@
import { FastifyInstance } from "fastify";
import fp from "fastify-plugin";
import jwt from "jsonwebtoken";
export default fp(async (server: FastifyInstance) => {
server.addHook("preHandler", async (req, reply) => {
try {
// 1) Token aus Cookie lesen
const cookieToken = req.cookies?.token
// 2) Token aus Header lesen (falls Cookie nicht da ist)
const authHeader = req.headers.authorization
const headerToken = authHeader?.startsWith("Bearer ")
? authHeader.slice(7)
: null
let token = null
if(headerToken !== null && headerToken.length > 10){
token = headerToken
} else if(cookieToken ){
token = cookieToken
}
if (!token) {
return // keine Exception → Route darf z. B. public sein
}
const payload = jwt.verify(token, process.env.JWT_SECRET!) as {
user_id: string;
email: string;
tenant_id?: string;
role?: string;
};
(req as any).user = payload;
} catch (err) {
return reply.code(401).send({ error: "Invalid or expired token" });
}
});
});
declare module "fastify" {
interface FastifyRequest {
user?: {
user_id: string;
email: string;
tenant_id?: string;
role?: string;
};
}
}