// // Middleware to handle returning the expiry time for the session. // This will allow clients to accurately manage session keep alive requests. // // In a similar manner to the swagger respone validator, we replace res.end() // with our own function, so that we will be called at the end of the response // tree. // etc. // 'use strict'; var debug = require('debug')('webconsole-api:cors-middleware'); var sessionTimeout = require(global.pathPrefix + 'utils.js').sessionTimeout; module.exports = middleware; /** * Define a middleware function to add the session expiry to responses, so that * clients can manage the session keepalive effectively. * * @param {Object} req - the express request * @param {Object} res - the express response */ function reportSessionExpiry(req, res) { const session = req.session; if (session && session.lastModified) { let expiry = new Date(session.lastModified); expiry.setMinutes(expiry.getMinutes() + sessionTimeout); const now = new Date(); const secondsLeft = Math.floor((expiry.getTime() - now.getTime()) / 1000); res.setHeader('X-BRIDGE-SESSION-EXPIRY', secondsLeft); } } /** * Define a middleware function to add the session expiry to responses, so that * clients can manage the session keepalive effectively. * This uses a replacement for the original res.end so that we get called at * the end as part of the response. * * @param {Object} req - the express request * @param {Object} res - the express response * @param {function} next - the callback for the next middleware in the chain * * @returns {any} - the result of the next() callback */ function middleware(req, res, next) { // Store the original end so we can restore it later var originalEnd = res.end; // Replace the end with our own function res.end = function(data, encoding) { // // Put the real end back // res.end = originalEnd; // // Add our header // reportSessionExpiry(req, res); // // Call the original end function to continue // res.end(data, encoding); }; // // Call the next item on the stack // return next(); }