-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
280 lines (224 loc) · 7.41 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
280
const rootPrefix = '.';
const express = require('express'),
path = require('path'),
createNamespace = require('continuation-local-storage').createNamespace,
morgan = require('morgan'),
bodyParser = require('body-parser'),
basicAuth = require('basic-auth'),
helmet = require('helmet'),
customUrlParser = require('url'),
cookieParser = require('cookie-parser'),
exphbs = require('express-handlebars');
const responseHelper = require(rootPrefix + '/lib/formatter/response'),
logger = require(rootPrefix + '/lib/logger/customConsoleLogger'),
customMiddleware = require(rootPrefix + '/helpers/customMiddleware'),
adminRoutes = require(rootPrefix + '/routes/admin'),
basicHelper = require(rootPrefix + '/helpers/basic'),
errorConfig = require(rootPrefix + '/config/apiErrorConfig'),
cookieHelper = require(rootPrefix + '/helpers/cookie'),
coreConstants = require(rootPrefix + '/config/coreConstants'),
handlebarHelper = require(rootPrefix + '/helpers/handlebar'),
sanitizer = require(rootPrefix + '/helpers/sanitizer');
const requestSharedNameSpace = createNamespace('pepoAdminNameSpace');
morgan.token('id', function getId(req) {
return req.id;
});
morgan.token('endTime', function getendTime(req) {
const hrTime = process.hrtime();
return hrTime[0] * 1000 + hrTime[1] / 1000000;
});
morgan.token('currentDateTime', function getCurrentDateTime(req) {
return basicHelper.logDateFormat();
});
const startRequestLogLine = function(req, res, next) {
const message =
'[' +
req.id +
']' +
"Started '" +
customUrlParser.parse(req.originalUrl).pathname +
"' '" +
req.method +
"' at " +
basicHelper.logDateFormat() +
' from agent ' +
req.headers['user-agent'];
logger.info(message);
next();
};
/**
* Assign params
*
* @param req
* @param res
* @param next
*/
const assignParams = function(req, res, next) {
// IMPORTANT NOTE: Don't assign parameters before sanitization
// Also override any request params, related to signatures
// And finally assign it to req.decodedParams
req.decodedParams = Object.assign(getRequestParams(req), req.decodedParams);
next();
};
/**
* Get request params
*
* @param req
* @return {*}
*/
const getRequestParams = function(req) {
// IMPORTANT NOTE: Don't assign parameters before sanitization
if (req.method === 'POST') {
return req.body;
} else if (req.method === 'GET') {
return req.query;
}
return {};
};
// Set request debugging/logging details to shared namespace
const appendRequestDebugInfo = function(req, res, next) {
requestSharedNameSpace.run(function() {
requestSharedNameSpace.set('reqId', req.id);
requestSharedNameSpace.set('startTime', req.startTime);
next();
});
};
const basicAuthentication = function(req, res, next) {
if (!coreConstants.USE_BASIC_AUTH || req.url == '/health-checker') {
return next();
}
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
res.status(401);
return res.sendFile(path.join(__dirname + '/' + rootPrefix + '/public/401.html'));
}
let user = basicAuth(req);
if (!user || !user.name || !user.pass) {
return unauthorized(res);
}
if (user.name === coreConstants.PAD_BASIC_AUTH_USERNAME && user.pass === coreConstants.PAD_BASIC_AUTH_PASSWORD) {
return next();
} else {
return unauthorized(res);
}
};
// If the process is not a master
// Set worker process title
process.title = 'pepo admin node worker';
// Create express application instance
const app = express();
// Add id and startTime to request
app.use(customMiddleware());
// Load Morgan
app.use(
morgan('[:id][:currentDateTime] Completed with ":status" in :response-time ms - ":res[content-length] bytes"')
);
// Helmet helps secure Express apps by setting various HTTP headers.
app.use(helmet());
app.use(helmet.referrerPolicy({ policy: 'no-referrer' }));
//Setting view engine template handlebars
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'handlebars');
// Node.js body parsing middleware.
app.use(bodyParser.json());
// Parsing the URL-encoded data with the qs library (extended: true)
app.use(bodyParser.urlencoded({ extended: true }));
// Sanitize request body and query params
// NOTE: dynamic variables in URL will be sanitized in routes
app.use(sanitizer.sanitizeBodyAndQuery, assignParams);
app.use(basicAuthentication);
// Node.js cookie parsing middleware.
app.use(cookieParser(coreConstants.COOKIE_SECRET));
app.use(cookieHelper.setAdminCsrf());
//Helper is used to ease stringifying JSON
app.engine(
'handlebars',
exphbs({
defaultLayout: 'main',
helpers: handlebarHelper,
partialsDir: path.join(__dirname, 'views/partials'),
layoutsDir: path.join(__dirname, 'views/layouts')
})
);
const hbs = require('handlebars');
hbs.registerHelper('css', function() {
const css = connectAssets.options.helperContext.css.apply(this, arguments);
return new hbs.SafeString(css);
});
hbs.registerHelper('js', function() {
const js = connectAssets.options.helperContext.js.apply(this, arguments);
return new hbs.SafeString(js);
});
hbs.registerHelper('json', function(context) {
return JSON.stringify(context);
});
hbs.registerHelper('randomStr', function() {
return Math.random()
.toString(36)
.replace(/[^a-z]+/g, '');
});
hbs.registerHelper('with', function(context) {
return options.fn(context);
});
app.use(express.static(path.join(__dirname, 'public')));
app.use(appendRequestDebugInfo, startRequestLogLine);
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/public/pepo.html'));
});
/* Elb health checker request */
app.get('/health-checker', function(req, res, next) {
const performer = function() {
// 200 OK response needed for ELB Health checker
if (req.headers['user-agent'] === 'ELB-HealthChecker/2.0') {
return res.status(200).json(responseHelper.successWithData({}).toHash());
} else {
return res.status(404).json(
responseHelper
.error({
internal_error_identifier: 'r_a_h_c_1',
api_error_identifier: 'resource_not_found',
debug_options: {}
})
.toHash()
);
}
};
performer();
});
app.use('/admin', adminRoutes);
// connect-assets relies on to use defaults in config
const connectAssetConfig = {
paths: [path.join(__dirname, 'assets/css'), path.join(__dirname, 'assets/js')],
buildDir: path.join(__dirname, 'builtAssets'),
fingerprinting: true,
servePath: 'assets'
};
if (!coreConstants.isDevelopment) {
connectAssetConfig.servePath = coreConstants.PAD_CLOUD_FRONT_BASE_DOMAIN + '/' + coreConstants.appName + '/js-css';
connectAssetConfig.bundle = true;
connectAssetConfig.compress = true;
} else {
connectAssetConfig.servePath = 'builtAssets';
}
const connectAssets = require('connect-assets')(connectAssetConfig);
app.use(connectAssets);
// Catch 404 and forward to error handler
app.use(function(req, res, next) {
const message =
"Started '" +
customUrlParser.parse(req.originalUrl).pathname +
"' '" +
req.method +
"' at " +
basicHelper.logDateFormat() +
' from agent ' +
req.headers['user-agent'];
logger.info(message);
return res.sendFile(path.join(__dirname + '/public/404.html'));
});
// Error handler
app.use(function(err, req, res, next) {
logger.error('a_6', 'Something went wrong', err);
return res.sendFile(path.join(__dirname + '/public/500.html'));
});
module.exports = app;