2019-10-24 10:21:41 +02:00
|
|
|
const winston = require('winston')
|
|
|
|
const expressWinston = require('express-winston')
|
|
|
|
const path = require('path')
|
2020-07-17 21:34:52 +02:00
|
|
|
const { checkValidURL } = require('./utils')
|
|
|
|
const { createTransports } = require('./log-utils')
|
2019-10-22 20:25:09 +02:00
|
|
|
const MissingURLParameter = () => new Error('Please provide valid URL or event number.')
|
2019-10-17 22:36:29 +02:00
|
|
|
|
2019-10-21 21:20:03 +02:00
|
|
|
const sendJSON = (req) => {
|
|
|
|
return req.accepts().includes('application/json')
|
|
|
|
}
|
|
|
|
|
2019-10-17 22:36:29 +02:00
|
|
|
const genericErrorHandler = (err, req, res, next) => {
|
2019-10-21 21:20:03 +02:00
|
|
|
if (sendJSON(req)) {
|
|
|
|
res
|
|
|
|
.status(500)
|
|
|
|
.send({ error: err.toString() })
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-10-17 22:36:29 +02:00
|
|
|
res
|
|
|
|
.status(500)
|
|
|
|
.render('error', { error: err.toString() })
|
|
|
|
}
|
|
|
|
|
2019-10-22 20:25:09 +02:00
|
|
|
const checkURLParameter = (req, res, next) => {
|
2019-10-17 22:36:29 +02:00
|
|
|
const { url } = req.body
|
|
|
|
|
2019-10-22 20:25:09 +02:00
|
|
|
if (!url || !checkValidURL(url)) {
|
|
|
|
return next(MissingURLParameter())
|
2019-10-17 22:36:29 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
|
2019-10-23 15:15:20 +02:00
|
|
|
const forceSecure = (req, res, next) => {
|
|
|
|
if (req.headers['x-forwarded-proto'] === 'http') {
|
|
|
|
return res.status(301).redirect(`https://${req.headers.host}/`)
|
|
|
|
}
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
|
2019-10-24 10:21:41 +02:00
|
|
|
const createRouteLogger = ({ dev }) => {
|
|
|
|
return expressWinston.logger({
|
2019-11-27 12:44:47 +01:00
|
|
|
transports: createTransports(dev),
|
2019-10-24 10:21:41 +02:00
|
|
|
format: winston.format.combine(
|
2019-11-27 12:44:47 +01:00
|
|
|
winston.format.timestamp(),
|
2019-10-24 10:21:41 +02:00
|
|
|
winston.format.json()
|
|
|
|
),
|
|
|
|
meta: true,
|
|
|
|
expressFormat: true,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const createErrorLogger = ({ dev }) => {
|
|
|
|
return expressWinston.errorLogger({
|
2019-11-27 12:44:47 +01:00
|
|
|
transports: createTransports(dev),
|
2019-10-24 10:21:41 +02:00
|
|
|
format: winston.format.combine(
|
2019-11-27 12:44:47 +01:00
|
|
|
winston.format.timestamp(),
|
2019-10-24 10:21:41 +02:00
|
|
|
winston.format.json()
|
|
|
|
),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-10-17 22:36:29 +02:00
|
|
|
module.exports = {
|
|
|
|
genericErrorHandler,
|
2019-10-22 20:25:09 +02:00
|
|
|
checkURLParameter,
|
2019-10-23 15:15:20 +02:00
|
|
|
forceSecure,
|
2019-10-24 10:21:41 +02:00
|
|
|
createRouteLogger,
|
|
|
|
createErrorLogger,
|
2019-10-17 22:36:29 +02:00
|
|
|
}
|