-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
7785 lines (7559 loc) · 354 KB
/
index.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
//process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; //allows to get files from https even if certificate invalid
var fileUpload = require('express-fileupload') //yarn add express-fileupload
var compression = require('compression') //yarn add compression
var express = require('express'); //yarn add express -- save
var sql = require('mssql'); //yarn add mssql -- save
var jwt = require("jsonwebtoken"); //yarn add jsonwebtoken --save
var request = require('request'); //yarn add request --save
var httpntlm = require('httpntlm'); //yarn add httpntlm
var axios = require('axios'); //yarn add axios --save
var soapRequest = require('easy-soap-request'); //yarn add easy-soap-request
//var curl = require('curl'); //yarn add curl --save
//var superagent = require('superagent'); //yarn add superagent --save
//var WebSocket = require("ws"); //yarn add ws --save
var nodemailer = require("nodemailer"); //yarn add nodemailer --save
var emlFormat = require("eml-format"); //yarn add eml-format --save
//var socketIO = require("socket.io"); //yarn add socket.io --save
var ExcelJS = require('exceljs'); //yarn add exceljs --save
//var url = require('url');
//var http = require('http');
var https = require('https');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
var logToFile = function(message){ fs.appendFile(process.env.logPathFile, new Date().toISOString() + '\t' + message + '\r\n', (err) => { if (err) throw err; } ); }
logToFile('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
logToFile('API starting2...')
logToFile('Express Version: ' + require('express/package').version)
logToFile('Node Version: ' + process.version)
logToFile('Process ID: ' + process.pid)
logToFile('Running Path: ' + process.cwd())
//#region Public_Functions_&_Variables
app.use(compression()) //Enable Compression
app.use(fileUpload()); //Enable File Upload
app.use(bodyParser.json({limit: '50mb'})); //Use bodyParser, and set file size
app.use(bodyParser.urlencoded({limit: '50mb', extended: true})); //Use bodyParser, and set file size
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");//Enabling CORS
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType, Content-Type, Accept, Authorization");
next();
});
var connectionPool = new sql.ConnectionPool(JSON.parse(process.env.dbConfig), (err, pool) => {
if(err){
logToFile('Error creating SQL connectionPool:' + err)
}else{
logToFile('SQL ConnectionPool Created with database: ' + pool.config.database)
}
})
var veryfyToken = function(req, res, next){
const bearerHeader = req.headers['authorization'];//get auth header value
if(typeof bearerHeader !== 'undefined'){
const bearer = bearerHeader.split(' '); //split by space
const bearerToken = bearer[1]; //get token from array
jwt.verify(bearerToken, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile('Se produjo un error en la validación del token')
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
if(req.body.sys_user_code || req.body.sys_user_code){
if( (authData.user.sys_user_code == req.query.sys_user_code) || (authData.user.sys_user_code == req.body.sys_user_code) ){
req.token = bearerToken; //set the token
next();
}else{
logToFile('No coincide el código del usuario con el token')
logToFile(authData.user.sys_user_code)
logToFile(req.query.sys_user_code)
logToFile(req.body.sys_user_code)
res.status(403).send({message: 'No coincide el código del usuario con el token'});
return;
}
}else{
req.token = bearerToken; //set the token
next();
}
}
})
}else{
logToFile('No se pudo verificar token')
res.status(403).send({message: 'No se pudo verificar token'});
}
}
app.get(process.env.iisVirtualPath+'status', function (req, res) {
//res.send(JSON.stringify(connectionPool));
let respuesta = {
status: 'UP'
,uptime: process.uptime()
,nodeVersion: process.version
,pid: process.pid
,platform: process.platform
,runningPath: process.cwd()
,memoryUsage: process.memoryUsage()
,resourceUsage: process.resourceUsage()
,connectionPool_eventsCount: connectionPool._eventsCount
,connectionPool_db: connectionPool.config.database
,connectionPool_connected: connectionPool._connected
,connectionPool_poolMax: connectionPool.pool.max
,connectionPool_poolUsed: connectionPool.pool.used
}
res.send(JSON.stringify(respuesta));
//res.send(JSON.stringify(connectionPool));
});
//#endregion Public_Functions_&_Variables
//#region Version_1_0_0
//#region SESSION_OTHERS
app.post(process.env.iisVirtualPath+'spSysLogin', function (req, res) {
let start = new Date()
logToFile('!!! New Login attempt from ' + 'Usuario: ' + req.body.sys_user_id + ' (' + req.ip + ')')
new sql.Request(connectionPool)
.input('sys_user_id', sql.VarChar(250), req.body.sys_user_id )
.input('sys_user_password', sql.VarChar(100), req.body.sys_user_password )
.execute('spSysLogin', (err, result) => {
logToFile("Request: " + req.originalUrl)
//NO quiero grabar la clave logToFile("Request: " + JSON.stringify(req.body))
logToFile("Perf spSysLogin: " + ((new Date() - start) / 1000) + ' secs' )
if(err){
if(err&&err.originalError&&err.originalError.info){
logToFile('DB Error: ' + JSON.stringify(err.originalError.info))
}else{
logToFile('DB Error: ' + JSON.stringify(err.originalError))
}
res.status(400).send(err.originalError);
return;
}
if(result.recordset.length > 0){
const user = {
username: req.body.sys_user_id
,sys_user_code: result.recordset[0].sys_user_code
,sys_profile_id: result.recordset[0].sys_profile_id
}
jwt.sign({user: user}, process.env.secretEncryptionJWT, (err, token) => {
if(err){
logToFile('JWT Error: ' + err)
res.status(400).send(err);
return;
}else{
new sql.Request(connectionPool)
.input('sys_user_code', sql.Int, result.recordset[0].sys_user_code)
.input('token', sql.NVarChar(sql.MAX), token)
.input('device_data', sql.NVarChar(sql.MAX), null)//se puede agregar información adicional
.execute('spSysLoginLogToken', (errA, resultA) => {
if(errA){
if(errA&&errA.originalError&&errA.originalError.info){
logToFile('DB Error: ' + JSON.stringify(errA.originalError.info))
}else{
logToFile('DB Error: ' + JSON.stringify(errA.originalError))
}
res.status(400).send(errA.originalError);
return;
}
logToFile('Welcome: ' + req.body.sys_user_id)
userToken = token
result.recordset[0].jwtToken = token
res.setHeader('content-type', 'application/json');
res.status(200).send(result.recordset);
})
}
})
}else{
res.status(400).send('Error de Inicio de Sesión');
return;
}
})
});
app.post(process.env.iisVirtualPath+'sp_sys_users_reset', function (req, res) {
let start = new Date()
logToFile('!!! New password Reset attempt for ' + req.body.sys_user_id)
new sql.Request(connectionPool)
.input('sys_user_id', sql.VarChar(250), req.body.sys_user_id )
.input('source_data', sql.VarChar(100), req.ip )
.input('url_destination', sql.VarChar(250), req.body.url_destination )
.execute('sp_sys_users_reset', (err, result) => {
logToFile("Request: " + req.originalUrl)
//NO quiero grabar la clave logToFile("Request: " + JSON.stringify(req.body))
logToFile("Perf spSysLogin: " + ((new Date() - start) / 1000) + ' secs' )
if(err){
if(err&&err.originalError&&err.originalError.info){
logToFile('DB Error: ' + JSON.stringify(err.originalError.info))
}else{
logToFile('DB Error: ' + JSON.stringify(err.originalError))
}
res.status(400).send(err.originalError);
return;
}
if(result.recordset.length > 0){
try{
logToFile("Temp Sent: " + JSON.stringify(result.recordset) )
let transporter = nodemailer.createTransport({
host: process.env.notifyMailHost,
port: process.env.notifyMailPort,
secure: process.env.notifyMailSecure,
auth: {
user: process.env.notifyMailUser,
pass: process.env.notifyMailPass,
},
tls: {
rejectUnauthorized: false// do not fail on invalid certs
},
});
var mailOptions = {
from: '"BITT" <'+process.env.notifyMailUser+'>', //from debe contener entre <> la misma cuenta que se usa en el Transporter (podría sacarla de [auth.user] )
//to: req.body.destinations,
to: result.recordset[0].destination_address,
subject: 'Solicitud de Código Temporal',
text: result.recordset[0].destination_message_HTML,
html: result.recordset[0].destination_message_HTML
};
logToFile("Sending Mail...")
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
logToFile("Error sending mail")
logToFile(error)
res.status(400).send(error);
return;
}
logToFile("Message Sent: " + JSON.stringify(info) )
logToFile("Perf sp_sys_users_reset: " + ((new Date() - start) / 1000) + ' secs')
res.status(200).send(info);
});
}catch(ex){
logToFile("Service Error")
logToFile(ex)
res.status(400).send(ex);
return;
}
}else{
res.status(400).send('Error de Inicio de Sesión');
return;
}
})
});
app.post(process.env.iisVirtualPath+'sp_sys_users_reset_validate', function (req, res) {
let start = new Date()
logToFile('!!! New password Reset attempt ' + req.ip )
new sql.Request(connectionPool)
.input('sys_user_id', sql.VarChar(250), req.body.sys_user_id )
.input('sys_user_password', sql.VarChar(100), req.body.sys_user_password )
.execute('spSysLogin', (err, result) => {
logToFile("Request: " + req.originalUrl)
//NO quiero grabar la clave logToFile("Request: " + JSON.stringify(req.body))
logToFile("Perf spSysLogin: " + ((new Date() - start) / 1000) + ' secs' )
if(err){
if(err&&err.originalError&&err.originalError.info){
logToFile('DB Error: ' + JSON.stringify(err.originalError.info))
}else{
logToFile('DB Error: ' + JSON.stringify(err.originalError))
}
res.status(400).send(err.originalError);
return;
}
if(result.recordset.length > 0){
const user = {
username: req.body.sys_user_id
,sys_user_code: result.recordset[0].sys_user_code
,sys_profile_id: result.recordset[0].sys_profile_id
}
jwt.sign({user: user}, process.env.secretEncryptionJWT, (err, token) => {
if(err){
logToFile('JWT Error: ' + err)
res.status(400).send(err);
return;
}else{
logToFile('Welcome: ' + req.body.sys_user_id)
userToken = token
result.recordset[0].jwtToken = token
res.setHeader('content-type', 'application/json');
res.status(200).send(result.recordset);
}
})
}else{
res.status(400).send('Error de Inicio de Sesión');
return;
}
})
});
app.get(process.env.iisVirtualPath+'spSysUserMainData', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
new sql.Request(connectionPool)
.input('sys_profile_id', sql.Int, req.query.sys_profile_id )
.input('sys_user_language', sql.VarChar(25), req.query.sys_user_language )
.input('sys_user_code', sql.Int, req.query.sys_user_code )
.execute('spSysUserMainData', (err, result) => {
logToFile("Request: " + req.originalUrl)
logToFile("Perf spSysUserMainData: " + ((new Date() - start) / 1000) + ' secs')
if(err){
logToFile("Error: " + JSON.stringify(err.originalError.info))
res.status(400).send(err.originalError);
return;
}
res.setHeader('content-type', 'application/json');
res.status(200).send(result.recordset);
})
}
})
})
app.get(process.env.iisVirtualPath+'spSysUserMainDataMobile', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
new sql.Request(connectionPool)
.input('sys_profile_id', sql.Int, req.query.sys_profile_id )
.input('sys_user_language', sql.VarChar(25), req.query.sys_user_language )
.input('sys_user_code', sql.Int, req.query.sys_user_code )
.execute('spSysUserMainDataMobile', (err, result) => {
logToFile("Request: " + req.originalUrl)
logToFile("Perf spSysUserMainDataMobile: " + ((new Date() - start) / 1000) + ' secs')
if(err){
logToFile("Error: " + JSON.stringify(err.originalError.info))
res.status(400).send(err.originalError);
return;
}
res.setHeader('content-type', 'application/json');
res.status(200).send(result.recordset);
})
}
})
})
app.get(process.env.iisVirtualPath+'spMyUnreadNotifications', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
new sql.Request(connectionPool)
.input('userCode', sql.Int, req.query.userCode )
.input('userCompany', sql.Int, req.query.userCompany )
.input('userLanguage', sql.VarChar(50), req.query.userLanguage )
.execute('spMyUnreadNotifications', (err, result) => {
logToFile("Request: " + req.originalUrl)
logToFile("Perf spMyUnreadNotifications: " + ((new Date() - start) / 1000) + ' secs' )
if(err){
logToFile("Error: " + JSON.stringify(err.originalError.info))
res.status(400).send(err.originalError);
return;
}
res.setHeader('content-type', 'application/json');
res.status(200).send(result.recordset);
})
}
})
})
app.get(process.env.iisVirtualPath+'spMyNotificationsContacts', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
new sql.Request(connectionPool)
.input('userCode', sql.Int, req.query.userCode )
.input('userCompany', sql.Int, req.query.userCompany )
.input('userLanguage', sql.VarChar(50), req.query.userLanguage )
.execute('spMyNotificationsContacts', (err, result) => {
logToFile("Request: " + req.originalUrl)
logToFile("Perf spMyNotificationsContacts: " + ((new Date() - start) / 1000) + ' secs' )
if(err){
logToFile("Error: " + JSON.stringify(err.originalError.info))
res.status(400).send(err.originalError);
return;
}
res.setHeader('content-type', 'application/json');
res.status(200).send(result.recordset);
})
}
})
})
app.get(process.env.iisVirtualPath+'spMyNotificationsContactMessages', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
new sql.Request(connectionPool)
.input('userCode', sql.Int, req.query.userCode )
.input('userCompany', sql.Int, req.query.userCompany )
.input('userLanguage', sql.VarChar(50), req.query.userLanguage )
.input('contactUserCode', sql.Int, req.query.contactUserCode )
.execute('spMyNotificationsContactMessages', (err, result) => {
logToFile("Request: " + req.originalUrl)
logToFile("Perf spMyNotificationsContactMessages: " + ((new Date() - start) / 1000) + ' secs' )
if(err){
logToFile("Error: " + JSON.stringify(err.originalError.info))
res.status(400).send(err.originalError);
return;
}
res.setHeader('content-type', 'application/json');
res.status(200).send(result.recordset);
})
}
})
})
app.post(process.env.iisVirtualPath+'uploadFile', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
try{
//logToFile('flag00')
/*if (!req.files){
logToFile('Error en uploadFile (no se recibió archivo)')
res.status(400).send('Error en uploadFile (no se recibió archivo)');
return;
}*/
var fileName = Object.keys(req.files)[0]
//logToFile('flag01')
let sampleFile = req.files[fileName]
//logToFile('flag02')
logToFile('Upload ' + process.env.filesPath + req.query.upload_file_name)
sampleFile.mv(process.env.filesPath + req.query.upload_file_name, function(err) {
if(err){
logToFile('Error escribiendo archivo (uploadFile): ' + JSON.stringify(err))
res.status(400).send(err);
return;
}
new sql.Request(connectionPool)
.input('attach_id', sql.VarChar(500), req.query.attach_id )
.execute('sp_attachs_uploaded', (err, result) => {
logToFile("Request: " + req.originalUrl)
logToFile("Perf sp_attachs_uploaded: " + ((new Date() - start) / 1000) + ' secs' )
if(err){
logToFile("DB Error: " + err.procName)
logToFile("Error: " + JSON.stringify(err.originalError.info))
res.status(400).send(err.originalError);
return;
}
res.setHeader('content-type', 'application/json');
res.status(200).send(result.recordset);
})
})
}catch(ex){
logToFile("Service Error")
logToFile(ex)
res.status(400).send(ex);
return;
}
}
})
})
app.get(process.env.iisVirtualPath+'downloadFile', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
logToFile("Request: " + req.originalUrl)
logToFile("Perf downloadFile: " + ((new Date() - start) / 1000) + ' secs' )
res.download((process.env.filesPath + "//" + req.query.fileName))
}
})
})
app.get(process.env.iisVirtualPath+'downloadTempFile', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
logToFile("Request: " + req.originalUrl)
logToFile("Perf downloadFile: " + ((new Date() - start) / 1000) + ' secs' )
res.download((process.env.tempFilesPath + "//" + req.query.fileName), function (err) {
if (err) {
logToFile("Error downloading File...")
} else {
logToFile("Deleting File: " + process.env.tempFilesPath + req.query.fileName);
fs.unlink(process.env.tempFilesPath + req.query.fileName, (err) => {
if (err) {
logToFile("Deleting File error: " + process.env.tempFilesPath + req.query.fileName);
}
});
logToFile("Temp file deleted")
}
})
}
})
})
app.post(process.env.iisVirtualPath+'spAttachGenerateID', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
try{
new sql.Request(connectionPool)
.input('userCode', sql.Int, req.body.userCode )
.input('userCompany', sql.Int, req.body.userCompany )
.input('original_file_name', sql.VarChar(500), req.body.original_file_name )
.input('file_type', sql.NVarChar(sql.MAX), req.body.file_type )
.input('file_size', sql.VarChar(sql.Int), req.body.file_size )
//.input('row_id', sql.Int, req.body.row_id )
.input('moduleName', sql.VarChar(500), req.body.moduleName )
.execute('spAttachGenerateID', (err, result) => {
logToFile("Request: " + req.originalUrl)
logToFile("Request: " + JSON.stringify(req.body))
logToFile("Perf spAttachGenerateID: " + ((new Date() - start) / 1000) + ' secs' )
if(err){
logToFile("DB Error: " + err.procName)
logToFile("Error: " + JSON.stringify(err.originalError.info))
res.status(400).send(err.originalError);
return;
}
res.setHeader('content-type', 'application/json');
res.status(200).send(result.recordset);
})
}catch(ex){
logToFile("Service Error")
logToFile(ex)
res.status(400).send(ex);
return;
}
}
})
})
app.post(process.env.iisVirtualPath+'saveGridUserState', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
try{
new sql.Request(connectionPool)
.input('userCode', sql.Int, req.body.userCode )
.input('userCompany', sql.Int, req.body.userCompany )
.input('moduleName', sql.VarChar(500), req.body.moduleName )
.input('gridName', sql.VarChar(500), req.body.gridName )
.input('gridState', sql.NVarChar(sql.MAX), req.body.gridState )
.execute('saveGridUserState', (err, result) => {
logToFile("Request: " + req.originalUrl)
logToFile("Request: " + JSON.stringify(req.body))
logToFile("Perf saveGridUserState: " + ((new Date() - start) / 1000) + ' secs' )
if(err){
logToFile("DB Error: " + err.procName)
logToFile("Error: " + JSON.stringify(err.originalError.info))
res.status(400).send(err.originalError);
return;
}
res.setHeader('content-type', 'application/json');
res.status(200).send(result.recordset);
})
}catch(ex){
logToFile("Service Error")
logToFile(ex)
res.status(400).send(ex);
return;
}
}
})
})
app.get(process.env.iisVirtualPath+'spGetMailFormData', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
//Generates PDF if exists URL
if(req.query.moduleReportURL){
logToFile("Generate PDF: " + req.originalUrl)
logToFile("Generate PDF as : " + req.query.uid)
//Config Request
const agent = new https.Agent({ rejectUnauthorized: false });
const options = {
url: req.query.moduleReportURL //url: 'https://localhost/ReportServer?/mktPO_1&rs:format=PDF&sys_user_code=1&sys_user_language=es&sys_user_company=1&row_id=5'
,followRedirect: true
,followAllRedirects: true
,jar: true
,agent: agent
,strictSSL: false
};
request(options).on('error', function(err) {
logToFile("Error: " + JSON.stringify(err))
res.status(400).send(err);
return;
}).pipe(fs.createWriteStream((process.env.tempFilesPath + req.query.uid + '.pdf')))
}
new sql.Request(connectionPool)
.input('userCode', sql.Int, req.query.userCode )
.input('userCompany', sql.Int, req.query.userCompany )
.input('userLanguage', sql.VarChar(25), req.query.userLanguage )
.input('moduleName', sql.VarChar(500), req.query.moduleName )
.input('row_id', sql.Int, req.query.row_id )
.execute('spGetMailFormData', (err, result) => {
logToFile("Request: " + req.originalUrl)
logToFile("Perf spGetMailFormData: " + ((new Date() - start) / 1000) + ' secs')
if(err){
logToFile("Error: " + JSON.stringify(err.originalError.info))
res.status(400).send(err.originalError);
return;
}
//Push Attachment to Result (Using Public Internet Path to Temp Files)
if(req.query.moduleReportURL){
let attachments = [{
fileName: req.query.moduleName+'_'+req.query.row_id+'.pdf'
,uploadFilename: req.query.uid + '.pdf'
}]
result.recordset[0].attachments = attachments
}
res.setHeader('content-type', 'application/json');
res.status(200).send(result.recordset);
})
}
})
})
app.post(process.env.iisVirtualPath+'sendUserMail', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
try{
let transporter = nodemailer.createTransport({
host: process.env.notifyMailHost,
port: process.env.notifyMailPort,
secure: process.env.notifyMailSecure,
auth: {
user: process.env.notifyMailUser,
pass: process.env.notifyMailPass,
},
tls: {
rejectUnauthorized: false// do not fail on invalid certs
},
});
//convert Attachments
let attachments = []
if(req.body.attachments){
JSON.parse(req.body.attachments).map(x=>
attachments.push({
filename: x.fileName
,path: process.env.tempFilesPath + x.uploadFilename
})
)
}
var mailOptions = {
from: '"'+req.body.senderName+'" <'+process.env.notifyMailUser+'>', //from debe contener entre <> la misma cuenta que se usa en el Transporter (podría sacarla de [auth.user] )
replyTo: req.body.senderMail,
to: req.body.destinations,
subject: req.body.subjectText,
text: req.body.bodyText,
html: req.body.bodyText,
attachments: attachments
};
logToFile("Sending Mail...")
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
logToFile("Error sending mail")
logToFile(error)
res.status(400).send(error);
return;
}
//logToFile("Message Message: " + info.messageId)
logToFile("Message Sent: " + JSON.stringify(info) )
if(req.body.attachments){
JSON.parse(req.body.attachments).map(x=>{
logToFile("Deleting File: " + process.env.tempFilesPath + x.uploadFilename);
fs.unlink(process.env.tempFilesPath + x.uploadFilename, (err) => {
if (err) {
logToFile("Deleting File error: " + process.env.tempFilesPath + x.uploadFilename);
}
});
})
}
logToFile("Perf spGetMailFormData: " + ((new Date() - start) / 1000) + ' secs')
res.status(200).send(info);
});
}catch(ex){
logToFile("Service Error")
logToFile(ex)
res.status(400).send(ex);
return;
}
}
})
})
app.post(process.env.iisVirtualPath+'generateEMLMail', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
try{
let attachments = []
if(req.body.attachments){
JSON.parse(req.body.attachments).map(x=>
attachments.push({
name: x.fileName
,data: fs.readFileSync(process.env.tempFilesPath + x.uploadFilename),
//,path: process.env.tempFilesPath + x.uploadFilename
})
)
}
let destinations = [];
if(req.body.destinations&&req.body.destinations){
req.body.destinations.replace(';',',')
req.body.destinations.split(',').map(x=>{
destinations.push({
//name: '"'+x+'"',
email: x
});
});
}
if(destinations.length<=0){
destinations = [{name: req.body.senderMail, email: req.body.senderMail}]
}
var data = {
from: req.body.senderMail,
headers: { "X-Unsent": "1"},
to: destinations,
subject: req.body.subjectText,
html: req.body.bodyText,
attachments: attachments
};
logToFile("Generating EML: " + process.env.tempFilesPath + req.body.uid + '.eml');
emlFormat.build(data, function(error, eml) {
if(error){
logToFile("Generating EML Error")
logToFile(error)
res.status(400).send(error);
return;
}
fs.writeFileSync(process.env.tempFilesPath + req.body.uid + '.eml', eml);
logToFile("EML File created: " + process.env.tempFilesPath + req.body.uid + '.eml')
let resultado = {
fileName: 'Mail.eml',
uploadFilename: req.body.uid + '.eml'
}
res.status(200).send(resultado);
});
}catch(ex){
logToFile("Service Error")
logToFile(ex)
res.status(400).send(ex);
return;
}
}
})
})
//2021 version 4.6.2
app.post(process.env.iisVirtualPath+'generatePDFandEML', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
try{
//Create PDF file based on parameters
const agent = new https.Agent({ rejectUnauthorized: false });
const options = {
url: req.body.mailReportURL //url: 'https://localhost/ReportServer?/mktPO_1&rs:format=PDF&sys_user_code=1&sys_user_language=es&sys_user_company=1&row_id=5'
,followRedirect: true
,followAllRedirects: true
,jar: true
,agent: agent
,strictSSL: false
};
var stream = request(options).on('error', function(err) {
logToFile("Error: " + JSON.stringify(err))
res.status(400).send(err);
return;
}).pipe(fs.createWriteStream((process.env.tempFilesPath + req.body.uid + '.pdf')))
//create attachments variable AFTER file is created (stream finished)
stream.on('finish', function (){
let attachments = []
let fileData = null;
fileData = fs.readFileSync(process.env.tempFilesPath + req.body.uid + '.pdf');
attachments.push({
name: req.body.rptName + '.pdf'
,data: fileData,
//,path: process.env.tempFilesPath + x.uploadFilename
})
//fix data for EML generation
let destinations = []
req.body.destinations.map(x=>{
destinations.push({
//name: x.contactName,
email: x.mail
})
})
if(destinations.length<=0){
destinations = [{name: req.body.senderMail, email: req.body.senderMail}]
}
var data = {
from: req.body.senderMail,
headers: { "X-Unsent": "1"},
to: destinations,
subject: req.body.subjectText,
html: req.body.bodyText,
attachments: attachments
};
//Generate EML
logToFile("Generating EML: " + process.env.tempFilesPath + req.body.uid + '.eml');
emlFormat.build(data, function(error, eml) {
if(error){
logToFile("Generating EML Error")
logToFile(error)
res.status(400).send(error);
return;
}
fs.writeFileSync(process.env.tempFilesPath + req.body.uid + '.eml', eml);
logToFile("EML File created: " + process.env.tempFilesPath + req.body.uid + '.eml')
let resultado = {
fileName: 'Mail.eml',
uploadFilename: req.body.uid + '.eml'
}
res.status(200).send(resultado);
});
})
}catch(ex){
logToFile("Service Error")
logToFile(ex)
res.status(400).send(ex);
return;
}
}
})
})
app.post(process.env.iisVirtualPath+'generatePDFandSEND', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
try{
//Create PDF file based on parameters
const agent = new https.Agent({ rejectUnauthorized: false });
const options = {
url: req.body.mailReportURL //url: 'https://localhost/ReportServer?/mktPO_1&rs:format=PDF&sys_user_code=1&sys_user_language=es&sys_user_company=1&row_id=5'
,followRedirect: true
,followAllRedirects: true
,jar: true
,agent: agent
,strictSSL: false
};
var stream = request(options).on('error', function(err) {
logToFile("Error: " + JSON.stringify(err))
res.status(400).send(err);
return;
}).pipe(fs.createWriteStream((process.env.tempFilesPath + req.body.uid + '.pdf')))
//create attachments variable AFTER file is created (stream finished)
stream.on('finish', function (){
let attachments = []
attachments.push({
filename: req.body.rptName + '.pdf'
,path: process.env.tempFilesPath + req.body.uid + '.pdf'
})
//fix data for MAIL
var mailOptions = {
from: '"'+req.body.senderName+'" <'+process.env.notifyMailUser+'>', //from debe contener entre <> la misma cuenta que se usa en el Transporter (podría sacarla de [auth.user] )
replyTo: req.body.senderMail,
to: req.body.destinations.map(x=>x.mail).join(", "),
subject: req.body.subjectText,
text: req.body.bodyText,
html: req.body.bodyText,
attachments: attachments
};
//create Transporter
let transporter = nodemailer.createTransport({
host: process.env.notifyMailHost,
port: process.env.notifyMailPort,
secure: process.env.notifyMailSecure,
auth: {
user: process.env.notifyMailUser,
pass: process.env.notifyMailPass,
},
tls: {
rejectUnauthorized: false// do not fail on invalid certs
},
});
//SendMail
logToFile("Sending Mail...")
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
logToFile("Error sending mail")
logToFile(error)
res.status(400).send(error);
return;
}
//logToFile("Message Message: " + info.messageId)
logToFile("Message Sent: " + JSON.stringify(info) )
logToFile("Deleting File: " + process.env.tempFilesPath + req.body.uid + '.pdf');
fs.unlink(process.env.tempFilesPath + req.body.uid + '.pdf', (err) => {
if (err) {
logToFile("Deleting File error: " + process.env.tempFilesPath + req.body.uid + '.pdf');
}
});
logToFile("Perf spGetMailFormData: " + ((new Date() - start) / 1000) + ' secs')
res.status(200).send(info);
});
})
}catch(ex){
logToFile("Service Error")
logToFile(ex)
res.status(400).send(ex);
return;
}
}
})
})
//app.post(process.env.iisVirtualPath+'generatePDFandDOWNLOAD', veryfyToken, function(req, res) {
app.get(process.env.iisVirtualPath+'generatePDFandDOWNLOAD', veryfyToken, function(req, res) {
let start = new Date()
jwt.verify(req.token, process.env.secretEncryptionJWT, (jwtError, authData) => {
if(jwtError){
logToFile("JWT Error:")
logToFile(jwtError)
res.status(403).send(jwtError);
}else{
try{
//Create PDF file based on parameters
logToFile("generatePDFandDOWNLOAD: " + req.query.reportURL)
const agent = new https.Agent({ rejectUnauthorized: false });
const options = {
url: req.query.reportURL //url: 'https://localhost/ReportServer?/mktPO_1&rs:format=PDF&sys_user_code=1&sys_user_language=es&sys_user_company=1&row_id=5'
,followRedirect: true
,followAllRedirects: true
,jar: true
,agent: agent
,strictSSL: false
,'cache-control': 'no-cache'
};
logToFile("Creando: " + process.env.tempFilesPath + req.query.fileName )
var stream = request(options).on('error', function(err) {
logToFile("Error: " + JSON.stringify(err))
res.status(400).send(err);
return;
//}).pipe(fs.createWriteStream((process.env.tempFilesPath + req.body.uid + '.pdf')))
}).pipe(fs.createWriteStream((process.env.tempFilesPath + req.query.fileName )))
//create attachments variable AFTER file is created (stream finished)
stream.on('finish', function (){
logToFile("Creado finish: " + process.env.tempFilesPath + req.query.fileName )
res.download(process.env.tempFilesPath + req.query.fileName)
})
}catch(ex){
logToFile("Service Error")
logToFile(ex)
res.status(400).send(ex);
return;