forked from christopher-pott/CATSReferenceCollectionsDb
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
1310 lines (1158 loc) · 46.2 KB
/
app.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
/**********************
* Module dependencies
**********************/
var express = require('express'),
cors = require('cors'),
fs = require('fs'),
logger = require("./logging"),
nodeExcel = require('excel-export'),
routes = require('./routes'),
api = require('./routes/api'),
http = require('http'),
https = require('https');
path = require('path'),
db = require("./db_mongo"),
Q = require('q'),
bcrypt = require('bcrypt-nodejs'),
SALT_WORK_FACTOR = 10,
passport = require('passport'),
negotiator = require('negotiator'),
gm = require('gm'),
config = require('./config');
var app = module.exports = express();
var MongoStore = require('connect-mongo')(express);
/****************
* Configuration
****************/
/*set port to whatever is in the environment variable PORT, or 3000 if there's nothing there.*/
//app.set('port', process.env.PORT || 3443);
if (app.get('env') === 'development') {
app.set('views', __dirname + '/views');
app.use(express.errorHandler());
}
/* production only */
if (app.get('env') === 'production') {
app.set('views', __dirname + '/dist/views');
app.use('/dist', express.static(__dirname + '/dist'));
}
app.set('view engine', 'jade');
logger.debug("Overriding 'Express' logger");
app.use(express.logger({format: 'dev', stream: logger.stream }));
/* BodyParser is bundled In Express 3, so no 'require' needed
* BodyParser allows Express to handle JSON, URLEncoded and multipart bodies in requests.
* However, we'll define them separately, because we want to set a limit
* for multiparts only (default limits are 1mb for json and urlencoded and we don't want to
* increase these).
*
* These apply to incoming bodies on all routes.
* */
//app.use(express.bodyParser());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart({
keepExtensions: true,
limit: 1024 * 1024 * 20, /*upload file size limit*/
defer: true /*don't stream to temp files*/
}));
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use('/public', express.static(__dirname + '/public'));
/*Passport middleware : must be before 'router'*/
app.use(express.cookieParser());
/*Use connect-mongo to persist sessions to db instead of RAM*/
app.use(express.session({
secret: 'rory gallagher',
store: new MongoStore({
db: 'cats'
})
}));
app.use(passport.initialize());
app.use(passport.session());
/*End Passport middleware*/
app.use(app.router);
app.use(cors());
/**************************
* Passport authentication
**************************/
var LocalStrategy = require('passport-local').Strategy;
/**
* Bcrypt middleware : return hashed password
*/
function encrypt(password, next) {
/*if(!user.isModified('password')) return next();*/
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if(err) return next(err);
bcrypt.hash(password, salt, null, function(err, hash) {
if(err) return next(err, null);
password = hash;
return next(null,password);
});
});
};
function findById(id, fn) {
var _id = db.ObjectId(id);
db.users.find({"_id": _id}).toArray(function(err, users) {
if(err || !users){return fn(err, null);}
if(users){return fn(null, users[0]);}
});
}
function findByUsername(username, fn) {
db.users.find({"username": username}).toArray(function(err, users) {
if(err || !users){return fn(err, null);}
if(users){return fn(null, users[0]);}
});
}
/*Passport strategy (local) Used when authenticating*/
passport.use(new LocalStrategy( function(username, password, done) {
/* Find the user by username. If there is no user with the given username
or the password is not correct then return an error, otherwise, return the
authenticated user*/
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
/* compare password with the hash */
bcrypt.compare(password, user.password, function(err, isMatch) {
if(err || !isMatch) return done(null, false, { message: 'Incorrect password.' });
return done(null, user);
});
})
}));
/*Passport sessions*/
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
findById(id, function (err, user) {
done(err, user);
});
});
/*Passport authentication Routes*/
/* login :
* Returns: user, or null if authentication failed
*/
app.post('/login', passport.authenticate('local'), function(req, res) {
logger.info('user ' + req.user.username.toString() + ' logged in');
res.status(200).send(req.user);
});
/* logout */
app.post('/logout', function(req, res){
if(req.isAuthenticated()){
logger.info('user ' + req.user.username.toString() + ' logging out');
req.logOut();
}else{
logger.info('logout request, but user not logged in');
}
res.send(200);
});
/* route to test if the user is logged in or not */
app.get('/loggedin', function(req, res) {
res.status(200).send(req.isAuthenticated() ? req.user : '0');
});
/********************
* Helper functions
********************/
/**
* buildSampleQuery
*
* Builds this mongo query used for searching samples:
*
* ({$and:[{$or: [{"productionDate" : {$lte: endDate}}, {"artwork.productionDateEarliest" : {$lte: endDate}}]},
* {$or: [{"productionDate" : {$gte: startDate}}, {"artwork.productionDateLatest" : {$gte: startDate}}]},
* {"sampleType.name": sampletype},
* {"$text": {"$search": fulltext}
* }]
* })
*
* Usage: accepts a request url containing any combination of these 4 queries:
* ?fulltext=search string&sampletype=Paint Cross Section&startdate=1850&enddate=1900
*/
function buildSampleQuery(req) {
var query = {};
var filters = [];
var fullText = req.query.fulltext;
var sampleType = req.query.sampletype;
/* date query requires ISO strings
* remove time as artwork date times are not relevant and can break the application
*/
var startDate = (req.query.startdate) ? new Date(req.query.startdate).toISOString().replace(/T.*Z/, '') : null;
var endDate = (req.query.enddate) ? new Date(req.query.enddate).toISOString().replace(/T.*Z/, '') : null;
if (fullText){filters.push({"$text" : {"$search": fullText}});}
if (sampleType){filters.push({"sampleType.name": sampleType});}
/* searches by date should use the related artwork date, except for pigments
* which have their own production dates (named productionDate)
*/
if (endDate){
filters.push({$or: [{"productionDate" : {$lte: endDate}}, {"artwork.productionDateEarliest" : {$lte: endDate}}]});
}
if (startDate){
filters.push({$or: [{"productionDate" : {$gte: startDate}}, {"artwork.productionDateLatest" : {$gte: startDate}}]});
}
/*apply AND operation to any filters*/
if(filters.length){
query.$and = filters;
}
return query;
}
/**
* Excel export (requires 'excel-export' module)
*/
function buildSampleExcel(query) {
var result = null;
/* use Q.defer() to create a deferred. Deferred is used to
* implement custom methods returning promises. We need to make a
* promise as the database query is asynch and this function may return
* before it completes. The calling function can use .then() to handle the
* completed promise*/
var deferred = Q.defer();
db.samples.find(query)
.sort('referenceNumber')
.toArray(function(err, items) {
if(err || !items){
logger.error(err);
}else if(items){
/*build excel sheet*/
var body = items;
var conf ={};
conf.cols = [
{
caption:'Sample Type',
type:'string',
width:20
},{
caption:'Ref.num',
type:'string',
width:20
},{
caption:'Sample origin',
type:'string',
width:20
},{
caption:'Sample date',
type:'string',
width:20
},{
caption:'Institution',
type:'string',
width:30
},{
caption:'Employee',
type:'string',
width:20
},{
caption:'Sample location',
type:'string',
width:20
},{
caption:'Remarks',
type:'string',
width:30
},{
caption:'Fibre type(s)',
type:'string',
width:30
},{
caption:'Fibre glue',
type:'string',
width:30
},{
caption:'(Fibre) Ligin',
type:'string',
width:10
},{
caption:'(Fibre) Alum',
type:'string',
width:10
},{
caption:'(Fibre) Filler',
type:'string',
width:10
},{
caption:'Material type(s)',
type:'string',
width:30
},{
caption:'(Paint) Priming',
type:'string',
width:15
},{
caption:'Paint layers description',
type:'string',
width:30
},{
caption:'Paint layers',
type:'string',
width:30
},{
caption:'(Pigment) Colour Classification',
type:'string',
width:20
},{
caption:'(Pigment) Source',
type:'string',
width:20
},{
caption:'(Pigment) Production no./Batch no.',
type:'string',
width:30
},{
caption:'(Pigment) Secondary provenance',
type:'string',
width:20
},{
caption:'(Pigment) Place of origin',
type:'string',
width:20
},{
caption:'(Pigment) Chemical composition',
type:'string',
width:20
},{
caption:'Pigment name',
type:'string',
width:20
},{
caption:'(Pigment) Other names',
type:'string',
width:20
},{
caption:'(Pigment) Form',
type:'string',
width:20
},{
caption:'(Pigment) Production date',
type:'string',
width:20
},{
caption:'(Pigment) Container',
type:'string',
width:20
},{
caption:'Stretcher type',
type:'string',
width:20
},{
caption:'(Stretcher) Material type',
type:'string',
width:20
},{
caption:'(Stretcher) Condition',
type:'string',
width:20
},{
caption:'(Stretcher) Joint technique',
type:'string',
width:20
},{
caption:'(Stretcher) Dimensions',
type:'string',
width:20
},{
caption:'(Stretcher) Production earliest',
type:'string',
width:20
},{
caption:'(Stretcher) Production date latest',
type:'string',
width:20
},{
caption:'(Stretcher) Source',
type:'string',
width:20
},{
caption:'Sample Analysis',
type:'string',
width:30
},{
caption:'Artwork Inventory Num.',
type:'string',
width:20
},{
caption:'Artwork Title',
type:'string',
width:20
},{
caption:'Artist',
type:'string',
width:20
},{
caption:'Artist nationality',
type:'string',
width:20
},{
caption:'Artwork Technique',
type:'string',
width:20
},{
caption:'Artwork production date earliest',
type:'string',
width:20
},{
caption:'Artwork production date latest',
type:'string',
width:20
},{
caption:'Artwork dimensions',
type:'string',
width:20
},{
caption:'Artwork owner',
type:'string',
width:20
}];
conf.rows = [];
for (i = 0; i<body.length; i++){
var ii = 0;
/*shared fields */
conf.rows[i] = [];
conf.rows[i][ii++] = body[i].sampleType.name;
conf.rows[i][ii++] = (body[i].referenceNumber) ? body[i].referenceNumber : null;
conf.rows[i][ii++] = (body[i].originLocation) ? body[i].originLocation : null;
conf.rows[i][ii++] = (body[i].sampleDate) ? body[i].sampleDate : null;
conf.rows[i][ii++] = (body[i].owner && body[i].owner.name) ? body[i].owner.name : null;
conf.rows[i][ii++] = (body[i].employee) ? body[i].employee : null;
conf.rows[i][ii++] = (body[i].sampleLocation) ? body[i].sampleLocation : null;
conf.rows[i][ii++] = (body[i].remarks) ? body[i].remarks : null;
/*paper fields*/
conf.rows[i][ii++] = (body[i].fibreType) ? body[i].fibreType.map(function(elem){return elem.name;}).join(", ") : null;
conf.rows[i][ii++] = (body[i].fibreGlue) ? body[i].fibreGlue.map(function(elem){return elem.name;}).join(", ") : null;
conf.rows[i][ii++] = (body[i].fibreLigin) ? true : null;
conf.rows[i][ii++] = (body[i].fibreAlum) ? true : null;
conf.rows[i][ii++] = (body[i].fibreFiller) ? true : null;
/*material fields*/
conf.rows[i][ii++] = (body[i].materialType) ? body[i].materialType.map(function(elem){return elem.name;}).join(", ") : null;
/*paint fields*/
conf.rows[i][ii++] = (body[i].paintPriming) ? true : null;
conf.rows[i][ii++] = (body[i].paintLayerDescription) ? body[i].paintLayerDescription : null;
conf.rows[i][ii++] = (body[i].paintLayer && body[i].paintLayer[0].layerType.name) ?
body[i].paintLayer.map(function(elem){
/*format all layer data for a single cell*/
var layer = "";
var binders = (elem.paintBinder) ? elem.paintBinder.map(function(elem){return elem.name;}).join(", ") : "";
var colours = (elem.colour) ? elem.colour.map(function(elem){return elem.name;}).join(", ") : "";
var pigments = (elem.pigment) ? elem.pigment.map(function(elem){return elem.name;}).join(", ") : "";
var dyes = (elem.dye) ? elem.dye.map(function(elem){return elem.name;}).join(", ") : "";
layer = elem.layerType.name + " layer" +
"\n Binders: " + binders +
"\n Colours: " + colours +
"\n Pigments: " + pigments +
"\n Dyes: " + dyes;
return layer;
}).join("\n\n") : null;
/*pigment fields*/
conf.rows[i][ii++] = (body[i].pigmentColourClass && body[i].pigmentColourClass.name) ? body[i].pigmentColourClass.name : null;
conf.rows[i][ii++] = (body[i].pigmentSource) ? body[i].pigmentSource : null;
conf.rows[i][ii++] = (body[i].pigmentProdNumber) ? body[i].pigmentProdNumber : null;
conf.rows[i][ii++] = (body[i].pigmentSecondryProvenance) ? body[i].pigmentSecondryProvenance : null;
conf.rows[i][ii++] = (body[i].pigmentOrigin) ? body[i].pigmentOrigin : null;
conf.rows[i][ii++] = (body[i].pigmentComposition) ? body[i].pigmentComposition : null;
conf.rows[i][ii++] = (body[i].pigmentName && body[i].pigmentName.name) ? body[i].pigmentName.name : null;
conf.rows[i][ii++] = (body[i].pigmentOtherName) ? body[i].pigmentOtherName : null;
conf.rows[i][ii++] = (body[i].pigmentForm && body[i].pigmentForm.name) ? body[i].pigmentForm.name : null;
conf.rows[i][ii++] = (body[i].productionDate) ? body[i].productionDate : null;
conf.rows[i][ii++] = (body[i].pigmentContainer && body[i].pigmentContainer.name) ? body[i].pigmentContainer.name : null;
/*stretcher fields*/
conf.rows[i][ii++] = (body[i].stretcherType) ? body[i].stretcherType.map(function(elem){return elem.name;}).join(", ") : null;
conf.rows[i][ii++] = (body[i].stretcherMaterialType) ? body[i].stretcherMaterialType.map(function(elem){return elem.name;}).join(", ") : null;
conf.rows[i][ii++] = (body[i].stretcherCondition && body[i].stretcherCondition.name) ? body[i].stretcherCondition.name : null;
conf.rows[i][ii++] = (body[i].stretcherJointTechnique) ? body[i].stretcherJointTechnique.map(function(elem){return elem.name;}).join(", ") : null;
conf.rows[i][ii++] = (body[i].stretcherDimensions) ? body[i].stretcherDimensions : null;
conf.rows[i][ii++] = (body[i].stretcherProductionDateEarliest) ? body[i].stretcherProductionDateEarliest : null;
conf.rows[i][ii++] = (body[i].stretcherProductionDateLatest) ? body[i].stretcherProductionDateLatest : null;
conf.rows[i][ii++] = (body[i].stretcherSource) ? body[i].stretcherSource : null;
/*analysis field*/
conf.rows[i][ii++] = (body[i].sampleAnalysis && body[i].sampleAnalysis[0].type) ? body[i].sampleAnalysis.map(function(elem){return elem.type.name;}).join(", ") : null;
/*artwork fields*/
conf.rows[i][ii++] = (body[i].artwork && body[i].artwork.inventoryNum) ? body[i].artwork.inventoryNum : null;
conf.rows[i][ii++] = (body[i].artwork && body[i].artwork.title) ? body[i].artwork.title : null;
conf.rows[i][ii++] = (body[i].artwork && body[i].artwork.artist) ? body[i].artwork.artist : null;
conf.rows[i][ii++] = (body[i].artwork && body[i].artwork.nationality) ? body[i].artwork.nationality : null;
conf.rows[i][ii++] = (body[i].artwork && body[i].artwork.technique) ? body[i].artwork.technique : null;
conf.rows[i][ii++] = (body[i].artwork && body[i].artwork.productionDateEarliest) ? body[i].artwork.productionDateEarliest : null;
conf.rows[i][ii++] = (body[i].artwork && body[i].artwork.productionDateLatest) ? body[i].artwork.productionDateLatest : null;
conf.rows[i][ii++] = (body[i].artwork && body[i].artwork.dimensions) ? body[i].artwork.dimensions : null;
conf.rows[i][ii++] = (body[i].artwork && body[i].artwork.owner) ? body[i].artwork.owner : null;
}
result = nodeExcel.execute(conf);
}
/* Calling resolve with a non-promise value causes promise to be
* fulfilled with that value */
deferred.resolve(result);
});
/* return the promises to be resolved later */
return deferred.promise;
};
/********************
* Define the Routes
********************/
/* index and view partials */
app.get('/', routes.index);
app.get('/partials/:name', routes.partials);
/* JSON API */
app.get('/api/name', api.name);
/**********************
* PROXY operations
**********************/
/*
* Search Corpus(solr) for SMK artworks
*
* Proxy to SMKs collectionspace solr instance as browser rejects cross origin
* requests. Response can be chunked, so we pipe all chunks back to the client.
*
* Usage : searchsmk?id=KMS1
*/
app.get('/searchsmk', function(req, res) {
var id = req.query.id;
var options = {
host: 'solr.smk.dk', //'csdev-seb',
port: 8080, // 8180,
path: '/solr/prod_CATS/' + //'/solr-example/dev_cats/
'select?q=id_s%3A' + id + '&wt=json&indent=true', /*id_s also works on verso & multiworks*/
method: 'GET'
};
var proxy = http.request(options, function (resp) {
resp.pipe(res, {
end: true
});
});
proxy.on('error', function(err) {
// Solr is down or otherwise not visible
logger.error("couldn't contact solr");
res.send(502); //"502 : Bad Gateway"
});
req.pipe(proxy, {
end: true
});
});
/********************
* SAMPLE operations
********************/
/**
* Retrieve all samples
*
* Returns JSON or an Excel .xlxs binary, depending on the media type accepted by the client.
*
* Optionally accepts the following filter parameters :
* fulltext (mongodb full text search on all samples)
* sampletype
* startDate
* endDate
* pageNum
* pageSize
* count (if 'true' only returns a result count)
*
* Usage: 1. All samples : sample
* 2. Samples with filter : sample?type=sample&fulltext=blue&sampletype=Paint%20Cross%20Section
* &startDate=&endDate==&pageNum=1&pageSize=50
*/
app.get('/sample', function(req, res) {
/*use the HTTP content negotiator library to parse requested media types*/
var media = new negotiator(req);
var supportedMedia = ['application/json', 'application/vnd.openxmlformats'];
var preferredMedia = media.mediaType(supportedMedia);
if (preferredMedia == 'application/json'){
var pageSize = parseInt(req.query.pageSize); /*limit() requires int*/
var pageNum = parseInt(req.query.pageNum);
var query = buildSampleQuery(req);
if(req.query.count == 'true'){
/*only return a count*/
db.samples.find(query)
.count(function(err, count) {
if(err || !count){
res.status(200).send("0");
}else{
logger.info("searchSize: " + count);
res.status(200).send(count.toString());
}
});
}else{
db.samples.find(query)
.skip(pageNum > 0 ? ((pageNum-1)*pageSize) : 0)
.limit(pageSize)
.sort('referenceNumber')
.toArray(function(err, items) {
if(err || !items){
logger.error(err);
res.status(500).send(err);
}else{
res.status(200).send(items);
}
});
}
}else if (preferredMedia == 'application/vnd.openxmlformats'){
var query = buildSampleQuery(req);
var result = buildSampleExcel(query);
result.then(function(report){
//this is called if promise has completed with success
if(report == null){
res.send(500);
}else{
res.setHeader('Content-Type', preferredMedia);
res.setHeader("Content-Disposition", "attachment; filename=" + "Report.xlsx");
res.end(report, 'binary');
}
}, function (err) {
//this is called if promise completed with failure
res.send(500);
});
}else{
res.send(406); /* "not acceptable" : we don't support the requested client media */
}
});
/**
* Retrieve a single sample
*
* Usage: sample/{sample _id}
*/
app.get('/sample/:id', function(req, res) {
/*use the HTTP content negotiator library to parse requested media types*/
var media = new negotiator(req);
var supportedMedia = ['application/json'];
var preferredMedia = media.mediaType(supportedMedia);
if (preferredMedia == 'application/json'){
var id = req.params.id;
try{
id = db.ObjectId(id);
}catch (err){
res.send(400); /*bad request, id probably not hex*/
return;
}
var query = {'_id' : id};
db.samples.find(query)
.toArray(function(err, items) {
if(err || !items){
logger.error(err);
res.status(500).send(err);
}else{
res.status(200).send(items);
}
});
}else{
res.send(406); /* "not acceptable" : we don't support the requested client media */
}
});
/**
* Create a sample
*
* Create or update the record depending on the existence of the "_id" parameter in the body
* Probably not very RESTful as the client doesn't know if a new resource will be created.
*
* Body may or may not contain an '_id', which may or may not be an existing one
*
* Returns the relative path of the updated object in the 'location' header.
*/
app.post('/sample', function(req, res) {
if (!req.isAuthenticated()){
res.send(401);
return;
}
var body = req.body;
if(!body || JSON.stringify(body) == '{}'){
res.send(400); /*bad request, no body*/
return;
}
try{
body._id = db.ObjectId(body._id);
}catch (err){
res.send(400); /*bad request, id probably not hex*/
return;
}
var query = {'_id' : body._id };
var options = { 'upsert': true };
db.samples.update(query, body, options, function (err, response) {
if (err || !response){
logger.info(body.sampleType + " not saved");
res.send(500); /*server error*/
} else {
logger.info('upsert successful ');
var status = 201;
var _id = '';
if(req.body._id){
_id = req.body._id;
}else if(response.upserted){
_id = response.upserted[0]._id;
}
if (response.updatedExisting){
status = 200;
}
res.header('Location', 'sample/' + _id);
res.status(status).send(response);
}
});
});
/**
* Delete a sample
*
* If successful returns the number of deleted records. Should only be an error if the
* operation failed, even if resource is not found, delete has succeeded.
*/
app.delete('/sample/:id', function(req, res){
if (!req.isAuthenticated()){
res.send(401);
return;
}
var id = req.params.id;
try{
id = db.ObjectId(id);
}catch (err){
res.send(400);
return;
}
logger.info("DELETE " + id);
db.samples.remove({"_id": id}, function(err, numberRemoved){
if (err){
logger.error("delete failed");
res.status(500).send(err);
} else {
logger.info("delete successful");
res.status(200).send(numberRemoved);
}
});
});
/*********************
* USER operations
*********************/
/**
* Updates or inserts (upserts) a new user record in mongodb using mongojs.
* Probably not very RESTful as the client doesn't know if a new resource will be created.
*
* Returns the relative path of the updated object in the the location header.
*
* Usage: POST with body = {"username": email, "password": password, "role": role}
*
* Command line hint: curl -H "Content-Type: application/json"
* --cookie "connect.sid=s%3AIzaNbY6BuBKwcZxkdKI73Mo4.S6hhH7mzJPooqfXPI4TPIdKZws3Cxq3lDYmL%2FEtqgNw"
* -d '{"username":"[email protected]", "password":"a_password"}'
* http://localhost:3000/user
*/
app.post('/user', function(req, res){
if (!req.isAuthenticated()){
res.send(401); /*unauthorised*/
return;
};
/* send user details in request body rather than as url parameters to avoid
* server logging and browser history caching */
var username = req.body.username;
var password = req.body.password;
var role = req.body.role;
if(!username || !password){
res.send(400); /*bad request*/
return;
}
/*only admin can edit others passwords*/
if(req.user.username != username && req.user.role != "admin"){
res.send(401); /*unauthorised*/
return;
};
/*Only admin can alter role*/
if(req.user.role != "admin"){
role = "default";
};
/*setup mongo findAndModify options*/
var options = {};
options.query = {'username' : username}; /*query by username*/
options.upsert = true; /*if query doesn't find a record then insert a new one */
options.new = true; /*return the modified document (not the original)*/
options.fields = {username: 1}; /*define fields for the returned document: just the id*/
password = encrypt(password, function(err, hash) {
/*called when encrypt resolved*/
options.update = {$set: {"username": username, "password": hash, "role": role}}; /*data to write to the record*/
if (err || !hash){
logger.error("could not encrypt password");
res.status(500).send(err);
} else {
db.users.findAndModify(options, function (err, record, lastErr) {
if (err || !record){
logger.error("user " + username + " not saved");
res.status(500).send(err);
} else {
logger.info('user upsert successful, username: ' + record.username);
res.header('Location', 'user/' + record._id);
res.status(200).send(record);
}
});
}
});
});
/**
* Delete a user profile
* If successful returns the number of deleted records
*
* Usage: [email protected]
*/
app.delete('/user', function(req, res){
if (!req.isAuthenticated() || req.user.role != "admin"){
res.send(401);
return;
};
if(!req.query || !req.query.username){
res.send(400);
return;
}
var username = req.query.username;
db.users.remove({"username": username}, function(err, numberRemoved){
if (err || !numberRemoved){
logger.error("delete failed");
res.status(500).send(err);
} else {
logger.info("delete successful");
res.status(200).send(numberRemoved);
}
});
});
/*********************
* ARTWORK operations
*********************/
/**
* Updates or inserts (upserts) a new artwork record in mongodb using mongojs
* Probably not very RESTful as the client doesn't know if a new resource will be created
*
* Returns the relative path of the updated object in the the location header
*
* Usage: POST with {artworkbody}
*
*/
app.post('/artwork', function(req, res){
if (!req.isAuthenticated()){
res.send(401);
return;
};
var body = req.body;
if(!body || JSON.stringify(body) == '{}'){
res.send(400); /*bad request, no body*/
return;
}
try{
body._id = db.ObjectId(body._id);
}catch (err){
res.send(400); /*bad request, id probably not hex*/
return;
}
var options = {};
options.query = {'_id' : body._id}; /*query by _id*/
options.upsert = true; /*if query doesn't find a record then insert a new one */
options.new = true; /*return the modified document (not the original)*/
options.fields = {_id: 1}; /*define fields for the returned document: just the id*/
options.update = {$set: body}; /*data to write to the record*/
/* findAndModify() can upsert a single record and return the new record _id, which update()
* cannot*/
db.artworks.findAndModify(options, function (err, record, lastErr) {
if (err || !record){
logger.error("artwork " + body.title + " not saved");
res.status(500).send(err);
} else {
logger.info('artwork upsert successful, _id: ' + record._id);
res.header('Location', 'artwork/' + record._id);
res.status(200).send(record);
}
});
});
/**
* Retrieve artwork(s)
* If successful returns the artwork object in json
*
* Optionally accepts the following filter parameter :
* invNum
*
* Usage: artwork?invNum=KMS456
*/
app.get('/artwork', function(req, res) {
var media = new negotiator(req);
var supportedMedia = ['application/json'];
var preferredMedia = media.mediaType(supportedMedia);
if (preferredMedia == 'application/json'){
var query = {};
var invNum = req.query.invNum;
if(invNum){
/* Regex will be inefficient, but we must have a case insensitive search for
* inventory numbers as we don't want to duplicate records */
var rg = new RegExp('^'+ invNum + '$', "i");
query = {"inventoryNum" : { "$regex" : rg }};
}
db.artworks.find(query)
.toArray(function(err, items) {
if (err || !items){
logger.error("failed to retrieve artworks with query : " + JSON.stringify(query));
res.status(500).send(err);
} else {
logger.info("found artworks");
res.status(200).send(items);
}
})
}else{
res.send(406); /* "not acceptable" : we don't support the requested client media */