core-api-lib
Version:
Core library with all microservice utilities
47 lines (46 loc) • 1.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateJwt = exports.checkJwt = exports.init = void 0;
const jwt = require("jsonwebtoken");
const fs = require("fs");
let authConfig = undefined;
exports.init = (config) => {
authConfig = config;
// use 'utf8' to get string instead of byte array (512 bit key)
authConfig.privateKey = fs.readFileSync(authConfig.PRIVATE_KEY_PATH, 'utf8');
authConfig.publicKey = fs.readFileSync(authConfig.PUBLIC_KEY_PATH, 'utf8');
};
exports.checkJwt = (req, res, next) => {
if (!authConfig) {
res.status(401).send(`NOT_AUTHORIZED`);
}
if (!(authConfig === null || authConfig === void 0 ? void 0 : authConfig.WHITELISTED_URLS.includes(req.url))) {
//Try to validate the token and get data
try {
//Get the jwt token from the head
let token = req.headers["authorization"];
token = token.split(' ')[1];
let jwtPayload;
jwtPayload = jwt.verify(token, authConfig === null || authConfig === void 0 ? void 0 : authConfig.privateKey);
res.locals.jwtPayload = jwtPayload;
}
catch (error) {
//If token is not valid, respond with 401 (unauthorized)
res.status(401).send(`NOT_AUTHORIZED`);
return;
}
}
//Call the next middleware or controller
next();
};
exports.generateJwt = (payload) => {
if (!authConfig) {
return 'No auth config found';
}
let jwtPayload = payload;
//The token is valid for 1 hour
//We want to send a new token on every request
return jwt.sign(jwtPayload, authConfig === null || authConfig === void 0 ? void 0 : authConfig.privateKey, {
expiresIn: "1h"
});
};