-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
14935 lines (13716 loc) · 692 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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ======================================
// INITIALIZING DEPENDENCIES
// ======================================
const express = require('express'),
app = express(),
bodyParser = require("body-parser"),
AWS = require('aws-sdk'),
cors = require('cors'),
AmazonCognitoIdentity = require('amazon-cognito-identity-js'),
utility = require('./utilities/utility'),
VerifyToken = require('./verify_user'),
cookieParser = require('cookie-parser'),
archiver = require("archiver"),
fs = require("fs"),
path = require("path"),
uploadFile = require("./upload.js"),
ms = require("ms"),
multer = require('multer'),
XLSX = require('xlsx'),
request = require('request'),
moment = require('moment'),
jwt = require('jsonwebtoken'),
// Load the core build of Lodash.
_array = require('lodash/array');
var md5 = require('md5');
global.fetch = require('node-fetch');
const https = require('https');
var _ = require('lodash');
const { exec } = require('child_process')
var nodemailer = require('nodemailer');
let ejs = require("ejs");
let pdf = require("html-pdf");
let csvjson = require('csvjson');
const csvparser = require("csvtojson");
app.use(express.static(path.resolve('./public')));
// var transporter = nodemailer.createTransport({
// host: 'email.us-west-2.amazonaws.com',
// port: 465,
// secure: true,
// auth: {
// user: 'AKIA5UBJSELBMRFTI2QO',
// pass: 'BPwKxokCSkorDHhAnyrVaNbML8Ydlo3scXbQEmwbPJay'
// }
// });
// ================================================
// SOCKET <DOT> IO CONFIGURATION
// ================================================
const http = require('http')
const socketIO = require('socket.io')
// our server instance
const server = http.createServer(app)
// This creates our socket using the instance of the server
const io = socketIO(server)
// This is what the socket.io syntax is like, we will work this later
let interval;
// var ffmpeg = require('ffmpeg');
io.on('connection', socket => {
console.log("New client connected");
socket.on("connection", () => {
})
socket.on("disconnect", () => {
console.log("Client disconnected");
});
})
// ================================================
// SERVER CONFIGURATION
// ================================================
global.navigator = () => null;
// ======================================
// GLOBAL VARIABLES
// ======================================
const successMessage = "success";
const failureMessage = "failure";
const apiPrefix = "/"
console.log("DOMAIN IS ", process.env.DOMAIN);
// ======================================
// CONFIGURING AWS SDK & EXPESS
// ======================================
// Avatar Configuration
// var config = {
// "awsAccessKeyId": process.env.AWS_ACCESS_KEY_ID,
// "awsSecretAccessKey": process.env.AWS_ACCESS_SECRET_KEY,
// "sportModelBucket": process.env.SPORT_MODEL_BUCKET,
// "avatar3dClientId": process.env.AVATAR_3D_CLIENT_ID,
// "avatar3dclientSecret": process.env.AVATAR_3D_CLIENT_SECRET,
// "region": process.env.REGION,
// "usersbucket": process.env.USER_BUCKET,
// "userPoolId": process.env.USER_POOL_ID,
// "apiVersion": process.env.API_VERSION,
// "ClientId": process.env.CLIENT_ID,
// "ComputeInstanceEndpoint": process.env.COMPUTE_INSTANCE_ENDPOINT,
// "FrontendUrl": process.env.FRONTEND_URL
// };
var config = require('./config/configuration_keys.json');
var config_env = config;
//AWS.config.loadFromPath('./config/configuration_keys.json');
const BUCKET_NAME = config_env.usersbucket;
// AWS Credentials loaded
var myconfig = AWS.config.update({
accessKeyId: config_env.awsAccessKeyId, secretAccessKey: config_env.awsSecretAccessKey, region: config_env.region,
maxRetries: 15,
retryDelayOptions: { base: 500 }
});
// Cognito Configurationo
var cognito = {
userPoolId: config_env.userPoolId,
region: config_env.region,
apiVersion: config_env.apiVersion,
ClientId: config_env.ClientId
}
const {
getUserDetails,
getUserDetailBySensorId,
getUserByPlayerId,
updateSimulationFileStatusInDB,
addTeam,
deleteTeam,
fetchAllTeamsInOrganization,
deleteTeamFromOrganizationList,
addTeamToOrganizationList,
getCumulativeAccelerationData,
getTeamData,
getCompletedJobs,
updateJobComputedTime,
getBrandData,
getPlayerSimulationFile,
removeRequestedPlayerFromOrganizationTeam,
getCumulativeAccelerationRecords,
addPlayer,
getUserDetailByPlayerId,
getAllTeamsOfOrganizationsOfSensorBrand,
getSimulationImageRecord,
createUserDbEntry,
getPlayersListFromTeamsDB,
createInviteUserDbEntry,
addRecordInUsersDDB,
getVerificationStatus,
addUserDetailsToDb,
getUserDbData,
getUserTokenDBDetails,
getUserSensor,
getOrganizationList,
InsertUserIntoSensor,
InsertImpactVideoKey,
storeSensorData,
fetchNumbers,
fetchStaffMembers,
fetchAllUsers,
putNumbers,
addPlayerToTeamInDDB,
getAllSensorBrands,
setVideoTime,
getOrgUniqueList,
getOrgUniqueTeams,
upDateUserFBGlid,
upDateuserPassword,
getUserAlreadyExists,
upDateuser,
DeleteOrganization,
getOrganizatonBynameSensor,
getOrganizatonByTeam,
getOrgSensorData,
renameOrganization,
renameSensorOrganization,
addOrganization,
MergeOrganization,
addorgTeam,
getSernsorDataByTeam,
renameTeam,
getUserByTeam,
renameUsers,
getUserDbDataByUserId,
getBrandOrganizationData,
getPlayerSimulationStatus,
getTeamList,
getOrganizationTeamData,
getPlayerList,
getTeamDataWithPlayerRecords,
fetchSensor,
fetchOrgStaffMembers,
getHeadAccelerationEvents,
getPlayersListFromTeamsDB_2,
getTeamDataWithPlayerRecords_2,
getBrandOrganizationData2,
getAllOrganizationsOfSensorBrand,
getTeamSpheres,
updateUserStatus,
getTeamDataWithPlayerRecords_3,
getPlayerCgValues,
getBrandDataByorg,
deleteSensorData,
deleteSimulation_imagesData,
InsertTrimVideoKey,
updateTrimVideoKey,
getSernsorDataByOrgTeam,
getModalValidationDB,
checkSensorDataExists,
getPlayerImageDetailsByaccoutId,
getOrgIdbyImageId,
updatePlayerPositions,
getPlayerSummariesData,
InsertUserIntoOrg,
downloadLogFileFromS3,
removePlayerFromTeam,
removePlayerFromTeam1,
getAllOrganizationsOfSensorBrand1,
getOrgpPlayerFromSensorDetails,
getOrgpPlayerFromUser,
getOrgpTeamFromSensorDetails,
getOrgFromSensorDetailsr,
addJobslog,
getUserDbDataByAccountId,
getSensorDataByPlayerID,
InsertNewSensorDataByPlayerID,
DeleteSensorDataByPlayerID,
} = require('./controllers/query');
// Multer Configuration
var storage = multer.memoryStorage()
var upload = multer({
storage: storage,
fileFilter: function (req, file, callback) {
//var ext = path.extname(file.originalname);
console.log("This is filename ------> \n", file.originalname);
let jpgFile = new RegExp(".jpg").test(file.originalname);
let jpegFile = new RegExp(".jpeg").test(file.originalname);
let JPEGFile = new RegExp(".JPEG").test(file.originalname);
let JPGFile = new RegExp(".JPG").test(file.originalname);
let pngFile = new RegExp(".png").test(file.originalname);
let PNGFile = new RegExp(".PNG").test(file.originalname);
let tiffFile = new RegExp(".tiff").test(file.originalname);
let TIFFFile = new RegExp(".TIFF").test(file.originalname);
if (!jpgFile && !jpegFile && !pngFile && !JPEGFile && !JPGFile && !PNGFile && !TIFFFile && !tiffFile) {
//req.body["file_error"] = "Only JPEG/ JPG/ jpeg/ jpg/ PNG/ png/ tiff/ TIFF format file is allowed";
}
callback(null, true)
}
// limits:{
// fileSize: 1024 * 1024
// }
});
var uploadSensorData = multer({
storage: storage,
fileFilter: function (req, file, callback) {
//var ext = path.extname(file.originalname);
console.log("This is filename ------> \n", file.originalname);
let csv = new RegExp(".csv").test(file.originalname);
let csv_upper = new RegExp(".CSV").test(file.originalname);
let excel = new RegExp(".xlsx").test(file.originalname);
let excelx = new RegExp(".xls").test(file.originalname);
if (!csv && !csv_upper && !excel && !excelx) {
// res.send({message : "FAILURE"});
req.body["file_error"] = "Only .csv , .xlsx file is allowed"
}
callback(null, true)
}
// limits:{
// fileSize: 1024 * 1024
// }
});
var uploadSidelineImpactVideo = multer({
storage: storage,
fileFilter: function (req, file, callback) {
//var ext = path.extname(file.originalname);
console.log("This is filename ------> \n", file);
// let csv = new RegExp(".csv").test(file.originalname);
// let csv_upper = new RegExp(".CSV").test(file.originalname);
// let excel = new RegExp(".xlsx").test(file.originalname);
// let excelx = new RegExp(".xls").test(file.originalname);
// if (!csv && !csv_upper && !excel && !excelx) {
// // res.send({message : "FAILURE"});
// req.body["file_error"] = "Only .csv , .xlsx file is allowed"
// }
callback(null, true)
}
// limits:{
// fileSize: 1024 * 1024
// }
});
var uploadModelRealData = multer({
storage: storage,
fileFilter: function (req, file, callback) {
//var ext = path.extname(file.originalname);
console.log("This is filename ------> \n", file.originalname);
let csv = new RegExp(".csv").test(file.originalname);
let csv_upper = new RegExp(".CSV").test(file.originalname);
let excel = new RegExp(".xlsx").test(file.originalname);
let excelx = new RegExp(".xls").test(file.originalname);
if (!csv && !csv_upper && !excel && !excelx) {
// res.send({message : "FAILURE"});
req.body["file_error"] = "Only .csv , .xlsx file is allowed"
}
callback(null, true)
}
// limits:{
// fileSize: 1024 * 1024
// }
});
// AWS S3 & Other Controllers Configuration
const awsWorker = require('./controllers/aws.controller.js');
const { resolve, reject } = require('bluebird');
var s3 = new AWS.S3({ useAccelerateEndpoint: true });
// Cognito client who initializes the AWS Credentials to invoke
// commands on behalf of the developer
var COGNITO_CLIENT = new AWS.CognitoIdentityServiceProvider({
apiVersion: cognito.apiVersion,
region: cognito.region
});
// DynamoDB Object created to do SCAN , PUT , UPDATE operations
const docClient = new AWS.DynamoDB.DocumentClient({
convertEmptyValues: true
});
// Make io accessible to our router
app.use(function (req, res, next) {
req.io = io;
next();
});
// Express configured for POST Request handling of multiple types
// xxx-url encoded (form type) & json type
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(cookieParser());
// app.use(cors(
// {
// origin: [process.env.DOMAIN],
// credentials: true
// }
// ));
app.use(express.static(path.join(__dirname, 'client', 'build')));
function setConnectionTimeout(time) {
var delay = typeof time === 'string'
? ms(time)
: Number(time || 5000);
return function (req, res, next) {
res.connection.setTimeout(delay);
next();
}
}
// ============================================
// FUNCTIONS OR IMPLEMENTATIONS
// ============================================
let users = [];
let paginationToken = "";
// Function list all users
// user_attributes only takes required or user attributes defined
// in cognito not custom attributes
function listAllUsers(user_attributes, cb) {
let params = {
"AttributesToGet": user_attributes, // Pass an array to it
"UserPoolId": cognito.userPoolId,
};
if (paginationToken) {
params["PaginationToken"] = paginationToken
}
COGNITO_CLIENT.listUsers(params, function (err, data) {
if (err) {
cb(err, ""); // an error occurred
} else {
if (data.PaginationToken == undefined) {
users.push(data.Users);
paginationToken = "";
cb("", utility.concatArrays(users)); // successful response
users = [];
} else {
paginationToken = data.PaginationToken;
users.push(data.Users);
listAllUsers(user_attributes, cb);
}
}
});
}
function verifyImageToken(token, item) {
console.log(token, item);
return new Promise((resolve, reject) => {
jwt.verify(token, item.secret, function (err, decoded) {
if (err) {
console.log(err);
reject({
err: err,
authorized: false
})
}
else {
resolve(decoded);
}
});
})
}
function getImageFromS3(image_record) {
return new Promise((resolve, reject) => {
var params = {
Bucket: image_record.bucket_name ? image_record.bucket_name : config_env.usersbucket,
Key: image_record.path
};
s3.getObject(params, function (err, data) {
if (err) {
// reject(err)
resolve(null);
}
else {
resolve(data);
}
});
})
}
function getImageFromS3Buffer(image_data) {
return new Promise((resolve, reject) => {
// console.log(image_data.Body);
try {
resolve(image_data.Body.toString('base64'))
}
catch (e) {
//reject(e)
resolve(null);
}
})
}
function getFileFromS3(url, bucket_name) {
console.log('url ---------------', url)
return new Promise((resolve, reject) => {
var params = {
Bucket: bucket_name ? bucket_name : config_env.usersbucket,
Key: url
};
s3.getObject(params, function (err, data) {
if (err) {
// reject(err)
resolve(null);
}
else {
resolve(data);
}
});
})
}
// Enable the user in cognito
function enableUser(user_name, cb) {
var params = {
UserPoolId: cognito.userPoolId,
/* required */
Username: user_name /* required */
};
COGNITO_CLIENT.adminEnableUser(params, function (err, data) {
if (err) cb(err, "") // an error occurred
else {
cb("", data);
} // successful response
});
}
// Disable the users in cognito
function disableUser(user_name, cb) {
var params = {
UserPoolId: cognito.userPoolId,
/* required */
Username: user_name /* required */
};
COGNITO_CLIENT.adminDisableUser(params, function (err, data) {
if (err) cb(err, "") // an error occurred
else {
cb("", data);
} // successful response
});
}
// Get List of groups of which user is member
// Like Admin,Associate etc
function getListGroupForUser(user_name, cb) {
var params = {
UserPoolId: cognito.userPoolId,
/* required */
Username: user_name,
/* required */
};
COGNITO_CLIENT.adminListGroupsForUser(params, function (err, data) {
if (err) {
cb(err.code, "");
} // an error occurred
else {
cb("", data.Groups);
} // successful response
});
}
function getFileSignedUrl(key, cb, type) {
var params = {
Bucket: BUCKET_NAME,
Key: key
};
if (type) {
let filename = key.split('/').pop();
filename = filename.split('.')[0];
filename = filename + '-' + type + '.zip';
params.ResponseContentDisposition = 'attachment; filename=' + filename
}
s3.getSignedUrl('getObject', params, function (err, url) {
if (err) {
cb(err, "");
} else {
cb("", url);
}
});
}
function getAvatarInspectionFileSignedUrl(key, cb) {
var params = {
Bucket: BUCKET_NAME,
Key: key
};
s3.headObject(params, function (err, metadata) {
if (err && err.code === 'NotFound') {
// Handle no object on cloud here
cb(err, "");
} else {
s3.getSignedUrl('getObject', params, function (err, url) {
if (err) {
cb(err, "");
} else {
cb("", url);
}
});
}
});
}
// Get user details & all his attributes
function getUser(user_name, cb) {
console.log('getUser', user_name)
var params = {
UserPoolId: cognito.userPoolId,
/* required */
Username: user_name /* required */
};
COGNITO_CLIENT.adminGetUser(params, function (err, data) {
if (err) {
cb(err.code, "");
} // an error occurred
else {
cb("", data);
} // successful response
});
}
//forgot password
function forgotPassword(user_name, cb) {
console.log('forgotPassword', user_name)
var params = {
ClientId: cognito.ClientId,
/* required */
Username: user_name /* required */
};
COGNITO_CLIENT.forgotPassword(params, function (err, data) {
if (err) {
cb(err.code, "");
} // an error occurred
else {
cb("", data);
} // successful response
});
}
function getUploadedImageFileList(user_name, cb) {
const s3Params = {
Bucket: BUCKET_NAME,
Delimiter: '/',
Prefix: user_name + '/profile/image/'
// Key: req.query.key + ''
};
s3.listObjectsV2(s3Params, (err, data) => {
if (err) {
// console.log(err);
cb(err, "");
}
console.log(data);
cb("", data.Contents);
});
}
// Function to get the path of all simulation directory stored with Date as folder name
function getSimulationFilePath(user_name, cb) {
const s3Params = {
Bucket: BUCKET_NAME,
Delimiter: '/',
Prefix: `${user_name}/simulation/`
// Key: req.query.key + ''
};
s3.listObjectsV2(s3Params, (err, data) => {
if (err) {
// console.log(err);
console.log(err);
cb(err, '');
}
console.log(data);
try {
var pathArray = data.CommonPrefixes;
const simulationDirectoryPaths = pathArray.map(d => d.Prefix);
cb('', simulationDirectoryPaths);
} catch (e) {
cb(err, '');
}
});
}
function getSimulationFilesOfPlayer(path, cb) {
const s3Params = {
Bucket: BUCKET_NAME,
Delimiter: '/',
Prefix: path
// Key: req.query.key + ''
};
s3.listObjectsV2(s3Params, (err, data) => {
if (err) {
// console.log(err);
console.log(err);
cb(err, '');
}
const imageList = data.Contents;
var counter = 0;
var url_arrary = [];
imageList.forEach(function (image, index) {
var params = {
Bucket: BUCKET_NAME,
Key: image.Key
};
s3.getSignedUrl('getObject', params, function (err, url) {
counter++;
if (err) {
console.log(err);
} else {
console.log(url);
url_arrary.push(url);
}
if (counter == imageList.length) {
cb('', url_arrary);
}
});
});
});
}
app.post(`${apiPrefix}checkIfPlayerExists`, (req, res) => {
console.log("Checking player", req.body);
getPlayersListFromTeamsDB({
organization: "PSU",
team_name: "York Tech Football"
})
.then(data => {
console.log("USER EXISTS ", data.player_list.indexOf(req.body.name));
if (data.player_list.indexOf(req.body.name) > -1) {
res.send({
message: "success",
flag: true
})
}
else {
res.send({
message: "success",
flag: false
})
}
})
.catch(err => {
res.send({
message: "failure",
error: err
})
})
})
app.post(`${apiPrefix}getSimulationFilePath`, (req, res) => {
console.log(req.body);
getSimulationFilePath(req.body.player_id, function (err, data) {
if (err) {
res.send({
message: "failure",
error: err
})
}
else {
res.send({
message: "success",
data: data
})
}
})
})
app.post(`${apiPrefix}getSimulationFilesOfPlayer`, (req, res) => {
console.log(req.body);
getSimulationFilesOfPlayer(req.body.path, function (err, data) {
if (err) {
res.send({
message: "failure",
error: err
})
}
else {
res.send({
message: "success",
data: data
})
}
})
})
function getUploadedModelFileList(user_name, cb) {
const s3Params = {
Bucket: BUCKET_NAME,
Delimiter: '/',
Prefix: user_name + '/profile/model/'
// Key: req.query.key + ''
};
s3.listObjectsV2(s3Params, (err, data) => {
if (err) {
// console.log(err);
cb(err, "");
}
console.log(data);
cb("", data.Contents);
});
}
function getSimulationFile(user_name, cb) {
const s3Params = {
Bucket: BUCKET_NAME,
Delimiter: '/',
Prefix: user_name + '/profile/simulation/'
// Key: req.query.key + ''
};
s3.listObjectsV2(s3Params, (err, data) => {
if (err) {
// console.log(err);
cb(err, "");
}
console.log(data);
cb("", data.Contents);
});
}
function getUploadedInpFileList(user_name, cb) {
const s3Params = {
Bucket: BUCKET_NAME,
Delimiter: '/',
Prefix: user_name + '/profile/rbf/'
// Key: req.query.key + ''
};
s3.listObjectsV2(s3Params, (err, data) => {
if (err) {
// console.log(err);
cb(err, "");
}
cb("", data.Contents);
});
}
function getUploadedVtkFileList(user_name, cb) {
const s3Params = {
Bucket: BUCKET_NAME,
Delimiter: '/',
// Prefix: user_name + '/profile/rbf/vtk/'
Prefix: user_name + '/profile/morphed_vtk/combined_meshes/'
// Key: req.query.key + ''
};
s3.listObjectsV2(s3Params, (err, data) => {
if (err) {
// console.log(err);
cb(err, "");
}
cb("", data.Contents);
});
}
// Function to authenticate user credentials
function login(user_name, password, user_type, cb) {
const poolData = {
UserPoolId: cognito.userPoolId, // Your user pool id here
ClientId: cognito.ClientId // Your client id here
};
var pool_region = cognito.region;
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails({
Username: user_name,
Password: password,
});
var userData = {
Username: user_name,
Pool: userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
// Data received on successfull authentication
// console.log('access token + ' + result.getAccessToken().getJwtToken());
// console.log('id token + ' + result.getIdToken().getJwtToken());
// console.log('refresh token + ' + result.getRefreshToken().getToken());
cb("", result);
},
onFailure: function (err) {
// console.log(err);
console.log(err);
cb(err.message, "");
}
});
}
function loginFirstTime(user, cb) {
const poolData = {
UserPoolId: cognito.userPoolId, // Your user pool id here
ClientId: cognito.ClientId // Your client id here
};
// var pool_region = 'ap-south-1';
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails({
Username: user.user_name,
Password: user.password,
});
var userData = {
Username: user.user_name,
Pool: userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
// console.log('access token + ' + result.getAccessToken().getJwtToken());
// console.log('id token + ' + result.getIdToken().getJwtToken());
// console.log('refresh token + ' + result.getRefreshToken().getToken());
cb("", result);
},
onFailure: function (err) {
cb(err.message, "");
},
newPasswordRequired: function (userAttributes, requiredAttributes) {
// User was signed up by an admin and must provide new
// password and required attributes, if any, to complete
// authentication.
// the api doesn't accept this field back
delete userAttributes.email_verified;
// Custom attributes can be also set if we want
// userAttributes.custom_blood_group = "O+";
// unsure about this field, but I don't send this back
delete userAttributes.phone_number_verified;
// Get these details and call
cognitoUser.completeNewPasswordChallenge(user.new_password, userAttributes, this);
}
});
}
function getAge(dob) {
let currentDate = new Date();
let birthDate = new Date(dob);
let age = currentDate.getFullYear() - birthDate.getFullYear()
let month = currentDate.getMonth() - birthDate.getMonth()
if (month < 0 || (month === 0 && currentDate.getDate() < birthDate.getDate())) {
age = age - 1
}
return age;
}
function adminUpdateUser(User, cb) {
var params = {
UserAttributes: [ /* required */
{
Name: 'email', /* required */
Value: User.email
},
/* more items */
],
UserPoolId: cognito.userPoolId, /* required */
Username: User.user_name, /* required */
};
COGNITO_CLIENT.adminUpdateUserAttributes(params, function (err, data) {
if (err) {
cb(err, "");
} // an error occurred
else {
cb("", data);
} // successful response
});
}
// Function to create User by Admin
function adminCreateUser(User, cb) {
var params = {
ClientId: cognito.ClientId, /* required */
Username: User.user_name, /* required */
Password: User.password_code,
UserAttributes: [
{
Name: 'phone_number', /* required */
Value: User.phone_number
},
{
Name: 'name', /* required */
Value: User.name