forked from globex-recommendation/globex-ui
-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.ts
435 lines (357 loc) · 14.5 KB
/
server.ts
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
import 'zone.js/dist/zone-node';
import { ngExpressEngine } from '@nguniversal/express-engine';
import express from 'express';
import { join } from 'path';
import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { existsSync } from 'fs';
import { PaginatedProductsList } from 'src/app/models/product.model';
import { AxiosError } from 'axios';
import { get } from 'env-var';
import { v4 as uuidv4 } from 'uuid';
import { LogLevel } from 'angular-auth-oidc-client';
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
console.log("Express server side setup is complete....")
const server = express();
const distFolder = join(process.cwd(), 'dist/globex-web/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
//setup pathways
//client UI to SSR calls
const ANGULR_API_GETPAGINATEDPRODUCTS = '/api/getPaginatedProducts';
const ANGULR_API_GETPAGINATEDPRODUCTS_LIMIT = 8;
const ANGULR_API_GETRECOMMENDEDPRODUCTS = '/api/getRecommendedProducts';
const ANGULR_API_TRACKUSERACTIVITY = '/api/trackUserActivity';
const ANGULR_API_GETPRODUCTDETAILS_FOR_IDS = '/api/getProductDetailsForIds';
const ANGULR_HEALTH = '/health';
const ANGULR_API_CART = '/api/cart';
const ANGULR_API_LOGIN = '/api/login';
const ANGULR_API_CUSTOMER = '/api/customer';
const ANGULAR_API_ORDER = '/api/order';
const ANGULAR_API_AUTHCONFIG = '/api/getAuthConfig';
const RECOMMENDED_PRODUCTS_LIMIT = get('RECOMMENDED_PRODUCTS_LIMIT').default(5).asInt();
const NODE_ENV = get('NODE_ENV').default('dev').asEnum(['dev', 'prod']);
const LOG_LEVEL = get('LOG_LEVEL').asString();
// HTTP and WebSocket traffic both use this port
const PORT = get('PORT').default(4200).asPortNumber();
// external micro services typically running on OpenShift
const API_MANAGEMENT_FLAG = get('API_MANAGEMENT_FLAG').default("NO").asString();
const API_TRACK_USERACTIVITY = get('API_TRACK_USERACTIVITY').default('http://d8523dbb-977d-4d5c-be98-aef3da676192.mock.pstmn.io/track').asString();
const API_GET_PAGINATED_PRODUCTS = get('API_GET_PAGINATED_PRODUCTS').default('http://3ea8ea3c-2bc9-45ae-9dc9-73aad7d8eafb.mock.pstmn.io/services/products').asString();
const API_GET_PRODUCT_DETAILS_BY_IDS = get('API_GET_PRODUCT_DETAILS_BY_IDS').default('http://3ea8ea3c-2bc9-45ae-9dc9-73aad7d8eafb.mock.pstmn.io/services/product/list/').asString();
const API_CATALOG_RECOMMENDED_PRODUCT_IDS = get('API_CATALOG_RECOMMENDED_PRODUCT_IDS').default('http://e327d0a8-a4cc-4e60-8707-51a295f04f76.mock.pstmn.io/score/product').asString();
const API_CART_SERVICE = get('API_CART_SERVICE').default('').asString();
const API_CUSTOMER_SERVICE = get('API_CUSTOMER_SERVICE').default('').asString();
const API_ORDER_SERVICE = get('API_ORDER_SERVICE').asString();
//setup keycloak auth settings
const SSO_CUSTOM_CONFIG = get('SSO_CUSTOM_CONFIG').default('').asString();
const SSO_AUTHORITY = get('SSO_AUTHORITY').default('').asString();
const SSO_REDIRECT_LOGOUT_URI = get('SSO_REDIRECT_LOGOUT_URI').default('').asString();
const SSO_LOG_LEVEL = get('SSO_LOG_LEVEL').default(LogLevel.Error).asString();
//3SCALE INTEGRATION FOR AUTH KEY BASED AUTHENTICATION
const API_USER_KEY_NAME = get('USER_KEY').default('api_key').asString();
const API_USER_KEY_VALUE = get('API_USER_KEY_VALUE').default('8efad5cc78ecbbb7dbb8d06b04596aeb').asString();
// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
server.engine('html', ngExpressEngine({
bootstrap: AppServerModule
}));
server.set('view engine', 'html');
server.set('views', distFolder);
// Example Express Rest API endpoints
//const http = require('http');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')
const axios = require('axios');
if(API_MANAGEMENT_FLAG && API_MANAGEMENT_FLAG =='YES') {
axios.defaults.headers.common[API_USER_KEY_NAME] = API_USER_KEY_VALUE // for all requests
}
server.use(bodyParser.json());
server.use(cookieParser())
server.use(bodyParser.urlencoded({extended: true}) );
// Session handling
const sessions = new Map<string, Session>();
//Access Token parsing
var Buffer = require('buffer').Buffer;
//API Setup START
server.get(ANGULAR_API_AUTHCONFIG, (req, res) => {
res.send(
{
"SSO_CUSTOM_CONFIG_KEY" : SSO_CUSTOM_CONFIG,
"SSO_AUTHORITY_KEY": SSO_AUTHORITY,
"SSO_REDIRECT_LOGOUT_URI_KEY": SSO_REDIRECT_LOGOUT_URI,
"SSO_LOG_LEVEL_KEY": SSO_LOG_LEVEL
}
);
});
server.get(ANGULR_API_GETPAGINATEDPRODUCTS, (req, res) => {
var getProducts:PaginatedProductsList;
var myTimestamp = new Date().getTime().toString();
var url = API_GET_PAGINATED_PRODUCTS.toString();
var limit = req.query['limit'];
var page = req.query['page'];
axios.get(url, {params: { limit: limit, timestamp:myTimestamp , page: page } })
.then(response => {
getProducts = response.data;;
res.send(getProducts);
})
.catch(error => {
console.log("ANGULR_API_GETPAGINATEDPRODUCTS", error);
});
});
// Get Product Details for the comma separated Product IDs string
server.get(ANGULR_API_GETRECOMMENDEDPRODUCTS, (req, res) => {
var commaSeparatedProdIds;
var recommendedProducts= [];
var getRecommendedProducIdsURL = API_CATALOG_RECOMMENDED_PRODUCT_IDS;
var getProdDetailsByIdURL = API_GET_PRODUCT_DETAILS_BY_IDS;
var getRecommendedProducts;
axios
.get(getRecommendedProducIdsURL)
.then(response => {
getRecommendedProducts = response.data;
//get a list of Product Ids from the array sent
var prodArray = getRecommendedProducts.map(s=>s.productId);
commaSeparatedProdIds = prodArray.toString();
if (!commaSeparatedProdIds) {
return {};
}
return axios.get(getProdDetailsByIdURL.replace(':ids', commaSeparatedProdIds));
})
.then(response => {
var prodDetailsArray = response.data;
var returnData = getRecommendedProducts.map(t1 => ({...t1, ...prodDetailsArray.find(t2 => t2.itemId === t1.productId)}));
returnData = returnData.slice(0,RECOMMENDED_PRODUCTS_LIMIT);
res.send(returnData);
}).catch(error => { console.log("ANGULR_API_GETRECOMMENDEDPRODUCTS", error); });
});
// Get Product Details based on Product IDs
server.get(ANGULR_API_GETPRODUCTDETAILS_FOR_IDS, (req, res) => {
var commaSeparatedProdIds: string = req.query.productIds + "";
var url = API_GET_PRODUCT_DETAILS_BY_IDS.replace(':ids', commaSeparatedProdIds);
if (!commaSeparatedProdIds) {
res.send('[]')
return;
}
axios
.get(url)
.then(response => {
res.send(response.data);
})
.catch(error => { console.log("ANGULR_API_GETPRODUCTDETAILS_FOR_IDS", error); });
});
// Save user activity
server.post(ANGULR_API_TRACKUSERACTIVITY, (req, res) => {
var url = API_TRACK_USERACTIVITY;
axios
.post(url, req.body)
.then(response => {
res.send(response.data);
})
.catch(
(reason: AxiosError<{additionalInfo:string}>) => {
if (reason.response!.status === 400) {
// Handle 400
res.send("error:reason.response!.status " + reason.response!.status);
} else {
res.send("error:reason.response!.status " + reason.response!.status);
}
console.log("ANGULR_API_TRACKUSERACTIVITY AxiosError", reason.message)
}
);
});
// Get CART API call
server.get(ANGULR_API_CART + '/:cartId', (req, res) => {
let cartId = req.params.cartId;
axios.get(API_CART_SERVICE + '/' + cartId)
.then(response => {
const items = response.data.items.map(i => {return {itemId: i.productId, name: i.productName, quantity: i.quantity, price: i.price}})
res.send(items)
})
.catch(error => console.log("ANGULR_API_CART", error));
})
// Post CART API call
server.post(ANGULR_API_CART + '/:cartId', (req, res) => {
let cartId = req.params.cartId;
let cartItem = {productId: req.body.itemId, productName: req.body.name, quantity: req.body.quantity, price: req.body.price};
axios.post(API_CART_SERVICE + '/' + cartId, cartItem)
.then(response => {
res.send(response.data);
})
.catch(error => console.log("ANGULR_API_CART", error));
});
// DELETE CART API Call (empty cart)
server.delete(ANGULR_API_CART + '/empty/:cartId', (req, res) => {
let cartId = req.params.cartId;
axios.delete(API_CART_SERVICE + "/empty/" + cartId)
.then(response => res.send(response.data))
.catch(error => console.log("ANGULR_API_CART", error));
});
// DELETE CART API Call (remove item)
server.delete(ANGULR_API_CART + '/:cartId', (req, res) => {
let cartId = req.params.cartId;
let cartItem = {productId: req.body.itemId, productName: req.body.name, quantity: req.body.quantity, price: req.body.price};
axios.delete(API_CART_SERVICE + "/" + cartId, {data: cartItem})
.then(response => res.send(response.data))
.catch(error => console.log("ANGULR_API_CART", error));
});
// POST LOGIN API Call
server.post(ANGULR_API_LOGIN, (req, res) => {
const accessToken: string = req.body.accessToken;
const accessTokenPart: string = accessToken.split('.')[1];
const decoded: any = JSON.parse(Buffer.from(accessTokenPart, 'base64').toString());
const sessionToken: string = decoded.sid;
const sessionExpiresAt: number = decoded.exp * 1000;
sessions.set(sessionToken, new Session(decoded.preferred_username, sessionExpiresAt, accessToken));
res.cookie("globex_session_token", sessionToken, { expires: new Date(sessionExpiresAt), sameSite: 'lax' });
res.status(200).send({"success": true});
});
// DELETE LOGIN API Call
server.delete(ANGULR_API_LOGIN, (req, res) => {
if (!req.cookies) {
res.status(401).send();
return;
}
const sessionToken = req.cookies['globex_session_token']
if (!sessionToken) {
res.status(401).send();
return;
}
sessions.delete(sessionToken);
res.status(204).send();
});
// GET CUSTOMER INFO API CALL
server.get(ANGULR_API_CUSTOMER + '/:custId', (req, res) => {
const sessionToken = req.cookies['globex_session_token']
const custId = req.params.custId;
if (!validateSession(sessions, sessionToken, custId)) {
res.status(401).send();
return;
}
axios.get(API_CUSTOMER_SERVICE.replace(':custId', custId))
.then(response => res.status(200).send(response.data))
.catch(error => {
if (error.response && error.response.status == 404) {
res.status(error.response.status).send()
} else {
console.log("ANGULR_API_CUSTOMER", error);
res.status(500).send();
}
});
});
// POST ORDER API CALL
server.post(ANGULAR_API_ORDER, (req, res) => {
const sessionToken = req.cookies['globex_session_token']
const custId = req.body.customer;
if (!validateSession(sessions, sessionToken, custId)) {
res.status(401).send();
return;
}
const configHeader = {
headers: { Authorization: `Bearer ${sessions.get(sessionToken).getAccessToken()}` }
};
axios.post(API_ORDER_SERVICE, req.body, configHeader)
.then(response => res.status(200).send(response.data))
.catch(error => {
console.log("ANGULR_API_CUSTOMER", error);
res.status(500).send();
})
});
//API Setup END
//Health check
server.get(ANGULR_HEALTH, (req, res) => {
var healthcheck = {
uptime: process.uptime(),
message: 'OK',
timestamp: Date.now()
};
res.send(healthcheck);
});
// Serve static files from /browser
server.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));
// All regular routes use the Universal engine
server.get('*', (req, res) => {
res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
});
return server;
}
function validateSession(sessions: Map<string, Session>, token: string, user: string): boolean {
if (!sessions.get(token)) {
console.log('No session found for ', token);
return false;
}
let active = sessions.get(token);
if (active.isExpired()) {
console.log('Session ' + token + ' is expired');
sessions.delete(token);
return false;
}
if (!active.isOwnedBy(user)) {
console.log('Session ' + token + ' is not owned by ' + user);
return false;
}
return true;
}
function run(): void {
const port = process.env['PORT'] || 4200;
// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
['log', 'warn', 'error'].forEach((methodName) => {
const originalMethod = console[methodName];
console[methodName] = (...args) => {
let initiator = 'unknown place';
try {
throw new Error();
} catch (e) {
if (typeof e.stack === 'string') {
let isFirst = true;
for (const line of e.stack.split('\n')) {
const matches = line.match(/^\s+at\s+(.*)/);
if (matches) {
if (!isFirst) { // first line - current function
// second line - caller (what we are looking for)
initiator = matches[1];
break;
}
isFirst = false;
}
}
}
}
originalMethod.apply(console, [...args, '\n', ` at ${initiator}`]);
};
});
}
class Session {
private username: String;
private expiresAt: number;
private accessToken: String;
constructor(username: String, expiresAt: number, accessToken: any) {
this.username = username;
this.expiresAt = expiresAt;
this.accessToken = accessToken;
}
isExpired(): boolean {
return this.expiresAt < Date.now();
}
isOwnedBy(user: String) {
return this.username == user;
}
getAccessToken(): String {
return this.accessToken;
}
}
// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
run();
}
export * from './src/main.server';