Facebook-Events-iCal-Converter/lib/middlewares.js

71 lines
1.6 KiB
JavaScript
Raw Normal View History

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')
const MissingURLParameter = () => new Error('Please provide valid URL or event number.')
2019-10-17 22:36:29 +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) => {
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() })
}
const checkURLParameter = (req, res, next) => {
2019-10-17 22:36:29 +02:00
const { url } = req.body
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()
}
const createRouteLogger = ({ dev }) => {
return expressWinston.logger({
transports: createTransports(dev),
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
meta: true,
expressFormat: true,
})
}
const createErrorLogger = ({ dev }) => {
return expressWinston.errorLogger({
transports: createTransports(dev),
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
})
}
2019-10-17 22:36:29 +02:00
module.exports = {
genericErrorHandler,
checkURLParameter,
2019-10-23 15:15:20 +02:00
forceSecure,
createRouteLogger,
createErrorLogger,
2019-10-17 22:36:29 +02:00
}