Changes
This commit is contained in:
54
src/plugins/auth.ts
Normal file
54
src/plugins/auth.ts
Normal 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;
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user