'use strict'; const auditLogging = require('./index'); const debug = require('debug')('audit/rest-api-versions'); /** * This middleware will add to your request object auditLog for generating audit entries. * Checks for req.authInfo and passes SecurityContext down for logged-in users. * @param {object} auditLogCreds Credentials obtained from xsenv for connecting to auditlog service. * @param {number} auditLogVersion Auditlog service version. Either 1 or 2. Defaults to 2. */ function auditlogMiddleware(auditLogCreds, auditLogVersion = 2) { return function(req, res, next) { if (!req.authInfo) { debug('No security context received. Will use auditlog credentials to obtain client_credentials token.'); } if (!auditLogCreds) { next(new Error('Missing credentials for audit log service.')); } if (isNaN(auditLogVersion)) { next(new Error('Provided auditlog version was not a number.')); } if (auditLogVersion === 1) { req.auditLog = auditLogging(auditLogCreds, req.authInfo); next(); } else { auditLogging.v2(auditLogCreds, req.authInfo, (err, auditlog) => { if (err) { debug('Connecting to auditlog service failed: %s', err); next(new Error(err)); } else { req.auditLog = auditlog; next(); } }); } }; } module.exports = auditlogMiddleware;