add middleware for forcing https

This commit is contained in:
Ondrej Synacek 2019-10-23 15:15:20 +02:00
parent 21df3856cf
commit 52b86953aa
3 changed files with 22 additions and 8 deletions

View File

@ -7,13 +7,16 @@ const rateLimit = require('express-rate-limit')
const crawl = require('./crawler') const crawl = require('./crawler')
const parseHTML = require('./parser') const parseHTML = require('./parser')
const generateICS = require('./ics') const generateICS = require('./ics')
const { genericErrorHandler, checkURLParameter } = require('./middlewares') const { genericErrorHandler, checkURLParameter, forceSecure } = require('./middlewares')
const port = process.env.PORT const port = process.env.PORT
const certEndpoint = process.env.CERT_ENDPOINT || '' const certEndpoint = process.env.CERT_ENDPOINT || ''
const certSecret = process.env.CERT_SECRET const certSecret = process.env.CERT_SECRET || ''
const app = express() const app = express()
app.use(forceSecure)
app.set('view engine', 'ejs') app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, 'views')) app.set('views', path.join(__dirname, 'views'))
@ -21,9 +24,11 @@ app.use(express.static(path.join(__dirname, 'public')))
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))) app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
app.use(bodyParser()) app.use(bodyParser())
app.get(`/${certEndpoint}`, (req, res) => { if (certEndpoint) {
res.status(200).send(certSecret) app.get(`/${certEndpoint}`, (req, res) => {
}) res.status(200).send(certSecret)
})
}
app.get('/', (req, res) => { app.get('/', (req, res) => {
res.render('index') res.render('index')
@ -55,7 +60,8 @@ app.post('/download', async (req, res, next) => {
if (ics) { if (ics) {
return res return res
.contentType('text/calendar') .contentType('text/calendar')
.send(200, new Buffer(ics, 'utf8')) .status(200)
.send(new Buffer(ics, 'utf8'))
} }
} catch (err) { } catch (err) {
next(err) next(err)

View File

@ -30,7 +30,15 @@ const checkURLParameter = (req, res, next) => {
return next() return next()
} }
const forceSecure = (req, res, next) => {
if (req.headers['x-forwarded-proto'] === 'http') {
return res.status(301).redirect(`https://${req.headers.host}/`)
}
return next()
}
module.exports = { module.exports = {
genericErrorHandler, genericErrorHandler,
checkURLParameter, checkURLParameter,
forceSecure,
} }

View File

@ -5,8 +5,8 @@
"main": "lib/index.js", "main": "lib/index.js",
"scripts": { "scripts": {
"start": "node lib/index.js", "start": "node lib/index.js",
"start:dev": "PORT=3000 nodemon lib/index.js", "start:dev": "NODE_ENV=development PORT=3000 nodemon lib/index.js",
"start:dev:inspect": "PORT=3000 nodemon --inspect lib/index.js", "start:dev:inspect": "NODE_ENV=development PORT=3000 nodemon --inspect lib/index.js",
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"keywords": [ "keywords": [