This repository has been archived by the owner on Dec 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathserver.js
77 lines (63 loc) · 2.1 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
'use strict';
var util = require('util');
var http = require('http');
var https = require('https');
var fs = require('fs');
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('express-cors');
var expressValidator = require('express-validator');
var HttpStatus = require('http-status-codes');
var api = require('./api');
var utils = require('./utils');
var port = process.env.PORT || 443;
var app = express();
var serverOptions = {};
if (utils.isProd) {
// in prod, enforce secured connections
app.use((req, res, next) => {
if (!req.headers['x-arr-ssl']) {
return res.status(HttpStatus.BAD_REQUEST).json({ error: 'use https'});
}
return next();
});
}
else { // dev
// accept self-signed cdertificates only in development
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
serverOptions.cert = fs.readFileSync('./cert/server.crt');
serverOptions.key = fs.readFileSync('./cert/server.key');
}
app.use(cors());
app.use(bodyParser.json());
app.use(expressValidator());
// middleware to log all incoming requests
app.use((req, res, next) => {
console.log(`url: ${req.method} ${req.originalUrl} ${util.inspect(req.body || {})}, headers: ${util.inspect(req.headers)}`);
return next();
});
// attach API to server
app.use('/api', api);
app.get('/', (req, res) => {
return res.end(`Supply Chain Service in on...`);
});
if (utils.isProd) {
// in prod we will use Azure's certificate to use ssl.
// so no need to use https here with a custom certificate for now.
// enforcing https in prod is being done on the first middleware (see above)
http.createServer(app).listen(port, err => {
if (err) return console.error(err);
console.info(`server is listening on port ${port}`);
});
}
else {
// this is development environment, use a local ssl server with self signed certificates
https.createServer(serverOptions, app).listen(port, err => {
if (err) return console.error(err);
console.info(`server is listening on port ${port}`);
});
}
process.on('uncaughtException', err => {
console.error(`uncaught exception: ${err.message}`);
setTimeout(() => process.exit(1), 1000);
});