Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
accesslogger.setLevels(winston.config.syslog.levels);
accesslogger.stream = {
write: message => accesslogger.info("[API access]", message)
};
// set data directory for serving data
api.dataDirectory = config.api.dataDirectory;
// enable body parsing
// parse application/x-www-form-urlencoded
api.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
api.use(bodyParser.json());
// new token to log POST body
morgan.token('body', function (req) {return "body: " + JSON.stringify(req.body);});
api.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method ' +
':url :body HTTP/:http-version" :status :res[content-length] :response-time ms ' +
'":referrer" ":user-agent" ', {stream: accesslogger.stream}));
// configure listening port
api.listen(config.api.port, function () {
log.notice(`Real-time OSM API server running on port ${config.api.port}.`);
});
// initialise data storage
api.db = new sequelize(config.api.database, null, null, {
dialect: "sqlite",
storage: config.api.database,
logging: false,
operatorsAliases: false
});
for (j = 1; j < array.length; j += 1) {
if (array[j] === '') {
val += '=';
} else {
val += array[j];
}
}
params[array[0]] = val;
}
return params;
};
morgan.token('errormsg', function getErrorMsg(req) {
return req.errormsg
})
var logDirectory = path.join(__dirname, 'logs')
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
var accessLogStream = fs.createWriteStream(path.join(logDirectory, 'error.log'), {
flags: 'a'
})
// setup the logger
app.use(morgan('combined', {
stream: accessLogStream,
skip: function(req, res) {
return res.statusCode < 400
}
}))
//
// Copyright (c) Microsoft.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
'use strict';
const logger = require('morgan');
const encryptionMetadataKey = '_ClientEncryptionMetadata2';
const piiFormat = ':id :method :scrubbedUrl :status :response-time ms - :res[content-length] :encryptedSession :correlationId';
const format = ':method :scrubbedUrl :status :response-time ms - :res[content-length] :encryptedSession :correlationId';
logger.token('encryptedSession', function getUserId(req) {
const config = req.app.settings.runtimeConfig;
if (req.session && req.session.passport && req.session.passport.user) {
const userType = config.authentication.scheme === 'aad' ? 'azure' : 'github';
return req.session.passport.user[userType] && req.session.passport.user[userType][encryptionMetadataKey] !== undefined ? 'encrypted' : 'plain';
}
});
logger.token('id', function getUserId(req) {
const config = req.app.settings.runtimeConfig;
if (config) {
const userType = config.authentication.scheme === 'aad' ? 'azure' : 'github';
return req.user && req.user[userType] && req.user[userType].username ? req.user[userType].username : undefined;
}
});
logger.token('correlationId', function getCorrelationId(req) {
this.app.use((req, res, next) => {
if (config.maintenanceOpts.maintenanceMode === true) {
// send a 503 error, with a message to the bitpay status page
let errorCode = 503;
let errorMessage = 'BWS down for maintenance';
res.status(503).send({ code: errorCode, message: errorMessage });
} else {
next();
}
});
if (opts.disableLogs) {
log.level = 'silent';
} else {
const morgan = require('morgan');
morgan.token('walletId', function getId(req) {
return req.walletId ? '<' + req.walletId + '>' : '<>';
});
const logFormat =
':walletId :remote-addr :date[iso] ":method :url" :status :res[content-length] :response-time ":user-agent" ';
const logOpts = {
skip(req, res) {
if (res.statusCode != 200) return false;
return req.path.indexOf('/notifications/') >= 0;
}
};
this.app.use(morgan(logFormat, logOpts));
}
const router = express.Router();
const optKeys = [];
// Check for additional access logs
if (customTokens && typeof customTokens === "object") {
for (const key in customTokens) {
try {
morgan.token(key, typeof customTokens[key] === "function" ? customTokens[key] : errorHandler);
}
catch(err) {
morgan.token(key, errorHandler);
}
optKeys.push(`\"${key}\": \":${key}\"`);
}
}
morgan.token("host_name", function getHostName(request, response) {
return hostName;
});
morgan.token("service_name", function getHostName(request, response) {
return serviceName;
});
morgan.token("uri", function getUri(request, response) {
try {
return request._parsedUrl.pathname;
} catch (e) {
return "error";
}
});
morgan.token("query_string", function getQueryString(request) {
registerLogger: function (app) {
morgan.token('header', function (req, res) {
if (req.rawHeaders && Object.keys(req.rawHeaders).length != 0)
return req.rawHeaders;
else
return "-";
});
morgan.token('body', function (req, res) {
console.log(req.body)
if (req.body && Object.keys(req.body).length != 0)
return JSON.stringify(req.body);
else
return "-";
});
var logging_string = '[:date[clf]], User: :remote-user, ":method :url, Status: :status"\n Header:\n :header\n Body:\n :body'
var requestLogStream = fs.createWriteStream('requests.log', { flags: 'a' })
app.use(morgan(logging_string, { stream: requestLogStream }), morgan(logging_string))
}
}
color = {
hilite: function (v) {
return '\x1B[7m' + v + '\x1B[27m';
},
green: function (v) {
return '\x1B[40m\x1B[32m' + v + '\x1B[39m\x1B[49m';
},
pink: function (v) {
return '\x1B[40m\x1B[35m' + v + '\x1B[39m\x1B[49m';
}
},
sslStarted = false;
morgan.token('cooprcred', function (req, res) {
return color.pink(req.headers['coopr-userid'] + '/' + req.headers['coopr-tenantid']);
});
var httpLabel = color.green('http'),
corsLabel = color.pink('cors'),
httpStaticLogger = morgan(httpLabel + ' :method :url :status'),
httpIndexLogger = morgan(httpLabel + ' :method ' + color.hilite(':url') + ' :status'),
corsLogger = morgan(corsLabel + ' :method :url :cooprcred :status', {
skip: function (req, res) {
return req.method === 'OPTIONS'
}
});
console.log(color.hilite(pkg.name) + ' v' + pkg.version + ' starting up...');
/**
});
};
module.exports.stop = () =>
new Promise(resolve => module.exports.server.close(() => resolve()));
app.enable('trust proxy');
app.disable('x-powered-by');
app.use(expressCors());
app.use(expressBodyParser.json());
morgan.token('bodyJSON', req => JSON.stringify(req.body || {}));
morgan.token('extentionsJSON', (_, res) =>
JSON.stringify(res._extensions || {})
);
morgan.token('errorsJSON', (_, res) => JSON.stringify(res._errors || {}));
morgan.token('operationName', req => req.body.operationName);
app.use((req, res, next) => {
if (app.logStyle !== 'none') {
if (app.logFormat === 'json') {
if (app.logStyle === 'extended')
return morgan(
morganJSON({
timestamp: ':date[iso]',
method: ':method',
url: ':url',
status: ':status',
length: ':res[content-length]',
responseTimeMs: ':response-time',
remoteAddr: ':remote-addr',
userAgent: ':user-agent',
operation: ':operationName',
function createAccessLogger( logFormat ){
morgan.token('remote-addr', customRemoteAddr);
morgan.token('url', customURL);
return morgan( logFormat, {
stream: through( function write( ln, _, next ){
peliasLogger.info( ln.toString().trim() );
next();
})
});
}
}
});
morgan.token("server_name", function getServerName(request, response) {
try {
return request.headers.host ? request.headers.host : "unknown";
} catch (e) {
return "error";
}
});
morgan.token("service_color", function getServiceColor(request, response) {
return serviceColor;
});
morgan.token("remote_client_id", function getRemoteClientId(request, response) {
let rcId = "";
try {
rcId = request.headers.customeruuid;
if (request.headers[CUSTOMER_UUID]) {
rcId = request.headers[CUSTOMER_UUID];
}
if (request.headers[AUTH_INFO_USER_ID]) {
rcId = request.headers[AUTH_INFO_USER_ID];
}
if (!rcId) {
rcId = "unknown";