Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
291 lines (242 loc) · 8.46 KB
/
Copy pathapp.js
File metadata and controls
291 lines (242 loc) · 8.46 KB
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
280
281
282
283
284
285
286
287
288
289
290
291
const express = require('express');
const path = require('path');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const compression = require('compression');
const methodOverride = require('method-override');
const handlebars = require('handlebars');
const layouts = require('handlebars-layouts');
const handlebarsWax = require('handlebars-wax');
const { Configuration } = require('@hpi-schul-cloud/commons');
const { initializeSessionStorage } = require('./helpers/sessionStorage');
const { staticAssetsMiddleware } = require('./middleware/assets');
const { version } = require('./package.json');
const {
filterLog,
nonceValueSet,
prometheus,
tokenInjector,
duplicateTokenHandler,
csrfErrorHandler,
csrfProtection,
logger,
sha,
} = require('./helpers');
const authHelper = require('./helpers/authentication');
const securityHeaders = require('./middleware/security_headers');
const cors = require('./middleware/cors');
const handlebarsHelper = require('./helpers/handlebars');
const setTheme = require('./helpers/theme');
const controllers = require('./controllers');
const i18nMiddleware = require('./middleware/i18n');
const datetimeMiddleware = require('./middleware/datetime');
const PUBLIC_BACKEND_URL = Configuration.get('PUBLIC_BACKEND_URL');
const API_HOST = Configuration.get('API_HOST'); // where undefined before
const KEEP_ALIVE = Configuration.get('REQUEST_OPTION__KEEP_ALIVE'); // where undefined before
const SC_DOMAIN = Configuration.get('SC_DOMAIN');
const SC_THEME = Configuration.get('SC_THEME');
const JWT_SHOW_TIMEOUT_WARNING_SECONDS = Configuration.get('JWT_SHOW_TIMEOUT_WARNING_SECONDS');
const MAXIMUM_ALLOWABLE_TOTAL_ATTACHMENTS_SIZE_BYTE = Configuration.get(
'MAXIMUM_ALLOWABLE_TOTAL_ATTACHMENTS_SIZE_BYTE',
);
const JWT_TIMEOUT_SECONDS = Configuration.get('JWT_TIMEOUT_SECONDS');
const setupApp = async () => {
const app = express();
// setup prometheus metrics
prometheus(app);
// set custom response header for ha proxy
if (KEEP_ALIVE) {
app.use((req, res, next) => {
res.setHeader('Connection', 'Keep-Alive');
next();
});
}
// disable x-powered-by header
app.disable('x-powered-by');
// set security headers
app.use(securityHeaders);
// generate nonce value
if (Configuration.get('CORS')) {
app.use(nonceValueSet);
}
// set cors headers
app.use(cors);
app.use(compression());
app.set('trust proxy', true);
const themeName = SC_THEME;
const wax = handlebarsWax(handlebars)
.partials(path.join(__dirname, 'views/**/*.{hbs,js}'))
.helpers(layouts)
.helpers(handlebarsHelper.helpers(app));
wax.partials(path.join(__dirname, `theme/${themeName}/views/**/*.{hbs,js}`));
const viewDirs = [path.join(__dirname, 'views')];
viewDirs.unshift(path.join(__dirname, `theme/${themeName}/views/`));
app.set('views', viewDirs);
app.engine('hbs', wax.engine);
app.set('view engine', 'hbs');
app.set('view cache', true);
if (Configuration.get('FEATURE_MORGAN_LOG_ENABLED')) {
let morganLogFormat = Configuration.get('MORGAN_LOG_FORMAT');
const noColor = Configuration.has('NO_COLOR') && Configuration.get('NO_COLOR');
if (morganLogFormat === 'dev' && noColor) {
morganLogFormat = ':method :url :status :response-time ms - :res[content-length]';
}
app.use(morgan(morganLogFormat));
}
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));
app.use(cookieParser());
staticAssetsMiddleware(app);
await initializeSessionStorage(app);
// add res.$t method for i18n with users prefered language
app.use(i18nMiddleware);
// CSRF middlewares
if (Configuration.get('FEATURE_CSRF_ENABLED')) {
app.use(duplicateTokenHandler);
app.use(csrfProtection);
app.use(tokenInjector);
// there follows an csrf error handler below...
}
// Custom flash middleware
app.use(async (req, res, next) => {
// if there's a flash message in the session request, make it available in the response, then delete it
res.locals.notification = req.session.notification;
res.locals.inline = req.query.inline || false;
setTheme(res);
res.locals.domain = SC_DOMAIN;
res.locals.production = req.app.get('env') === 'production';
res.locals.env = req.app.get('env') || false; // TODO: ist das false hier nicht quatsch?
res.locals.JWT_SHOW_TIMEOUT_WARNING_SECONDS = Number(
JWT_SHOW_TIMEOUT_WARNING_SECONDS,
);
res.locals.MAXIMUM_ALLOWABLE_TOTAL_ATTACHMENTS_SIZE_BYTE = Number(
MAXIMUM_ALLOWABLE_TOTAL_ATTACHMENTS_SIZE_BYTE,
);
// eslint-disable-next-line max-len
res.locals.MAXIMUM_ALLOWABLE_TOTAL_ATTACHMENTS_SIZE_MEGABYTE = MAXIMUM_ALLOWABLE_TOTAL_ATTACHMENTS_SIZE_BYTE / 1024 / 1024;
res.locals.JWT_TIMEOUT_SECONDS = Number(JWT_TIMEOUT_SECONDS);
res.locals.API_HOST = PUBLIC_BACKEND_URL || `${API_HOST}/`;
res.locals.version = version;
res.locals.sha = sha;
delete req.session.notification;
return next();
});
app.use(methodOverride('_method')); // for GET requests
app.use(
methodOverride((req, res, next) => {
// for POST requests
if (
req.body
&& typeof req.body === 'object'
&& '_method' in req.body
) {
// eslint-disable-next-line no-underscore-dangle
const method = req.body._method;
// eslint-disable-next-line no-underscore-dangle
delete req.body._method;
return method;
}
return undefined;
}),
);
app.use(datetimeMiddleware);
const redirectUrl = Configuration.get('ROOT_URL_REDIRECT');
if (redirectUrl !== '') {
app.get('/', (req, res, next) => {
res.redirect(redirectUrl);
});
}
// Initialize the modules and their routes
app.use(controllers);
// catch 404 and forward to error handler
app.use((req, res, next) => {
const url = req.originalUrl || req.url;
const err = new Error(`Page Not Found ${url}`);
err.status = 404;
next(err);
});
// error handlers
if (Configuration.get('FEATURE_CSRF_ENABLED')) {
app.use(csrfErrorHandler);
}
// no statusCode exist for this cases
const isTimeoutError = (err) => err
&& err.message
&& (err.message.includes('ESOCKETTIMEDOUT')
|| err.message.includes('ECONNREFUSED')
|| err.message.includes('ETIMEDOUT'));
const errorHandler = (err) => {
const error = err.error || err;
const status = error.status || error.statusCode || 500;
error.statusCode = status;
// prevent logging jwts and x-api-keys
if (error.options && error.options.headers) {
delete error.options.headers;
}
return { error, status };
};
app.use((err, req, res, next) => {
const { error, status } = errorHandler(err);
if (!res.locals) {
res.locals = {};
}
if (Configuration.get('FEATURE_LOG_REQUEST') === true) {
const reqInfo = {
url: req.originalUrl || req.url,
method: req.originalMethod || req.method,
params: req.params,
body: req.body,
};
error.requestInfo = filterLog(reqInfo);
}
if (res.locals.currentUser) {
res.locals.loggedin = true;
const { _id, schoolId, roles } = res.locals.currentUser;
error.currentUser = {
userId: _id,
schoolId,
roles: (roles || []).map((r) => r.name),
};
}
if (error.message) {
res.setHeader('error-message', error.message);
res.locals.message = error.message;
} else {
res.locals.message = `Error with statusCode ${status}`;
}
// override with try again message by timeouts
if (isTimeoutError(error)) {
const baseRoute = typeof err.options.baseUrl === 'string'
? err.options.baseUrl.slice(0, -1)
: '';
const route = baseRoute + err.options.uri;
const routeMessage = res.locals.production
? ''
: ` beim Aufruf der Route ${route}`;
res.locals.message = `Es ist ein Fehler aufgetreten${routeMessage}. Bitte versuche es erneut.`;
}
// do not show full errors in production mode
res.locals.error = req.app.get('env') !== 'development' ? err : { status };
logger.error(error);
// keep sidebar restricted in error page
authHelper.restrictSidebar(req, res);
// render the error page
return res.status(status).render('lib/error', {
// For errors coming from middlewares which are registered before i18nMiddleware, res.$t is not available. Thus the check below.
pageTitle: res.$t?.('lib.error.headline.pageTitle'),
loggedin: res.locals.loggedin,
inline: res.locals.inline ? true : !res.locals.loggedin,
});
});
process.on('unhandledRejection', (err) => {
const { error } = errorHandler(err);
error.message = `unhandledRejection: ${error.message}`;
logger.error(error);
});
return app;
};
module.exports = async () => {
const app = await setupApp();
return app;
};