From 2c21b0db36643770d64b2627c74c5bf78b0f514f Mon Sep 17 00:00:00 2001 From: Sebastian Tanase Date: Sun, 17 Oct 2021 10:04:50 +0200 Subject: [PATCH] Add ssl support --- README.md | 6 ++++++ app.js | 27 +++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d66bd3c..1008a76 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,12 @@ If you need to apply basic HTTP authentication, you can set user name and passwo Also, you may have to **set permissions** for your `node_modules` folder. Refer [this](https://docs.npmjs.com/getting-started/fixing-npm-permissions). +If you need to use SSL, you can pass the private key and certificat through environment variables: + + SSL_CERT=/path/to/ssl_certificate SSL_KEY=/path/to/ssl_private_key + +Make sure node has the correct **permissions** to read the certificate and the key. + If you need to autosave your changes to crontab directly: crontab-ui --autosave diff --git a/app.js b/app.js index 9ff5729..7c71cfd 100755 --- a/app.js +++ b/app.js @@ -5,6 +5,8 @@ var crontab = require("./crontab"); var restore = require("./restore"); var moment = require('moment'); var basicAuth = require('express-basic-auth'); +var http = require('http'); +var https = require('https'); var path = require('path'); var mime = require('mime-types'); @@ -32,6 +34,22 @@ if (BASIC_AUTH_USER && BASIC_AUTH_PWD) { })) } +// ssl credentials +var credentials = { + key: process.env.SSL_KEY ? fs.readFileSync(process.env.SSL_KEY) : '', + cert: process.env.SSL_CERT ? fs.readFileSync(process.env.SSL_CERT) : '', +} + +if ( + (credentials.key && !credentials.cert) || + (credentials.cert && !credentials.key) +) { + console.error('Please provide both SSL_KEY and SSL_CERT'); + process.exit(1); + } + +var startHttpsServer = credentials.key && credentials.cert; + // include the routes var routes = require("./routes").routes; var routes_relative = require("./routes").relative @@ -238,7 +256,10 @@ process.on('SIGTERM', function() { process.exit(); }) -app.listen(app.get('port'), app.get('host'), function() { +var server = startHttpsServer ? + https.createServer(credentials, app) : http.createServer(app); + +server.listen(app.get('port'), app.get('host'), function() { console.log("Node version:", process.versions.node); fs.access(crontab.db_folder, fs.W_OK, function(err) { if(err){ @@ -277,5 +298,7 @@ app.listen(app.get('port'), app.get('host'), function() { crontab.reload_db(); } - console.log("Crontab UI is running at http://" + app.get('host') + ":" + app.get('port') + base_url); + + var protocol = startHttpsServer ? "https" : "http"; + console.log("Crontab UI is running at " + protocol + "://" + app.get('host') + ":" + app.get('port') + base_url); });