71 lines
2.0 KiB
JavaScript
71 lines
2.0 KiB
JavaScript
const http = require('http');
|
|
const https = require('https');
|
|
const httpProxy = require('http-proxy');
|
|
const cors = require('cors');
|
|
const express = require('express');
|
|
const cookieParser = require('cookie-parser');
|
|
const fs = require('fs');
|
|
const Config = require('./config.js');
|
|
|
|
const UserInterface = require('./user.js');
|
|
const TodoInterface = require('./todo.js');
|
|
|
|
let credentials = {};
|
|
|
|
if (Config.config.https) {
|
|
if (fs.existsSync(Config.config.cert) && fs.existsSync(Config.config.cert_key)) {
|
|
credentials.key = fs.readFileSync(Config.config.cert_key);
|
|
credentials.cert = fs.readFileSync(Config.config.cert);
|
|
}
|
|
else {
|
|
console.error('could not load certs')
|
|
process.exit()
|
|
}
|
|
}
|
|
|
|
let app = express();
|
|
|
|
app.use(cors());
|
|
app.use(cookieParser());
|
|
|
|
// force https
|
|
app.use((req, res, next) => {
|
|
if (Config.config.https) {
|
|
if (req.headers['x-forwarded-proto'] !== 'https') {
|
|
return res.redirect(`https://${req.headers.host}${req.url}`);
|
|
}
|
|
}
|
|
return next();
|
|
});
|
|
|
|
if (!Config.config.secret) {
|
|
console.error('No password secret found. please set `secret` in config.json');
|
|
process.exit();
|
|
} else if (Config.config.https && Config.config.secret == 'TEST_SECRET') {
|
|
console.error('please do not use the testing secret in production.');
|
|
process.exit();
|
|
}
|
|
|
|
app.use('/api/user', UserInterface.router);
|
|
app.use('/api/todo', TodoInterface.router);
|
|
|
|
if (Config.config.frontend_url) {
|
|
const proxy = httpProxy.createProxyServer({})
|
|
app.use('/', (req, res) => {
|
|
return proxy.web(req, res, {
|
|
target: Config.config.frontend_url
|
|
})
|
|
});
|
|
}
|
|
|
|
if (Config.config.https) {
|
|
var server = https.createServer(credentials, app);
|
|
server.listen(Config.config.port || 8080);
|
|
} else {
|
|
var server = http.createServer(app);
|
|
server.listen(Config.config.port || 8080);
|
|
}
|
|
console.log(
|
|
`listening on port ${Config.config.port || 8080}` + ` with https ${Config.config.https ? 'enabled' : 'disabled'}`
|
|
);
|