-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
241 lines (197 loc) · 6.87 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
const rootPrefix = '.';
const express = require('express'),
path = require('path'),
createNamespace = require('continuation-local-storage').createNamespace,
morgan = require('morgan'),
bodyParser = require('body-parser'),
helmet = require('helmet'),
customUrlParser = require('url'),
URL = require('url').URL;
const requestSharedNameSpace = createNamespace('pepoApiNameSpace');
const responseHelper = require(rootPrefix + '/lib/formatter/response'),
logger = require(rootPrefix + '/lib/logger/customConsoleLogger'),
customMiddleware = require(rootPrefix + '/helpers/customMiddleware'),
apiVersions = require(rootPrefix + '/lib/globalConstant/apiVersions'),
createErrorLogsEntry = require(rootPrefix + '/lib/errorLogs/createEntry'),
errorLogsConstants = require(rootPrefix + '/lib/globalConstant/errorLogs'),
basicHelper = require(rootPrefix + '/helpers/basic'),
coreConstants = require(rootPrefix + '/config/coreConstants'),
sanitizer = require(rootPrefix + '/helpers/sanitizer');
const apiRoutes = require(rootPrefix + '/routes/api/index'),
storeRoutes = require(rootPrefix + '/routes/storeApi/index'),
webhookRoutes = require(rootPrefix + '/routes/webhooks/index'),
elbHealthCheckerRoute = require(rootPrefix + '/routes/internal/elb_health_checker');
const errorConfig = basicHelper.fetchErrorConfig(apiVersions.v1);
const pepoApiHostName = new URL(coreConstants.PA_DOMAIN).hostname;
const pepoStoreApiHostName = new URL(coreConstants.PA_STORE_DOMAIN).hostname;
morgan.token('id', function getId(req) {
return req.id;
});
morgan.token('pid', function getId(req) {
return process.pid;
});
morgan.token('endTime', function getendTime(req) {
return Date.now();
});
morgan.token('endDateTime', function getEndDateTime(req) {
return basicHelper.logDateFormat();
});
const startRequestLogLine = function(req, res, next) {
const message = [
"Started '",
customUrlParser.parse(req.originalUrl).pathname,
"' '",
req.method,
"' at ",
basicHelper.logDateFormat()
];
logger.step(message.join(''));
if (!basicHelper.isProduction()) {
logger.step(
'\nHEADERS FOR CURRENT REQUEST=====================================\n',
JSON.stringify(req.headers),
'\n========================================================'
);
}
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);
delete req.decodedParams.current_user;
delete req.decodedParams.user_login_cookie_value;
delete req.decodedParams.current_admin;
delete req.decodedParams.admin_login_cookie_value;
// IMPORTANT: Above keys are removed from decoded params as they are being set internally. Thus any such key coming from front end should not be respected.
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 setResponseHeader = async function(req, res, next) {
res.setHeader('Pragma', 'no-cache');
res.setHeader('Cache-Control', 'no-store, no-cache, max-age=0, must-revalidate, post-check=0, pre-check=0');
res.setHeader('Vary', '*');
res.setHeader('Expires', '-1');
res.setHeader('Last-Modified', new Date().toUTCString());
next();
};
// If the process is not a master.
// Set worker process title.
process.title = 'Pepo API node worker';
// Create express application instance.
const app = express();
// Add id and startTime to request.
app.use(customMiddleware());
// Load Morgan
app.use(
morgan(
'[:pid][:id][:endTime][' +
coreConstants.APP_NAME +
'] Completed with ":status" in :response-time ms at :endDateTime - ":res[content-length] bytes" - ":remote-addr" ":remote-user" - "HTTP/:http-version :method :url" - ":referrer" - ":user-agent"'
)
);
app.use(function(req, res, next) {
var data = '';
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.rawBody = data;
});
next();
});
// Helmet helps secure Express apps by setting various HTTP headers.
app.use(helmet());
// 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 }));
// Static file location.
app.use(express.static(path.join(__dirname, 'public')));
// Health checker.
app.use('/health-checker', elbHealthCheckerRoute);
// Start Request logging. Placed below static and health check to reduce logs.
app.use(appendRequestDebugInfo, startRequestLogLine);
// Set response headers.
app.use(setResponseHeader);
/**
* NOTE: API routes where first sanitize and then assign params.
*/
app.use('/api', sanitizer.sanitizeBodyAndQuery, assignParams, function(request, response, next) {
if (request.hostname === pepoApiHostName) {
apiRoutes(request, response, next);
} else if (request.hostname === pepoStoreApiHostName) {
storeRoutes(request, response, next);
} else {
next();
}
});
/**
* NOTE: OST webhooks where first assign params, validate signature and then sanitize the params
*/
app.use('/webhooks', webhookRoutes);
// Catch 404 and forward to error handler.
app.use(function(req, res, next) {
return responseHelper.renderApiResponse(
responseHelper.error({
internal_error_identifier: 'a_1',
api_error_identifier: 'resource_not_found',
debug_options: {}
}),
res,
errorConfig
);
});
// Error handler.
app.use(async function(err, req, res, next) {
let errorObject = null;
if (err.code == 'EBADCSRFTOKEN') {
logger.error('a_3', 'Bad CSRF TOKEN', err);
errorObject = responseHelper.error({
internal_error_identifier: 'a_3',
api_error_identifier: 'forbidden_api_request',
debug_options: {}
});
} else {
logger.error('a_2', 'Something went wrong', err);
errorObject = responseHelper.error({
internal_error_identifier: 'a_2',
api_error_identifier: 'something_went_wrong',
debug_options: { err: err }
});
await createErrorLogsEntry.perform(errorObject, errorLogsConstants.mediumSeverity);
logger.error(' In catch block of app.js', errorObject);
}
return responseHelper.renderApiResponse(errorObject, res, errorConfig);
});
module.exports = app;