UNPKG

@fran-834/gs-microservice-core

Version:

Core package for Node.js microservices by Galduria Software. Includes security, logging, validation, and error handling middlewares.

47 lines (46 loc) 2.09 kB
import { getAuthSecret } from "../config/auth.config.js"; import jwt from "jsonwebtoken"; import { AppError, commonErrors, commonHTTPErrors } from "../helpers/errors/index.js"; const verifyToken = (req, res, next) => { try { // Validate that the Authorization header exists and has the correct format const authHeader = req.headers["authorization"]; if (!authHeader || typeof authHeader !== "string" || !authHeader.startsWith("Bearer ")) { throw new AppError(commonErrors.unauthorized, commonHTTPErrors.unauthorized, "Unauthorized"); } // Extraer el token const token = authHeader.split(" ")[1]; if (!token) { throw new AppError(commonErrors.unauthorized, commonHTTPErrors.unauthorized, "Unauthorized"); } const secret = getAuthSecret(); // Verify the token using the secret key jwt.verify(token, secret, (error, decoded) => { if (error) { // If token verification fails, throw an unauthorized error throw new AppError(commonErrors.unauthorized, commonHTTPErrors.unauthorized, "Unauthorized"); } // Attach user information to the request object req.userId = decoded.id; req.sessionId = decoded.sessionId; req.userType = decoded.type; if (req.body?.companyId) { req.companyId = req.body.companyId; } else if (Array.isArray(decoded.companies) && decoded.companies.length > 0 && decoded.companies[0].id) { req.companyId = decoded.companies[0].id; } else { // Si no hay companyId, lanza error explícito throw new AppError(commonErrors.unauthorized, commonHTTPErrors.unauthorized, "Invalid token payload: companyId not found"); } // Proceed to the next middleware next(); }); } catch (error) { // Pass any errors to the next middleware next(error); } }; export { verifyToken };