-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
1401 lines (1238 loc) · 50.9 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
var createError = require('http-errors');
var sslRedirect = require('heroku-ssl-redirect');
var express = require('express');
var cookieParser = require('cookie-parser');
var logger = require('morgan'); //Morgan is an HTTP request logger middleware for Node.js. It simplifies the process of logging requests to your application.
var flash = require('express-flash');
var session = require('express-session');
var QRCode = require('qrcode');
var cors = require('cors');
var path = require('path');
var router = express.Router();
var connection = require('./src/js/db');
var CUSTOM_ENUMS = require('./src/js/enums')
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var nodemailer = require('nodemailer');
var fs = require('fs')
var initModels = require("./models/init-models");
var sequelise = require('./src/js/db_sequelise');
const {Op} = require("sequelize");
var models = initModels(sequelise);
//only load the .env file if the server isn’t started in production mode
if (process.env.NODE_ENV !== CUSTOM_ENUMS.PRODUCTION) {
require('dotenv').config();
}
//emailer configuration
let transporter = nodemailer.createTransport({
service: CUSTOM_ENUMS.GMAIL,
auth: {
user: process.env.EMAIL_ADDRESS,
pass: process.env.EMAIL_PASSWORD
}
});
// Testing Emails Pattern
// when testing emails, in NODE_ENV=development, set EMAIL_OVERRIDE
// if EMAIL_OVERRIDE is set, send email to it's value, prepend subject line with [TEST EMAIL], include intended recipients in the body
//sanitization and validation
const {check, validationResult, sanitizeParam} = require('express-validator');
//alternative import
//var expressValidator = require('express-validator');
//expressValidator.sanitizeBody, expressValidator.sanitizeParam, expressValidator.body etc
const uuidv4 = require('uuid/v4')
var db = require('./dbxml/localdb');
var app = express();
var configRouter = require('./routes/config');
var harvestRouter = require('./routes/harvest');
var storageRouter = require('./routes/storage');
var authRouter = require('./routes/auth');
var ROLES = require('./utils/roles');
const {Sequelize} = require("sequelize");
// enable ssl redirect
app.use(sslRedirect([
'other',
//'development',
'production'
]));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// You can set morgan to log differently depending on your environment
// create a write stream (in append mode), to current directory
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'})
// only log error responses, write log lines to process.stdout
if (app.get('env') == CUSTOM_ENUMS.PRODUCTION) {
app.use(logger('common', {
skip: function (req, res) {
return res.statusCode < 400
}
}));
// app.use(logger('common', { skip: function(req, res) { return res.statusCode < 400 }, stream: __dirname + '/access.log' }));
} else {
//write logfile to current directory, flag a is append
app.use(logger('dev', {stream: accessLogStream}));
}
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(cors());
app.use(session({
secret: '123456cat',
resave: false,
saveUninitialized: true,
cookie: {maxAge: 1800000} // time im ms: 60000 - 1 min, 1800000 - 30min, 3600000 - 1 hour
}))
// Initialize Passport and restore authentication state, if any, from the session.
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
// middleware for all views
app.use(function (req, res, next) {
// locals is deleted at the end of current request, flash is deleted after it is displayed,
// and it is stored in session intermediately.
// (this works with redirect)
res.locals.error = req.flash("error");
res.locals.success = req.flash("success")
next();
});
// Mount routers
app.use('/', router);
app.use('/app/config', configRouter);
app.use('/app/auth', authRouter);
app.use('/app/harvest', harvestRouter);
app.use('/app/storage', storageRouter);
app.use(express.static(path.join(__dirname, "src")));
app.use(express.static(path.join(__dirname, 'build')));
// Configure the local strategy for use by Passport.
//
// The local strategy require a `verify` function which receives the credentials
// (`username` and `password`) submitted by the user. The function must verify
// that the password is correct and then invoke `cb` with a user object, which
// will be set at `req.user` in route handlers after authentication.
// We will use two LocalStrategies, one for file-based auth and another for db-auth
passport.use('file-local', new LocalStrategy({
usernameField: 'loginUsername', //useful for custom id's on your credentials fields, if incorrect you get a missing credentials error
passwordField: 'loginPassword', //useful for custom id's on your credentials fields
},
function (username, password, cb) {
db.users.findByUsername(username, function (err, user) {
if (err) {
return cb(err);
}
if (!user) {
return cb(null, false, {message: 'Incorrect username.'});
}
if (user.password != password) {
return cb(null, false, {message: 'Incorrect password.'});
}
// If the credentials are valid, the verify callback invokes done to supply
// Passport with the user that authenticated.
return cb(null, user);
});
}));
passport.use('db-local', new LocalStrategy({
usernameField: 'loginUsername', //useful for custom id's on your credentials fields, if this is incorrect you get a missing credentials error
passwordField: 'loginPassword', //useful for custom id's on your credentials fields
},
function (username, password, cb) {
db.users.findByUsername(username, function (err, user) {
if (err) {
return cb(err);
}
if (!user) {
return cb(null, false, {message: 'Incorrect username.'});
}
if (user.password != password) {
return cb(null, false, {message: 'Incorrect password.'});
}
// If the credentials are valid, the verify callback invokes done to
// supply Passport with the user that authenticated.
return cb(null, user);
});
}));
// Configure Passport authenticated session persistence.
//
// In order to restore authentication state across HTTP requests, Passport needs
// to serialize users into and deserialize users out of the session. The
// typical implementation of this is as simple as supplying the user ID when
// serializing, and querying the user record by ID from the database when
// deserializing.
passport.serializeUser(function (user, cb) {
cb(null, user.id);
});
passport.deserializeUser(function (id, cb) {
db.users.findById(id, function (err, user) {
if (err) {
return cb(err);
}
cb(null, user);
});
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
//home page
router.get('/', function (req, res) {
res.render('index', {user: req.user, page_name: 'home'});
//res.sendFile(path.join(__dirname+'/src/index.html')); //__dirname : It will resolve to your project folder.
});
//supply chain - harvest and storage
router.get('/app/supplychain',
require('connect-ensure-login').ensureLoggedIn({redirectTo: '/app/auth/login'}),
function (req, res) {
res.render('supplychain', {user: req.user, page_name: 'supplychain'});
});
//about
router.get('/about', function (req, res) {
res.render('about', {user: req.user, page_name: 'about'});
});
//produce gallery
router.get('/gallery', function (req, res) {
res.render('gallery', {user: req.user, page_name: 'gallery'});
});
//farmers
router.get('/farmers', function (req, res) {
res.render('farmers', {user: req.user, page_name: 'farmers'});
});
//markets
router.get('/markets', function (req, res) {
res.render('markets', {user: req.user, page_name: 'markets'});
});
//retailers
router.get('/retailers', function (req, res) {
res.render('retailers', {user: req.user, page_name: 'retailers'});
});
//pricing
router.get('/pricing', function (req, res) {
res.render('pricing', {user: req.user, page_name: 'pricing'});
});
//food101
router.get('/food101', function (req, res) {
res.render('food101', {user: req.user, page_name: 'food101'});
});
//tech101
router.get('/tech101', function (req, res) {
res.render('tech101', {user: req.user, page_name: 'tech101'});
});
//trace_produce
router.get('/app/trace_produce',
require('connect-ensure-login').ensureLoggedIn({redirectTo: '/app/auth/login'}),
function (req, res) {
res.render('trace_produce', {user: req.user, page_name: 'trace_produce'});
});
//blockchain_explorer
router.get('/app/blockchain_explorer',
require('connect-ensure-login').ensureLoggedIn({redirectTo: '/app/auth/login'}),
function (req, res) {
res.render('blockchain_explorer', {user: req.user, page_name: 'blockchain_explorer'});
});
//contact
router.get('/contact', function (req, res) {
res.render('contact', {user: req.user, page_name: 'contact'});
});
//return template for what is at the market this week
router.get('/weekly',
require('connect-ensure-login').ensureLoggedIn({redirectTo: '/app/auth/login'}),
function (req, res) {
res.render('weekly', {user: req.user, page_name: 'weekly'});
});
//return template for how
router.get('/how', function (req, res) {
res.render('how', {user: req.user, page_name: 'how'});
});
//return template for terms and conditions
router.get('/terms', function (req, res) {
res.render('termsofuse', {user: req.user, page_name: 'terms'});
});
//return template for privacy policy
router.get('/privacy', function (req, res) {
res.render('privacypolicy', {user: req.user, page_name: 'privacy'});
});
//return template with scan results for produce
//NB this is an old template (scanresultv1) which probably should be removed
router.get('/scan/:id', function (req, res) {
var supplierProduceID = req.params.id; //OranjezichtCityFarm_Apples
var boolTracedOnBlockchain = process.env.SHOW_TRACED_ON_BLOCKCHAIN || false
// http://localhost:3000/scan/OranjezichtCityFarm_Apples
connection.execute('\n' +
'SELECT \n' +
'\ts.counter,\n' +
'\ts.ID,\n' +
'\ts.marketID,\n' +
'\ts.marketAddress,\n' +
'\ts.quantity,\n' +
'\ts.unitOfMeasure,\n' +
'\ts.storageTimeStamp,\n' +
'\ts.storageCaptureTime,\n' +
'\ts.URL,\n' +
'\ts.hashID,\n' +
'\ts.storageDescription,\n' +
'\ts.geolocation,\n' +
'\ts.supplierproduce,\n' +
'\th.supplierID,\n' +
'\th.supplierAddress,\n' +
'\th.productID,\n' +
'\th.photoHash,\n' +
'\th.harvestTimeStamp,\n' +
'\th.harvestCaptureTime,\n' +
'\th.harvestDescription,\n' +
'\th.geolocation\n' +
'FROM \n' +
'\tstorage s \n' +
'INNER JOIN\n' +
'\tharvest h\n' +
'ON \n' +
'\ts.supplierproduce = h.supplierproduce\n' +
'WHERE \n' +
'\ts.supplierproduce = ? AND \n' +
'\th.counter = (SELECT max(counter) FROM harvest where supplierproduce = ?) AND \n' +
' s.counter = (SELECT max(counter) FROM storage where supplierproduce = ?);',
[
supplierProduceID,
supplierProduceID,
supplierProduceID
],
function (err, rows) {
if (err) {
//req.flash('error', err);
console.error('error', err);
res.render('scanresultv1', {
data: '', user: req.user,
showTracedOnBlockchain: boolTracedOnBlockchain,
page_name: 'scanresultv1'
});
} else {
res.render('scanresultv1', {
data: rows, user: req.user,
showTracedOnBlockchain: boolTracedOnBlockchain,
page_name: 'scanresultv1'
});
}
});
});
//return template with scan results for produce i.e. http://localhost:3000/app/scan/WMNP_Fennel
//TODO Return Farmers email address as part of provenance_data
//TODO Update to include marketid '/app/scan/:marketid/:id' i.e. http://localhost:3000/app/scan/ozcf/WMNP_Fennel
router.get('/app/scan/:id', [sanitizeParam('id').escape().trim()],
function (req, res) {
var supplierProduceID = req.params.id; //OZCF_Apples or WMNP_Fennel
let weeklyViewQuery;
let testProvenance;
let baseAttributes = [
'harvest_supplierShortcode', 'harvest_supplierName', 'harvest_farmerName',
'year_established', 'harvest_description_json', 'harvest_photoHash', 'harvest_supplierAddress', 'harvest_produceName',
'harvest_TimeStamp', 'harvest_CaptureTime', 'harvest_Description', 'harvest_geolocation', 'supplierproduce',
'market_Address', 'market_storageTimeStamp', 'market_storageCaptureTime', 'logdatetime', 'lastmodifieddatetime'
]
/*var traceSqlBase = 'SELECT harvest_supplierShortcode, harvest_supplierName, harvest_farmerName,' +
'year_established, harvest_description_json, harvest_photoHash, harvest_supplierAddress, harvest_produceName,' +
'harvest_TimeStamp, harvest_CaptureTime, harvest_Description, harvest_geolocation, supplierproduce,' +
'market_Address, market_storageTimeStamp, market_storageCaptureTime, logdatetime, lastmodifieddatetime ' +
'FROM foodprint_weeklyview WHERE supplierproduce = ? '*/
if (supplierProduceID.split("_")[0] == CUSTOM_ENUMS.TEST) {
// e.g. https://www.foodprintapp.com/app/scan/TEST_beetroot
testProvenance = true;
//return single latest entry for supplierproduce
/*var traceSqlFinal = traceSqlBase + 'ORDER BY logdatetime DESC LIMIT 1;'*/
weeklyViewQuery = {
attributes: baseAttributes,
where: {
supplierproduce: supplierProduceID
},
order: [
['logdatetime', 'DESC']
],
limit: 1
}
} else {
//return latest weekly entry using ozcf protocol
testProvenance = false;
/*var traceSqlFinal = traceSqlBase + ' AND ' +
'logdatetime < (date(curdate() - interval weekday(curdate()) day + interval 1 week)) AND ' +
'logdatetime > (date(curdate() - interval weekday(curdate()) day));'*/
weeklyViewQuery = {
attributes: baseAttributes,
where: {
[Op.and]: [
{supplierproduce: supplierProduceID},
{
logdatetime: {
[Op.lt]: Sequelize.literal('(date(curdate() - interval weekday(curdate()) day + interval 1 week))')
}
},
{
logdatetime: {
[Op.gt]: Sequelize.literal('(date(curdate() - interval weekday(curdate()) day))')
}
}
]
}
}
}
// console.debug('Final provenance SQL query ' + traceSqlFinal);
console.debug('Final provenance SQL query params ' + supplierProduceID);
let provenance_data = '';
models.FoodprintWeeklyview
.findAll(weeklyViewQuery)
.then(rows => {
if (typeof rows !== 'undefined' && rows.length) {
// TODO - Use sharp library to attempt to resize base64 and if error, set flag that image invalid
// https://stackoverflow.com/questions/51010423/how-to-resize-base64-image-in-javascript
// convert your binary data to base64 format & then pass it to ejs
rows[0].harvest_photoHash = 'data:image/png;base64,' +
new Buffer(rows[0].harvest_photoHash, 'binary').toString('base64');
}
provenance_data = rows;
console.log('Provenance scan successful');
})
.catch(err => {
//req.flash('error', err);
provenance_data = '';
console.error('error', err);
console.error('Provenance scan error occured');
})
.finally(() => {
var boolTracedOnBlockchain = process.env.SHOW_TRACED_ON_BLOCKCHAIN || false
//START Track QR Scan (this could be done as xhr when scan page is rendered)
var marketID = CUSTOM_ENUMS.OZCF; //shortcode e.g. ozcf
var logid = uuidv4()
var qrid = '' //TODO this is not yet being tracked in config
//http://localhost:3000/app/scan/WMNP_Fennel
//https://www.foodprintapp.com/app/scan/WMNP_Fennel
var qrurl = req.protocol + '://' + req.get('host') + req.originalUrl;
var request_host = req.get('host')
var request_origin = req.headers.referer
//req.headers.referer - The Referer request header contains the address of the previous web page
//from which a link to the currently requested page was followed.
//The Referer header allows servers to identify where people are visiting them from and
// may use that data for analytics, logging, or optimized caching, for example.
//alternative would have been to use origin request header
//The Origin request header indicates where a fetch originates from.
var request_useragent = req.headers['user-agent']
var logdatetime = new Date();
//TODO - cross check marketID and supplierProduceID against existing marketID's from foodprint_market and foodPrint_supplierproduceid
//using connection.query and not connection.execute because of
// TypeError: Bind parameters must not contain undefined. To pass SQL NULL specify JS null
let data = {
logid: logid,
qrid: qrid,
qrurl: qrurl,
marketid: marketID,
request_host: request_host,
request_origin: request_origin,
request_useragent: request_useragent,
logdatetime: logdatetime
}
models.FoodprintQrcount
.create(data)
.then(_ => {
console.log('Produce scan tracking successful');
})
.catch(err => {
console.error('Produce scan tracking error occurred');
console.error('error', err);
})
res.render('scanresult', {
data: provenance_data, user: req.user,
showTracedOnBlockchain: boolTracedOnBlockchain,
testRecord: testProvenance, page_name: 'scanresult'
})
})
/*connection.execute(traceSqlFinal, [
supplierProduceID
],
function (err, rows) {
if (err) {
//req.flash('error', err);
var provenance_data = '';
console.error('error', err);
console.error('Provenance scan error occured');
} else {
if (typeof rows !== 'undefined' && rows.length) {
// TODO - Use sharp library to attempt to resize base64 and if error, set flag that image invalid
// https://stackoverflow.com/questions/51010423/how-to-resize-base64-image-in-javascript
// convert your binary data to base64 format & then pass it to ejs
rows[0].harvest_photoHash = 'data:image/png;base64,' +
new Buffer(rows[0].harvest_photoHash, 'binary').toString('base64');
}
var provenance_data = rows;
console.log('Provenance scan successful');
}
var boolTracedOnBlockchain = process.env.SHOW_TRACED_ON_BLOCKCHAIN || false
//START Track QR Scan (this could be done as xhr when scan page is rendered)
var marketID = CUSTOM_ENUMS.OZCF; //shortcode e.g. ozcf
var logid = uuidv4()
var qrid = '' //TODO this is not yet being tracked in config
//http://localhost:3000/app/scan/WMNP_Fennel
//https://www.foodprintapp.com/app/scan/WMNP_Fennel
var qrurl = req.protocol + '://' + req.get('host') + req.originalUrl;
var request_host = req.get('host')
var request_origin = req.headers.referer
//req.headers.referer - The Referer request header contains the address of the previous web page
//from which a link to the currently requested page was followed.
//The Referer header allows servers to identify where people are visiting them from and
// may use that data for analytics, logging, or optimized caching, for example.
//alternative would have been to use origin request header
//The Origin request header indicates where a fetch originates from.
var request_useragent = req.headers['user-agent']
var logdatetime = new Date();
//TODO - cross check marketID and supplierProduceID against existing marketID's from foodprint_market and foodPrint_supplierproduceid
//using connection.query and not connection.execute because of
// TypeError: Bind parameters must not contain undefined. To pass SQL NULL specify JS null
let data = {
logid: logid,
qrid: qrid,
qrurl: qrurl,
marketid: marketID,
request_host: request_host,
request_origin: request_origin,
request_useragent: request_useragent,
logdatetime: logdatetime
}
models.FoodprintQrcount
.create(data)
.then(_ => {
console.log('Produce scan tracking successful');
})
.catch(err => {
console.error('Produce scan tracking error occurred');
console.error('error', err);
})
// connection.query('INSERT INTO foodprint_qrcount (' +
// 'logid , qrid, qrurl, marketid, request_host,' +
// 'request_origin, request_useragent,logdatetime) ' +
// ' VALUES (?, ?, ?, ?, ?, ?, ?, ?);',
// [
// logid, qrid, qrurl, marketID, request_host,
// request_origin, request_useragent, logdatetime
// ]
// , function (err, res2) {
// if (err) {
// console.error('Produce scan tracking error occured');
// console.error('error', err);
// } else {
// console.log('Produce scan tracking successful');
// }
// });
//END Track QR Scan
res.render('scanresult', {
data: provenance_data, user: req.user,
showTracedOnBlockchain: boolTracedOnBlockchain,
testRecord: testProvenance, page_name: 'scanresult'
})
}
); //end of connection.execute*/
});
//REST API Get a single produce data record (twin to router.get('/app/scan/:id'))
//return json with scan results for produce http://localhost:3000/app/api/v1/scan/WMNP_Fennel
//TODO Update to include marketid '/app/scan/:marketid/:id' i.e. http://localhost:3000/app/api/v1/scan/ozcf/WMNP_Fennel
router.get('/app/api/v1/scan/:id', [sanitizeParam('id').escape().trim()], function (req, res) {
var supplierProduceID = req.params.id; //OZCF_Apples or WMNP_Fennel
let weeklyViewQuery;
let testProvenance;
let baseAttributes = [
'harvest_supplierShortcode', 'harvest_supplierName', 'harvest_farmerName',
'year_established', 'harvest_description_json', 'harvest_photoHash', 'harvest_supplierAddress', 'harvest_produceName',
'harvest_TimeStamp', 'harvest_CaptureTime', 'harvest_Description', 'harvest_geolocation', 'supplierproduce',
'market_Address', 'market_storageTimeStamp', 'market_storageCaptureTime', 'logdatetime', 'lastmodifieddatetime'
]
/*var traceSqlBase = 'SELECT harvest_supplierShortcode, harvest_supplierName, harvest_farmerName,' +
'year_established, harvest_description_json, harvest_photoHash, harvest_supplierAddress, harvest_produceName,' +
'harvest_TimeStamp, harvest_CaptureTime, harvest_Description, harvest_geolocation, supplierproduce,' +
'market_Address, market_storageTimeStamp, market_storageCaptureTime, logdatetime, lastmodifieddatetime ' +
'FROM foodprint_weeklyview WHERE supplierproduce = ? '*/
if (supplierProduceID.split("_")[0] == CUSTOM_ENUMS.TEST) {
// e.g. https://www.foodprintapp.com/app/scan/TEST_beetroot
//http://localhost:3000/app/api/v1/scan/TEST_Beetroot
testProvenance = true;
//return single latest entry for supplierproduce
/*var traceSqlFinal = traceSqlBase + 'ORDER BY logdatetime DESC LIMIT 1;'*/
weeklyViewQuery = {
attributes: baseAttributes,
where: {
supplierproduce: supplierProduceID
},
order: [
['logdatetime', 'DESC']
],
limit: 1
}
} else {
//return latest weekly entry using ozcf protocol
testProvenance = false;
/*var traceSqlFinal = traceSqlBase + ' AND ' +
'logdatetime < (date(curdate() - interval weekday(curdate()) day + interval 1 week)) AND ' +
'logdatetime > (date(curdate() - interval weekday(curdate()) day));'*/
weeklyViewQuery = {
attributes: baseAttributes,
where: {
[Op.and]: [
{supplierproduce: supplierProduceID},
{
logdatetime: {
[Op.lt]: Sequelize.literal('(date(curdate() - interval weekday(curdate()) day + interval 1 week))')
}
},
{
logdatetime: {
[Op.gt]: Sequelize.literal('(date(curdate() - interval weekday(curdate()) day))')
}
}
]
}
}
}
let provenance_data = [];
models.FoodprintWeeklyview
.findAll(weeklyViewQuery)
.then(rows => {
if (typeof rows !== 'undefined' && rows.length) {
// TODO - Use sharp library to attempt to resize base64 and if error, set flag that image invalid
// https://stackoverflow.com/questions/51010423/how-to-resize-base64-image-in-javascript
// convert your binary data to base64 format & then pass it to ejs
rows[0].harvest_photoHash = 'data:image/png;base64,' +
new Buffer(rows[0].harvest_photoHash, 'binary').toString('base64');
provenance_data = rows[0]; // return 1st row only
} else {
provenance_data = []; // return empty list for no data
}
console.log('Provenance scan successful');
})
.catch(err => {
//req.flash('error', err);
provenance_data = [];
console.error('error', err);
console.error('Provenance scan error occured');
//res.render('scanresult',{data:'', user:req.user});
})
.finally(() => {
var boolTracedOnBlockchain = process.env.SHOW_TRACED_ON_BLOCKCHAIN || false
//START Track QR Scan (this could be done as xhr when scan page is rendered)
var marketID = 'ozcf'; //shortcode e.g. ozcf
var logid = uuidv4()
var qrid = '' //TODO this is t yet being tracked in config
//http://localhost:3000/app/scan/WMNP_Fennel
//https://www.foodprintapp.com/app/scan/WMNP_Fennel
var qrurl = req.protocol + '://' + req.get('host') + req.originalUrl;
var request_host = req.get('host')
var request_origin = req.headers.referer
//req.headers.referer - The Referer request header contains the address of the previous web page
//from which a link to the currently requested page was followed.
//The Referer header allows servers to identify where people are visiting them from and may use that data for analytics, logging, or optimized caching, for example.
//alternative would have been to use origin request header
//The Origin request header indicates where a fetch originates from.
var request_useragent = req.headers['user-agent']
var logdatetime = new Date();
//TODO - cross check marketID and supplierProduceID against existing marketID's from foodprint_market and foodPrint_supplierproduceid
// connection.query( 'INSERT INTO foodprint_qrcount (' +
// 'logid , qrid, qrurl, marketid, request_host,' +
// 'request_origin, request_useragent,logdatetime) ' +
// ' VALUES (?, ?, ?, ?, ?, ?, ?, ?);',
// [
// logid, qrid, qrurl, marketID, request_host,
// request_origin, request_useragent, logdatetime
// ]
// ,function(err, res2) {
// if (err) {
// console.error('Produce scan tracking error occured');
// console.error('error', err);
// }
// console.log('Produce scan tracking successful');
// //callback(null, res2); // think 'return'
// });
//END Track QR Scan
provenance_data['user'] = req.user;
provenance_data['showTracedOnBlockchain'] = boolTracedOnBlockchain;
provenance_data['page_name'] = 'home';
//res.end() method to send data to client as json string via JSON.stringify() methoD
res.end(JSON.stringify(provenance_data, null, 4));
})
/*connection.execute(traceSqlFinal,
[
supplierProduceID
],
function (err, rows) {
if (err) {
//req.flash('error', err);
var provenance_data = [];
console.error('error', err);
console.error('Provenance scan error occured');
//res.render('scanresult',{data:'', user:req.user});
} else {
if (typeof rows !== 'undefined' && rows.length) {
// TODO - Use sharp library to attempt to resize base64 and if error, set flag that image invalid
// https://stackoverflow.com/questions/51010423/how-to-resize-base64-image-in-javascript
// convert your binary data to base64 format & then pass it to ejs
rows[0].harvest_photoHash = 'data:image/png;base64,' +
new Buffer(rows[0].harvest_photoHash, 'binary').toString('base64');
var provenance_data = rows[0]; // return 1st row only
} else {
var provenance_data = []; // return empty list for no data
}
console.log('Provenance scan successful');
}
var boolTracedOnBlockchain = process.env.SHOW_TRACED_ON_BLOCKCHAIN || false
//START Track QR Scan (this could be done as xhr when scan page is rendered)
var marketID = 'ozcf'; //shortcode e.g. ozcf
var logid = uuidv4()
var qrid = '' //TODO this is t yet being tracked in config
//http://localhost:3000/app/scan/WMNP_Fennel
//https://www.foodprintapp.com/app/scan/WMNP_Fennel
var qrurl = req.protocol + '://' + req.get('host') + req.originalUrl;
var request_host = req.get('host')
var request_origin = req.headers.referer
//req.headers.referer - The Referer request header contains the address of the previous web page
//from which a link to the currently requested page was followed.
//The Referer header allows servers to identify where people are visiting them from and may use that data for analytics, logging, or optimized caching, for example.
//alternative would have been to use origin request header
//The Origin request header indicates where a fetch originates from.
var request_useragent = req.headers['user-agent']
var logdatetime = new Date();
//TODO - cross check marketID and supplierProduceID against existing marketID's from foodprint_market and foodPrint_supplierproduceid
// connection.query( 'INSERT INTO foodprint_qrcount (' +
// 'logid , qrid, qrurl, marketid, request_host,' +
// 'request_origin, request_useragent,logdatetime) ' +
// ' VALUES (?, ?, ?, ?, ?, ?, ?, ?);',
// [
// logid, qrid, qrurl, marketID, request_host,
// request_origin, request_useragent, logdatetime
// ]
// ,function(err, res2) {
// if (err) {
// console.error('Produce scan tracking error occured');
// console.error('error', err);
// }
// console.log('Produce scan tracking successful');
// //callback(null, res2); // think 'return'
// });
//END Track QR Scan
provenance_data['user'] = req.user;
provenance_data['showTracedOnBlockchain'] = boolTracedOnBlockchain;
provenance_data['page_name'] = 'home';
//res.end() method to send data to client as json string via JSON.stringify() methoD
res.end(JSON.stringify(provenance_data, null, 4));
}); //end of connection.execute*/
});
//TODO Add Weekly View route and template
//TODO Add Weekly View REST API
//return template with market checkin form e.g. http://localhost:3000/checkin/ozcf
router.get('/checkin/:market_id', [sanitizeParam('market_id').escape().trim()], function (req, res) {
var boolCheckinForm = process.env.SHOW_CHECKIN_FORM || false
var marketID = req.params.market_id; //shortcode e.g. ozcf
var logid = uuidv4()
var qrid = '' //TODO this is not yet being tracked in config
var qrurl = req.protocol + '://' + req.get('host') + req.originalUrl;
var request_host = req.get('host')
var request_origin = req.headers.referer
//req.headers.referer - The Referer request header contains the address of the previous web page
//from which a link to the currently requested page was followed.
//The Referer header allows servers to identify where people are visiting them from and may use that data for analytics, logging, or optimized caching, for example.
//alternative would have been to use origin request header
//The Origin request header indicates where a fetch originates from.
var request_useragent = req.headers['user-agent']
var logdatetime = new Date();
//TODO - cross check marketID against existing marketID's from foodprint_market
try {
let data = {
logid: logid,
qrid: qrid,
qrurl: qrurl,
marketID: marketID,
request_host: request_host,
request_origin: request_origin,
request_useragent: request_useragent,
logdatetime: logdatetime
}
models.FoodprintQrcount
.create(data)
.then(() => {
console.log('Market checkin tracking successful');
//res.json({ success: true, email: checkin_email });
})
.catch(err => {
//req.flash('error', err);
//console.error('error', err)
console.error('Market checkin tracking error occured');
// res.status.json({ err: err });
})
/*connection.execute('\n' +
'INSERT INTO foodprint_qrcount (\n' +
' logid ,\n' +
' qrid,\n' +
' qrurl,\n' +
' marketid,\n' +
' request_host,\n' +
' request_origin,\n' +
' request_useragent,\n' +
' logdatetime)\n' +
'VALUES (?, ?, ?, ?, ?, ?, ?, ?);',
[
logid,
qrid,
qrurl,
marketID,
request_host,
request_origin,
request_useragent,
logdatetime
], function (err, rows) {
if (err) {
//req.flash('error', err);
//console.error('error', err)
console.error('Market checkin tracking error occured');
// res.status.json({ err: err });
} else {
console.log('Market checkin tracking successful');
//res.json({ success: true, email: checkin_email });
}
});*/
} catch (e) {
//TODO log the error
//this will eventually be handled by your error handling middleware
//next(e)
//res.json({success: false, errors: e});
//console.error('error', err)
console.error('Market checkin tracking error occured');
res.render('checkin.ejs', {data: marketID, showCheckinForm: boolCheckinForm, user: req.user, page_name: 'checkin'});
}
res.render('checkin.ejs', {data: marketID, showCheckinForm: boolCheckinForm, user: req.user, page_name: 'checkin'});
});
//market checkin XmlHTTP request
router.post('/marketcheckin', [
check('checkin_email', 'Your email is not valid').not().isEmpty().isEmail().normalizeEmail(),
],
function (req, res) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.json({errors: errors.array(), success: false});
} else {
var checkin_market_id = req.body.checkin_market_id;
var checkin_email = req.body.checkin_email;
var checkin_datetime = new Date();
var checkin_firstname = '';
var checkin_surname = '';
let data = {
market_id: checkin_market_id,
firstname: checkin_firstname,
surname: checkin_surname,
email: checkin_email,
logdatetime: checkin_datetime,
}
try {
models.MarketSubscription
.create(data)
.then(_ => {
console.log('add market_subscription DB success');
res.json({success: true, email: checkin_email});
})
.catch( err => {
//req.flash('error', err);
console.error('error', err);
res.status.json({err: err});
})
/*connection.execute('\n' +
'INSERT INTO market_subscription (\n' +
' market_id ,\n' +
' firstname,\n' +
' surname,\n' +
' email,\n' +
' logdatetime)\n' +
'VALUES (?, ?, ?, ?, ?);',
[
checkin_market_id,
checkin_firstname,
checkin_surname,
checkin_email,
checkin_datetime
], function (err, rows) {
if (err) {
//req.flash('error', err);
console.error('error', err);
res.status.json({err: err});
} else {
console.log('add market_subscription DB success');
res.json({success: true, email: checkin_email});
}
});*/
} catch (e) {
//this will eventually be handled by your error handling middleware
next(e)
res.json({success: false, errors: e});
}
}
});
/*router.get('/test_db',
require('connect-ensure-login').ensureLoggedIn({redirectTo: '/app/auth/login'}),
async (req, res, next) => {
if (req.user.role === ROLES.Admin || req.user.role === ROLES.Superuser) {