forked from Gaduo/FHIRSampleCreator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
584 lines (418 loc) · 14.5 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
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//simple server to serve static files...
var request = require('request');
var moment = require('moment');
var httpProxy = require('http-proxy')
// remove for proxy var myParser = require("body-parser");
var Cookies = require( "cookies" )
var express = require('express');
var app = express();
//remove for proxy app.use(myParser.json({extended : true}));
var orionModule = require("./serverModuleOrion.js")
var smartModule = require("./serverModuleSMART.js")
//var connect = require('connect');
var http = require('http');
process.on('uncaughtException', function(err) {
console.log('>>>>>>>>>>>>>>> Caught exception: ' + err);
});
var db;
var port = process.env.port;
if (! port) {
port=80;
}
//if the port was passed in on a command line
process.argv.forEach(function (val, index) {
//console.log(index + ': ' + val);
if (val == '-p') {
port = process.argv[index+1];
}
});
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://127.0.0.1:27017/clinfhir', function(err, ldb) {
if(err) {
//throw err;
console.log('>>> Mongo server not running')
} else {
db = ldb;
orionModule.setup(app,db);
smartModule.setup(app,db);
}
});
// proxy - for servers not implementing CORS
var proxy = httpProxy.createProxyServer({});
proxy.on('error', function (err, req, res) {
console.log('proxy error',err)
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong. And we are reporting a custom error message.');
});
proxy.on('proxyRes', function (proxyRes, req, res) {
console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});
proxy.on('proxyReq', function (proxyRes, req, res) {
console.log('sending');
});
function recordAccess(req,data) {
console.log(data)
var clientIp = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
if (db) {
var audit = {ip:clientIp,date:new Date().getTime()};
audit.data = data;
db.collection("accessAudit").insert(audit, function (err, result) {
if (err) {
console.log('Error logging access ',audit)
} else {
if (result && result.length) {
console.log('logged ',err)
updateLocation(result[0],clientIp);
}
}
});
}
}
//return status pages, index is resourceCeator.html
//app.use('/', express.static(__dirname,{index:'/resourceCreator.html'}));
app.use('/', express.static(__dirname,{index:'/launcher.html'}));
app.all('/proxy/*',function(req,res){
console.log(req.url)
req.url = req.url.replace('proxy/','')
console.log('-->'+req.url)
proxy.web(req, res, { target: 'http://snapp.clinfhir.com:8081/baseDstu3/' });
});
/*
//--- proxies for Grahames server. Could generalize this using - eg - headers,but will need to update allservices making $http calls...
app.all('/grahamv3/*',function(req,res){
//console.log(req.url)
req.url = req.url.replace('grahamv3/','')
proxy.web(req, res, { target: 'http://fhir3.healthintersections.com.au/open/' });
});
app.all('/grahamv2/*',function(req,res){
//console.log(req.url)
req.url = req.url.replace('grahamv2/','')
proxy.web(req, res, { target: 'http://fhir2.healthintersections.com.au/open/' });
});
*/
//this is used for the re-direct from simplifier
app.get('/createExample',function(req,res){
var cookies = new Cookies( req, res )
var profile = req.query['profile'];
cookies.set('myProfile',profile,{httpOnly:false});
//res.sendFile("builder.html", { root: __dirname })
res.sendFile("resourceCreator.html", { root: __dirname })
});
//======== temp ======= for Orion calling the medication dispense endpoint
app.get('/orion/:nhi',function(req,res){
var nhi = req.params['nhi'];
//var url = "https://frontend1.solution-nzmoh-dataset-leahr-graviton-jump-host-auckland.graviton.odl.io/fhir/1.0/MedicationDispense?patient.identifier=SYS_A|"+nhi
//var url = "https://52.41.169.101/fhir/1.0/MedicationDispense?patient.identifier=SYS_A|"+nhi
var url = "http://fhir.hl7.org.nz/baseDstu2/MedicationDispense?patient.identifier="+nhi
if (nhi) {
var options = {
method:'GET',
rejectUnauthorized: false,
uri : url,
auth : {
'user':'level1.sys_a',
'password':'Orionsy5!?'
},headers: {
'Accept': 'application/json+fhir'
}
};
request(options,function(error,response,body){
//console.log('error:', error); // Print the error if one occurred
//console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
//console.log('body:', body); // Print the HTML for the Google homepage.
if (body) {
if (response) {
res.status(response.statusCode)
}
res.end(body);
}
if (error) {
if (response) {
res.status(response.statusCode)
}
res.end(error);
}
});
} else {
res.end({"error":"No NHI"});
}
});
//when a user navigates to cf
app.post('/stats/login',function(req,res){
console.log('access')
var body = '';
req.on('data', function (data) {
body += data;
console.log("Partial body: " + body);
});
req.on('end', function () {
var jsonBody = {};
//just swallow errors for now
try {
jsonBody = JSON.parse(body);
} catch (ex) {}
recordAccess(req,jsonBody);
res.end('ok');
});
//recordAccess(req);
//res.end();
});
//get a summary of the access stats. This code is rather crude - mongo has better ways of doing this...
//probably want to be able to specify a date range and number of detailed items as well...
app.get('/stats/summary',function(req,res){
if(! db) {
//check that the mongo server is running...
res.json({});
return;
}
var query = {};
var min = req.query.min;
var max = req.query.max;
if (min) {
console.log('min=',min)
//var minDate = new Date(parseFloat(min))
console.log(new Date(parseFloat(max)))
query.date = {$gte : parseInt(min),$lte:parseInt(max)}
}
db.collection("accessAudit").find({$query: query}).toArray(function(err,doc){
if (err) {
res.status(500);
res.json({err:err});
} else {
var rtn = {cnt:doc.length,item:[],country:{},lastAccess : {date:0},module:{}};
var daySum = {};
//console.log(doc.length)
doc.forEach(function(d,inx){
//console.log(d.date,rtn.lastAccess.date)
if (d.data) {
if (d.data.module) {
var m = d.data.module;
var dataServer,confServer,termServer;
if (d.data.servers) {
dataServer = d.data.servers.data;
termServer = d.data.servers.terminology;
confServer = d.data.servers.conformance;
}
if (rtn.module[m]) {
rtn.module[m].cnt++;
updateServerCount(dataServer,'data',rtn.module[m])
updateServerCount(termServer,'term',rtn.module[m])
updateServerCount(confServer,'conf',rtn.module[m])
} else {
rtn.module[m] = {cnt:1};
updateServerCount(dataServer,'data',rtn.module[m])
updateServerCount(termServer,'term',rtn.module[m])
updateServerCount(confServer,'conf',rtn.module[m])
}
}
}
if (d.date > rtn.lastAccess.date) {
rtn.lastAccess = d;
}
if (d.location) {
var c = d.location['country_code'];
if (c) {
if (!rtn.country[c]) {
rtn.country[c] = {name: d.location['country_name'], cnt: 0}
}
rtn.country[c].cnt++;
}
}
var day = moment(d.date).startOf('day').valueOf();
if (! daySum[day]) {
daySum[day] = 0;
}
daySum[day] ++;
});
rtn.daySum = [];
for (var day in daySum) {
rtn.daySum.push([parseInt(day),daySum[day]]);
}
rtn.daySum.sort(function(a,b){
if (a[0] > b[0]){
return 1
} else {
return -1;
}
});
//now create an array of countries - easier for sorting
rtn.countryList = [];
for (var c in rtn.country) {
rtn.countryList.push(rtn.country[c])
}
//and sort it...
rtn.countryList.sort(function(a,b){
if (a.cnt < b.cnt) {
return 1
} else {
return -1
}
});
rtn.moduleList = []
for (var m in rtn.module) {
rtn.moduleList.push({name:m,cnt : rtn.module[m].cnt,detail:rtn.module[m]})
}
rtn.moduleList.sort(function(a,b){
if (a.cnt < b.cnt) {
return 1
} else {
return -1
}
});
res.json(rtn);
}
})
});
function updateServerCount(serverName,type,obj) {
if (serverName) {
var key = type+'Server'
obj[key] = obj[key] || {};
var o = obj[key];
o[serverName] = o[serverName] || {cnt:0}
o[serverName].cnt++
//return obj;
}
}
//old clients trying to access server...
app.use('/socket.io',function(req,res){
res.end();
});
app.post('/errorReport',function(req,res){
if(! db) {
//check that the mongo server is running...
res.json({});
return;
}
var clientIp = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
var body = '';
req.on('data', function (data) {
body += data;
console.log("Partial body: " + body);
});
req.on('end', function () {
var jsonBody = JSON.parse(body);
jsonBody.ip = clientIp;
jsonBody.date = new Date().getTime();
db.collection("errorLog").insert(jsonBody, function (err, result) {
if (err) {
console.log('Error logging error ',audit)
res.end();
} else {
res.end();
}
});
});
});
//distinct resourceTypes: db.getCollection('errorLog').distinct("resource.resourceType")
//return all results
app.get('/errorReport/distinct',function(req,res){
if(! db) {
//check that the mongo server is running...
res.json({});
return;
}
db.collection("errorLog").distinct("resource.resourceType",function(err,doc){
if (err) {
console.log('Error logging error ',audit)
res.end();
} else {
res.json(doc)
}
});
});
//return all results
app.get('/errorReport/:type?',function(req,res){
console.log(req.params.type);
var qry = {};
if (req.params.type) {
qry = {"resource.resourceType":req.params.type}
}
if (db) {
db.collection("errorLog").find(qry).sort({date:-1}).toArray(function(err,doc){
if (err) {
console.log('Error logging error ',audit)
res.end();
} else {
res.json(doc)
}
});
} else {
res.json({})
}
});
/*
app.get('/',function(req,res){
//console.log('d')
res.sendFile(__dirname+'/resourceCreator.html');
});
*/
//app.use('/', express.static(__dirname,{index:'/resourceCreator.html'}));
var sendEmail = function(recipient,message) {
}
app.listen(port);
var updateLocation = function(doc,ip) {
//doc.ip="198.102.235.144"
var url = "http://freegeoip.net/json/"+doc.ip;
var options = {
method:'GET',
uri : "http://freegeoip.net/json/"+doc.ip
};
request(options,function(error,response,body){
if (body) {
var loc;
try {
loc = JSON.parse(body);
} catch (ex) {}
if (loc) {
db.collection("accessAudit").update({_id:doc._id},{$set:{location:loc}},function(err,doc){
if (err) {
console.log('Error setting location',err)
} else {
chatModule.addActivity({display:"login from "+loc['country_name'],data:loc,ip:ip});
}
})
}
}
});
};
console.log('listening on port '+port);
//========== not currently used ===========
//which profiles are being used...
function getProfileUsage(summary,cb) {
db.collection("profileAudit").find().toArray(function(err,doc){
if (err) {
cb();
} else {
summary.profileAccess = [];
var profiles = {};
doc.forEach(function(item,inx){
if (item.profile) {
var profile = item.profile;
if (! profiles[profile]) {
profiles[profile] = {profile:profile,cnt:0}
}
profiles[profile].cnt++;
}
});
for (var p in profiles) {
summary.profileAccess.push(profiles[p])
}
summary.profileAccess.sort(function(a,b){
if (a.cnt < b.cnt) {
return 1
} else {
return -1
}
});
cb();
}
}
)};