-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathapp.js
279 lines (240 loc) · 7.37 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/* jslint es5: true */
const express = require('express');
const helmet = require('helmet');
const compression = require('compression');
const favicon = require('serve-favicon');
const morgan = require('morgan');
const methodOverride = require('method-override');
const expressSession = require('express-session');
const cookieParser = require('cookie-parser');
const errorHandler = require('errorhandler');
const rewrite = require('express-urlrewrite');
const http = require('http');
const https = require('https');
const fs = require('fs');
const multer = require('multer');
const path = require('path');
const rotator = require('file-stream-rotator');
const mongoose = require('mongoose');
const logger = require('./lib/loggers').getLogger();
const config = require('./config/config');
config.load();
const { configPath } = config;
const apiSettings = config.api;
const mongoConfig = config.mongo;
const appSettings = config.app;
// Load MongoDB object modeling tool
mongoose.connection.close();
// Load MongoDB models
require('./model/user');
require('./model/form');
require('./model/released-form');
require('./model/traveler');
require('./model/binder');
require('./model/history');
// Connect to mongo database
let mongoAddress = 'mongodb://';
mongoAddress += mongoConfig.server_address || 'localhost';
mongoAddress += `:${mongoConfig.server_port || '27017'}`;
mongoAddress += `/${mongoConfig.traveler_db || 'traveler'}`;
const mongoOptions = {
native_parser: true,
poolSize: 5,
connectTimeoutMS: 30000,
keepAlive: 1,
};
// Set authentication options if specified
if (mongoConfig.username !== undefined) {
mongoOptions.user = mongoConfig.username;
mongoOptions.pass = mongoConfig.password;
}
if (mongoConfig.auth) {
mongoOptions.auth = config.mongo.auth;
}
mongoose.connect(mongoAddress, mongoOptions);
mongoose.connection.on('connected', function() {
logger.info('Mongoose default connection opened.');
});
mongoose.connection.on('error', function(err) {
logger.info(`Mongoose default connection error: ${err}`);
});
mongoose.connection.on('disconnected', function() {
logger.info('Mongoose default connection disconnected');
});
// LDAP client
const adClient = require('./lib/ldap-client');
adClient.getDefaultClient(function(client, ldapClientCleanup) {
logger.info('ldap connection successfully tested');
ldapClientCleanup();
});
// CAS client
const auth = require('./lib/auth');
// api and web app
const api = express();
const app = express();
/* Configure Web Application */
app.locals.orgName = appSettings.org_name;
let access_logfile;
app.enable('strict routing');
if (app.get('env') === 'production') {
access_logfile = rotator.getStream({
filename: path.resolve(appSettings.log_dir, 'access.log'),
frequency: 'daily',
});
}
app.set('port', process.env.PORT || appSettings.app_port);
app.set('views', `${__dirname}/views`);
app.set('view engine', 'jade');
if (app.get('env') === 'production') {
app.use(
morgan('common', {
stream: access_logfile,
})
);
}
app.use(
helmet({
contentSecurityPolicy: false,
})
);
app.use(compression());
app.use(express.static(path.join(__dirname, 'public')));
app.use(favicon(`${__dirname}/public/favicon.ico`));
if (app.get('env') === 'development') {
app.use(morgan('common'));
}
app.use(methodOverride());
app.use(cookieParser());
app.use(
expressSession({
secret: appSettings.cookie_sec || 'traveler_secret',
resave: true,
saveUninitialized: false,
cookie: {
maxAge: appSettings.cookie_life || 28800000,
},
})
);
app.use(
multer({
dest: config.uploadPath,
limits: {
files: 1,
fileSize: (config.app.upload_size || 10) * 1024 * 1024,
},
})
);
app.use(express.json({ limit: config.app.body_max_size || '1mb' }));
app.use(express.urlencoded({ extended: true }));
app.use(auth.proxied);
app.use(auth.sessionLocals);
if (app.get('env') === 'development') {
app.use(errorHandler());
}
// apply app alias routing if any
if (appSettings.alias) {
const fromList = Object.keys(appSettings.alias);
for (let i = 0; i < fromList.length; i += 1) {
const from = fromList[i];
const to = appSettings.alias[from];
logger.info(`Route ${from} to ${to}`);
app.use(rewrite(from, to));
}
}
const routes = require('./routes');
require('./routes/main')(app);
require('./routes/form')(app);
require('./routes/form-management')(app);
require('./routes/traveler')(app);
require('./routes/traveler-note')(app);
require('./routes/binder')(app);
require('./routes/report')(app);
require('./routes/admin')(app);
require('./routes/review')(app);
require('./routes/user')(app);
require('./routes/group')(app);
require('./routes/profile')(app);
require('./routes/device')(app);
require('./routes/ldaplogin')(app);
require('./routes/doc')(app);
app.get('/api', function(req, res) {
res.render('api', {
prefix: req.proxied ? req.proxied_prefix : '',
});
});
// app.get('/', auth.ensureAuthenticated, routes.main);
app.get('/login', auth.ensureAuthenticated, function(req, res) {
if (req.session.userid) {
return res.redirect(req.proxied ? auth.proxied_service : '/');
}
// something wrong
return res.send(400, 'please enable cookie in your browser');
});
app.get('/logout', routes.logout);
app.get('/apis', function(req, res) {
res.redirect(`https://${req.host}:${api.get('port')}${req.originalUrl}`);
});
// Start application using settings
const appPort = appSettings.app_port;
let server;
if (appSettings.ssl_key) {
const appCredentials = {
key: fs.readFileSync(`./${configPath}/${appSettings.ssl_key}`),
cert: fs.readFileSync(`./${configPath}/${appSettings.ssl_cert}`),
};
server = https.createServer(appCredentials, app).listen(appPort, function() {
logger.info(`Express server listening on ssl port ${app.get('port')}`);
});
} else {
server = http.createServer(app).listen(appPort, function() {
logger.info(`Express server listening on port ${app.get('port')}`);
});
}
/* Configure REST API */
const apiPort = apiSettings.app_port;
api.enable('strict routing');
api.set('port', process.env.APIPORT || apiPort);
api.use(helmet());
api.use(morgan('common'));
// api.use(express.logger({stream: access_logfile}));
api.use(express.json());
api.use(express.urlencoded({ extended: true }));
api.use(auth.basicAuth);
api.use(compression());
require('./routes/api')(api);
// Start Api using settings
let apiserver;
if (apiSettings.ssl_key) {
const apiCredentials = {
key: fs.readFileSync(`./${configPath}/${apiSettings.ssl_key}`),
cert: fs.readFileSync(`./${configPath}/${apiSettings.ssl_cert}`),
};
apiserver = https
.createServer(apiCredentials, api)
.listen(api.get('port'), function() {
logger.info(`API server listening on ssl port ${api.get('port')}`);
});
} else {
apiserver = http.createServer(api).listen(apiPort, function() {
logger.info(`API server listening on port ${api.get('port')}`);
});
}
// When the node.js application is closed.
function cleanup() {
server._connections = 0;
apiserver._connections = 0;
mongoose.connection.close();
server.close(function() {
apiserver.close(function() {
logger.info('web and api servers close.');
// Close db connections, other chores, etc.
process.exit();
});
});
setTimeout(function() {
logger.error('Could not close connections in time, forcing shut down');
process.exit(1);
}, 30 * 1000);
}
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);