citi-hub-session-engine
Version:
Module for authentication methods for CITI hub
88 lines (74 loc) • 3.13 kB
JavaScript
const { configurations_key } = require("../utils/Constants");
const { logger } = require("../utils/Logger");
const fetch = require("node-fetch");
const { setUserTransactionContext } = require("../utils/transactionContext");
const validate = async (token) => {
// Aquí puedes añadir tu lógica de validación del token
// Por ejemplo, decodificar un JWT, buscar el token en la base de datos, etc.
//const isValid = validateToken(token); // Implementa esta función según tu lógica
const config = global[configurations_key];
const endpointValidate = config.validate.endpoint;
logger.info(`endpointValidate ${endpointValidate} `);
//INVOKE ENDPOINT VALIDATE, POST, headers: {company: config.company, provider: 'device'}
const response = await fetch(endpointValidate, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: token,
},
})
.then((res) => res.json())
.catch((error) => console.error("error", error));
if (response.code !== 200) {
logger.error(`Error validating token ${JSON.stringify(response)}`);
return {
isValid: false,
user: null,
};
}
setUserTransactionContext(response.user);
return {
isValid: true,
user: response.user,
};
};
const bearer = (server, options) => {
return {
authenticate: async (_req, _h) => {
try {
logger.info(`Bearer schema strategy`);
//get token from header
logger.info("Get token from header");
const tokenHe = _req.headers.authorization;
logger.info(`tokenHeader ${tokenHe} `);
logger.info("Get configurations for module");
//get configurations for global variable
const config = global[configurations_key];
logger.info("SessionEngine configurations", config);
if (undefined === config || null === config) {
logger.error("sessionEngine configurations not found");
return _h.response({ code: 500, message: "sessionEngine configurations not found" }).code(500);
}
if (!tokenHe) {
throw _h.response({ code: 400, message: "header bearer 'token' is required" }).code(400);
}
const valid = await validate(tokenHe);
logger.info(`valid user ? ${valid.isValid}`);
if (!valid.isValid) {
//unauthorized error, invalid token
//consider Lifecycle methods called before the handler can only return an error, a takeover response, or a continue signal
return _h.response({ code: 401, message: "Unauthorized" }).code(401).takeover();
}
// Si la validación es exitosa, continúa con el request
// Puedes adjuntar información al request.auth.credentials si es necesario
return _h.authenticated({
credentials: valid,
});
} catch (error) {
logger.error("Error on bearer schema strategy", error);
throw _h.response({ code: 500, message: "Internal error" }).code(500);
}
},
};
};
module.exports = bearer;