-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
222 lines (170 loc) · 4.97 KB
/
app.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
const dotenv = require('dotenv').config();
const fs = require('fs');
const createError = require('http-errors');
const debug = require('debug')('sh:server');
const http = require('http');
const https = require('https');
const express = require('express');
const expressSession = require('express-session');
const mysqlStore = require('express-mysql-session')(expressSession);
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const router = require('./routes/routes');
const cors = require('cors');
const Socket = require('./modules/socket');
// APP
const app = express();
// View engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Logging
app.use(logger('dev'));
if ( process.env.APP_LOG && process.env.APP_LOG !== 'false') {
app.use(logger('common', {
stream: fs.createWriteStream(process.env.APP_LOG, {flags: 'a'})
}));
}
// CORS
app.use(cors());
app.options('*', cors());
// Express features
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Sessions
const session = expressSession({
key: 'secret_hitler_session',
resave: false, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
secret: process.env.APP_SESSION_SECRET,
store: new mysqlStore({
host: process.env.DB_HOST || 'localhost',
port: process.env.DB_PORT || 3306,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
}),
cookie: {
sameSite: true
}
});
app.use( session );
// Define routes.
app.use( '/', router );
// Catch 404 and forward to error handler.
app.use(function(req, res, next) {
next(createError(404));
});
// Error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = process.env.NODE_ENV === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error', {
title: 'Error | Secret Hitler'
});
});
// Start HTTP(S) server.
let port,
server,
usingPassenger = ( typeof(PhusionPassenger) != 'undefined' ),
usingSSL = ( process.env.SSL && process.env.SSL === 'true' );
if ( usingPassenger ) {
PhusionPassenger.configure({
autoInstall: false
});
port = 'passenger';
server = app.listen( port );
} else if ( usingSSL ) {
port = normalizePort( process.env.SSL_PORT );
app.set('port', port );
// HTTPS
server = https.createServer({
cert: fs.readFileSync( process.env.SSL_CERTIFICATE, 'utf-8'),
key: fs.readFileSync( process.env.SSL_KEY, 'utf-8')
}, app).listen( port );
} else {
port = normalizePort( process.env.APP_PORT );
app.set('port', port );
server = http.createServer( {}, app ).listen( port );
}
server.on( 'error', onError );
server.on( 'listening', onListening );
// Sockets server listens on a separate port.
let socketPort = normalizePort( process.env.WS_PORT ),
socketServer;
if ( socketPort === port ) {
socketServer = server;
} else if ( usingSSL ) {
socketServer = https.createServer({
cert: fs.readFileSync( process.env.SSL_CERTIFICATE, 'utf-8'),
key: fs.readFileSync( process.env.SSL_KEY, 'utf-8')
}, app).listen( socketPort );
} else {
socketServer = http.createServer( {}, app ).listen( socketPort );
}
Socket.setup( socketServer, session );
// Backup HTTP server redirects to SSH.
if ( usingSSL && !usingPassenger ) {
const httpPort = normalizePort( process.env.APP_PORT );
const httpApp = express()
.set('port', httpPort)
.get('*', function(req, res) {
res.redirect( process.env.APP_URL + req.url);
});
const httpServer = http.createServer( {}, httpApp ).listen( httpPort );
}
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
const port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
const bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
const addr = server.address();
const bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
module.exports = app;