-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
277 lines (232 loc) · 7.57 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
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
'use strict';
const config = require('config');
const log = require('npmlog');
log.level = config.log.level;
const pathlib = require('path');
const express = require('express');
const app = express();
const flash = require('connect-flash');
const session = require('express-session');
const MongoStore = require('connect-mongo');
const routes = require('./lib/routes');
const cookieParser = require('cookie-parser');
const morgan = require('morgan');
const compression = require('compression');
const passport = require('passport');
const fs = require('fs');
const https = require('https');
const http = require('http');
const tools = require('./lib/tools');
const db = require('./lib/db');
const st = require('st');
const packageInfo = require('./package.json');
const moment = require('moment');
const urllib = require('url');
moment.locale('et');
const csrf = require('csurf')({
cookie: true
});
const mount = st({
path: pathlib.join(__dirname, 'www', 'static'),
url: '/',
dot: false,
index: false,
passthrough: true,
cache: {
// specify cache:false to turn off caching entirely
content: {
max: 1024 * 1024 * 64
}
},
// gzip is handled by express
gzip: false
});
let server;
// Setup SSL
if (config.web.ssl) {
config.web.ssl.key = fs.readFileSync(config.web.ssl.key, 'utf-8');
config.web.ssl.cert = fs.readFileSync(config.web.ssl.cert, 'utf-8');
if (config.web.ssl.ca) {
config.web.ssl.ca = [].concat(config.web.ssl.ca).map(ca => fs.readFileSync(ca, 'utf-8'));
}
}
// HTTP port to listen
app.set('port', config.web.port);
// do not expose express version
app.disable('x-powered-by');
// Define path to EJS templates
app.set('views', pathlib.join(__dirname, 'www', 'views'));
// Redirect to specified hostname if required
app.use((req, res, next) => {
if (!config.web.forceDomain) {
return next();
}
if (req.header('host') === config.web.forceDomain) {
next();
} else {
res.redirect(301, (config.web.forceProtocol || (config.web.ssl ? 'https:' : 'http:')) + '//' + config.web.forceDomain + req.path);
}
});
// Use gzip compression
app.use(
compression({
filter: (req, res) => {
if (res && req.path === '/updates_feed') {
return false;
} else {
return compression.filter(req, res);
}
}
})
);
// if res.forceCharset is set, convert ecoding for output
// this is needed to serve non-utf8 transactions
app.use(require('./lib/forcecharset'));
// Define static content path
app.use((req, res, next) => {
mount(req, res, () => {
next();
});
});
// Parse cookies
app.use(cookieParser(config.session.secret));
// Parse POST requests. We need to use homecooked parser as the input might
// include non-utf8 input that needs to be converted to utf8
app.use(require('./lib/bodyparser'));
// detect transaction information, bank type, language etc.
app.use(tools.checkEncoding);
// setup session handling, store everything to MongoDB
app.use(
session({
store: MongoStore.create({
mongoUrl: config.mongodb.url,
ttl: config.session.ttl
}),
secret: config.session.secret,
saveUninitialized: true,
resave: false
})
);
// setup flash messages
app.use(flash());
// setup user handling
app.use(passport.initialize());
app.use(passport.session());
// Log requests to console
app.use(
morgan(config.log.interface, {
stream: {
write: message => {
message = (message || '').toString();
if (message) {
log.info('HTTP', message.replace('\n', '').trim());
}
}
},
skip: (req, res) => {
// ignore ping requests
if (res && req.query && req.query.monitor === 'true') {
return true;
}
return false;
}
})
);
// Use EJS template engine
app.set('view engine', 'ejs');
app.use((...args) => {
if (/^\/(api|banklink)\//.test(args[0].url)) {
// skip CSRF check for api calls
return args[2]();
}
if (args[0].method === 'POST' && /^\/project\/[a-f0-9]{24}\b/.test(args[0].url)) {
return args[2]();
}
return csrf(...args);
});
app.use((req, res, next) => {
db.database.collection('user').findOne({ role: 'admin' }, { projection: { _id: true, username: true, role: true } }, (err, admin) => {
if (err) {
return next(err);
}
res.locals.adminUser = admin;
return next();
});
});
app.use((req, res, next) => {
res.locals.csrfToken = req.csrfToken && req.csrfToken();
db.database.collection('settings').findOne({ env: process.env.NODE_ENV || 'development' }, (err, settings) => {
if (err) {
return next(err);
}
settings = settings || {};
let urlParts = urllib.parse(settings.url || '/');
res.locals.logoUrl = req.logoUrl = 'logo' in settings ? settings.logo : config.logoUrl;
res.locals.proto = req.siteProto =
(urlParts.protocol ? urlParts.protocol.substr(0, urlParts.protocol.length - 1) : '') || config.proto || req.protocol || 'http';
res.locals.hostname = req.siteHostname = (urlParts.host || config.hostname || (req.headers && req.headers.host) || 'localhost').replace(
/:(80|443)$/,
''
);
res.locals.title = req.siteTitle = settings.title || config.title || packageInfo.name;
res.locals.packageTitle = packageInfo.name;
res.locals.user = req.user;
res.locals.googleAnalyticsID = config.googleAnalyticsID;
req.emailName = 'emailName' in settings ? settings.emailName : settings.title || req.siteTitle;
req.emailAddress = settings.emailAddress || config.mail.defaults.from || 'pangalink@' + req.siteHostname;
res.locals.version = packageInfo.version;
next();
});
});
app.use((req, res, next) => {
res.locals.messages = {
success: req.flash('success'),
error: req.flash('error'),
info: req.flash('info')
};
next();
});
// Use routes from routes.js
routes(app);
// create server instance
if (config.web.ssl) {
server = https.createServer(config.web.ssl, app);
} else {
server = http.createServer(app);
}
server.on('error', err => {
log.error('SERVER', err);
process.exit(1);
});
// open database
db.init()
.then(() => {
log.info('DB', 'Database opened');
server.listen(app.get('port'), config.web.host, () => {
log.info('SERVER', 'Web server running on port ' + app.get('port'));
// downgrade user and group if needed
if (config.group) {
try {
process.setgid(config.group);
log.info('App', 'Changed group to "%s" (%s)', config.group, process.getgid());
} catch (E) {
log.error('App', 'Failed to change group to "%s" (%s)', config.group, E.message);
return process.exit(1);
}
}
if (config.user) {
try {
process.setuid(config.user);
log.info('App', 'Changed user to "%s" (%s)', config.user, process.getuid());
} catch (E) {
log.error('App', 'Failed to change user to "%s" (%s)', config.user, E.message);
return process.exit(1);
}
}
});
return;
})
.catch(err => {
log.error('DB', err);
process.exit(1);
});