File size: 1,228 Bytes
4e83772 5a1ffec 4e83772 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import { NextFunction, Request, Response } from "express";
import jwt from "jsonwebtoken";
import { ENVS } from "@/config/env.config.js";
import { USER_ERRORS } from "@/constants/errors.js";
import { STATUS_CODES } from "@/utils/statusCodes.js";
import AppError from "@/utils/AppError.js";
export const authenticaContainerToken = (req: Request, res: Response, next: NextFunction) => {
try {
const serviceToken = req.headers["authorization"]?.split(" ")[1];
const containerToken = req.headers["x-static-token"];
if (!containerToken || !serviceToken) {
console.log("No token");
return res.status(STATUS_CODES.UNAUTHORIZED).json({ message: USER_ERRORS.NO_TOKEN });
}
const decoded = jwt.verify(serviceToken, ENVS.SERVICE_JWT_SECRET, {
algorithms: ["HS256"],
}) as { pId: string; dId: string };
// console.log(decoded);
const server_token = ENVS.CONTAINER_API_TOKEN;
if (containerToken !== server_token) {
console.log("Invalid container token");
return res.status(STATUS_CODES.UNAUTHORIZED).json({ message: USER_ERRORS.INVALID_TOKEN, resource: "Container token" });
}
} catch (error: any) {
console.log("JWT decode error");
next(new AppError(error.message, 401));
return;
}
next();
};
|