-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
1729 lines (1581 loc) · 65.4 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
restify = require('restify'),
url = require('url'),
mongoose = require('mongoose'),
bunyan = require('bunyan'),
util = require('util'),
Schema = mongoose.Schema,
config = require('./config.js'),
db = mongoose.connect(config.creds.mongoose_auth),
schemas = require('./schema.js'),
//populateDB = require('./data_import.js'),
Brand = mongoose.model('Brand', schemas.BrandSchema),
AttributeDomain = mongoose.model('AttributeDomain', schemas.AttributeDomainSchema),
Cigar = mongoose.model('Cigar', schemas.CigarSchema),
User = mongoose.model('User', schemas.UserSchema),
App = mongoose.model('App', schemas.AppSchema),
UpdateRequest = mongoose.model('UpdateRequest', schemas.UpdateRequestSchema),
DeleteRequest = mongoose.model('DeleteRequest', schemas.DeleteRequestSchema),
APILog = mongoose.model('APILog', schemas.LogSchema),
CigarDB = {}; // Namespace
// Constants
CigarDB.APPROVED = 'approved';
CigarDB.CREATE_PENDING = 'create_pending';
CigarDB.PENDING = 'pending';
CigarDB.DENIED = 'denied';
CigarDB.DELETED = 'deleted';
CigarDB.DEV_DAILY_LIMIT_REQUESTS = 500;
CigarDB.DEV_DAILY_LIMIT_HOURS = 24;
CigarDB.MODERATOR = 99;
CigarDB.PREMIUM = 10;
CigarDB.DEVELOPER = 0;
CigarDB.CLEANED_STATUS_DIRTY = 'dirty';
CigarDB.CLEANED_STATUS_PROCESSING = 'processing';
CigarDB.CLEANED_STATUS_CLEANED = 'cleaned';
CigarDB.cleanEmptyList = function (val) {
// Feeling kind of anal about these list values.
if (val === ['']) {
return [];
} else {
return val;
}
};
// Assemble the object which defines our custom log fields
CigarDB.buildCustomLogFields = function (req, err) {
var log_object = {};
if (err) {
log_object.err = err;
}
if (req.params) {
log_object.api_key = req.params.api_key;
log_object.params = req.params;
} else {
log_object.api_key = req.api_key;
}
log_object.req = req;
return log_object;
};
// My Bunyan stream for saving log entries to MongoDB
CigarDB.saveLog = function () {
};
CigarDB.saveLog.prototype.write = function (rec) {
if (typeof (rec) !== 'object') {
console.error('error: raw stream got a non-object record: %j', rec)
} else {
var new_log = new APILog();
for (param in rec) {
new_log[param] = rec[param];
}
new_log.save(function (err, new_log_instance) {
if (err) {
// Could not save log entry. Fail silently and with much shame. /facepalm
}
});
}
};
// My custom JSON formatter, based off default code. Adds ValidationError handling for Mongoose validation
CigarDB.cigarDBFormatJSON = function (req, res, body) {
if (body instanceof Error) {
// snoop for RestError or HttpError, but don't rely on
// instanceof
res.statusCode = body.statusCode || 500;
if (body.name && body.name == 'ValidationError') {
var err_msg = '';
if (Object.keys(body.errors).length > 1) {
var fields_in_error = Object.keys(body.errors);
err_msg = 'The following fields failed validation: ' + fields_in_error.join(', ');
} else {
if (body.errors[Object.keys(body.errors)[0]].type == 'required') {
err_msg = 'The field ' + Object.keys(body.errors)[0] + ' is required.';
} else {
err_msg = body.errors[Object.keys(body.errors)[0]].type;
}
}
body = {
message: err_msg
};
} else if (body.body) {
body = body.body;
} else {
body = {
message: body.message
};
}
} else if (Buffer.isBuffer(body)) {
body = body.toString('base64');
}
var data = JSON.stringify(body);
res.setHeader('Content-Length', Buffer.byteLength(data));
return (data);
}
CigarDB.getBrands = function (req, res, next) {
// Return a list of all brands, paginated or
// search for brands by name if name parameter supplied.
// Premium members get full list without paging.
var limit = (req.access_level > CigarDB.DEVELOPER) ? 0 : 50,
page = (req.params.page) ? req.params.page : 1,
skip = (page > 1) ? page * 50 : 0,
options_obj = {skip: skip},
return_obj = {message: '', data: []},
query_obj = {status: CigarDB.APPROVED},
doc_count = 0;
if (limit > 0) {
options_obj.limit = limit;
}
if (req.params.name) {
query_obj.name = new RegExp(req.params.name, 'i');
}
// Get a count of documents in this query to we can calculate number of pages later.
Brand.find(query_obj, 'name').count().exec().then(
function (count) {
doc_count = count;
return Brand.find(query_obj, '', options_obj).sort('name').lean().exec(); // Returns a promise
}
).then(
function (brands) {
// TODO admins can query non-approved
if (brands.length == 0) {
throw new restify.ResourceNotFoundError("No records found!");
} else {
return_obj.numberOfPages = Math.floor(doc_count / limit);
return_obj.currentPage = parseInt(page);
for (var i = 0; brands[i]; i++) {
var current_doc = {};
for (field in brands[i]) {
// Remove Mongoose version field and rename MongoDB _id field for return
if (field == '__v') {
continue;
} else if (field == '_id') {
current_doc.id = brands[i][field];
} else {
current_doc[field] = brands[i][field];
}
}
return_obj.data.push(current_doc);
}
res.send(return_obj);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: getBrands: All clear');
return next();
}
}
).then(null, function (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getBrands: ' + err.message);
return next(err);
});
};
CigarDB.getBrand = function (req, res, next) {
// Return a single Brand
var
limit_fields = 'name location established website status updated',
return_obj = {data: {}};
if (!req.params.id) {
var err = new restify.MissingParameterError("You must supply an ID.");
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getBrand: ID parameter not provided');
return next(err);
}
Brand.findOne({_id: req.params.id, status: CigarDB.APPROVED}, limit_fields).exec(function (err, doc) {
if (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getBrand: Query failed');
return next(err);
} else if (!doc) {
var err = new restify.ResourceNotFoundError("Brand not found!");
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getBrand: Query returned no documents');
return next(err);
} else {
res.status(200);
for (field in doc) {
// Remove Mongoose version field and rename MongoDB _id field for return
if (field == '__v') {
continue;
} else if (field == '_id') {
return_obj.data.id = doc[field];
} else {
return_obj['data'][field] = doc[field];
}
}
res.send(return_obj);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: getBrand: All clear');
return next();
}
});
};
CigarDB.createBrand = function (req, res, next) {
// Create a new Brand entry
// Minimum required field is name
if (!req.params.name) {
var err = new restify.MissingParameterError('You must supply at least a name.');
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: createBrand: Name parameter not provided');
return next(err);
}
('Creating a new brand');
// Let's fill in the values manually
var name = req.params.name,
status = CigarDB.CREATE_PENDING,
location = req.params.location || '',
established = req.params.established || 0,
brand = new Brand();
if (req.access_level == CigarDB.MODERATOR) {
// Admins skip the queue
status = CigarDB.APPROVED;
}
brand.name = name;
brand.status = status;
brand.location = location;
brand.established = established;
brand.save(function (err, brand) {
if (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: createBrand: Save failed');
return next(err);
} else {
res.status(202);
var data = {"data": {"id": brand.id}, "message": "The brand has been created and is awaiting approval."};
res.send(data);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: createBrand: All clear');
return next();
}
});
};
CigarDB.updateBrand = function (req, res, next) {
if (!req.params.id) {
var err = new restify.MissingParameterError('You must supply an ID.');
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: updateBrand: ID parameter not provided');
return next(err);
}
var
brand_updates = {};
if (req.access_level === CigarDB.MODERATOR) {
for (param in req.params) {
brand_updates[param] = req.params[param];
}
brand_updates.updated = Date.now();
Brand.findByIdAndUpdate(req.params.id, brand_updates).exec().then(function (updated_brand) {
if (!updated_brand) {
throw new Error('Brand update failed.');
} else {
res.status(200);
var data = {"message": "The update has been processed."};
res.send(data);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: updateBrand MODERATOR: All clear');
return next();
}
}).then(null, function (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: updateBrand MODERATOR: ' + err.message);
return next(err);
});
} else {
var update_req = new UpdateRequest();
update_req.type = 'brand';
update_req.api_key = req.api_key;
update_req.data = req.params;
update_req.status = CigarDB.PENDING;
update_req.save(function (err, update_req) {
if (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: updateBrand: Save failed');
return next(err);
} else {
res.status(202);
var data = {"message": "The update has been submitted and is awaiting approval."};
res.send(data);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: updateBrand: All clear');
return next();
}
})
}
};
CigarDB.removeBrand = function (req, res, next) {
var err;
if (!req.params.id) {
err = new restify.MissingParameterError('You must supply an ID.');
} else if (!req.params.reason && req.access_level < CigarDB.MODERATOR) {
err = new restify.MissingParameterError('You must provide a reason.');
}
if (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: removeBrand: Required parameter not provided');
return next(err);
}
if (req.access_level == CigarDB.MODERATOR) {
reason = req.params.reason || '';
Brand.findByIdAndUpdate(req.params.id, {status: CigarDB.DELETED, reason: reason}).exec().then(function (removed_brand) {
if (!removed_brand) {
throw new Error('Brand update failed.');
} else {
res.status(200);
data = {"message": "The brand was marked as deleted."};
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: removeBrand MODERATOR: All clear');
return next();
}
}).then(null, function (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: removeBrand MODERATOR: ' + err.message);
return next(err);
}
);
} else {
var delete_req = new DeleteRequest();
delete_req.target_id = req.params.id;
delete_req.reason = req.params.reason;
delete_req.type = 'brand';
delete_req.api_key = req.api_key;
delete_req.status = CigarDB.PENDING;
delete_req.save(function (err, delete_req) {
if (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: removeBrand: Save failed');
return next(err);
} else {
res.status(202);
var data = {"message": "The delete request has been submitted and is awaiting approval."};
res.send(data);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: removeBrand: All clear');
return next();
}
});
}
};
CigarDB.getCigars = function (req, res, next) {
/*
Return a list of all cigars, paginated
User must filter by at least 1 field, unless they are premium.
*/
var
param_found = false,
doc_count = 0,
limit = (req.access_level > CigarDB.DEVELOPER) ? 9999 : 50,
page = (req.params.page) ? req.params.page : 1,
skip = (page > 1) ? page * 50 : 0,
sort_field = '',
limit_fields = (req.params.limit_fields) ? 'name brand' : '',
required_fields = ['brand', 'name', 'vitola', 'color', 'fillers', 'wrappers', 'binders', 'strength'],
query_obj = {status: CigarDB.APPROVED},
return_obj = {};
for (param in req.params) {
if (required_fields.indexOf(param) != -1) {
if (param == 'name') {
query_obj[param] = new RegExp(req.params.name, 'i');
} else if (param == ('fillers' || 'wrappers' || 'binders')) {
query_obj[param] = {};
query_obj[param]['$in'] = req.params[param].split(',');
} else {
query_obj[param] = req.params[param];
}
param_found = true;
}
}
if (!param_found && req.access_level < CigarDB.PREMIUM) {
var err = new restify.MissingParameterError("You must supply at least one field.");
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getCigars: Required parameter not provided');
return next(err);
}
if (req.params.sort_field) {
sort_field = req.params.sort_field;
if (req.params.sort_direction && req.params.sort_direction == 'desc') {
sort_field = '-' + sort_field;
}
}
// Get a count of documents in this query to we can calculate number of pages later.
Cigar.find(query_obj, 'name').count().exec().then(
function (count) {
doc_count = count;
// Query that mofo!
return Cigar.find(query_obj, limit_fields, {limit: limit, skip: skip}).sort(sort_field).lean().exec();
}
).then(
function (cigars) {
if (cigars.length == 0) {
throw new restify.ResourceNotFoundError("No records found!");
} else {
return_obj.numberOfPages = Math.floor(doc_count / limit);
return_obj.currentPage = page;
return_obj.data = [];
for (var i = 0; cigars[i]; i++) {
var current_doc = {};
for (field in cigars[i]) {
// Remove Mongoose version field and rename MongoDB _id field for return
if (field == '__v') {
continue;
} else if (field == '_id') {
current_doc.id = cigars[i][field];
} else {
current_doc[field] = cigars[i][field];
}
}
return_obj.data.push(current_doc);
}
res.status(200);
res.send(return_obj);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: getCigars: All clear');
return next();
}
}
).then(null, function (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getCigars: ' + err.message);
return next(err);
});
};
CigarDB.getCigar = function (req, res, next) {
// Return a single Cigar
if (!req.params.id) {
var err = new restify.MissingParameterError("You must supply an ID.");
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getCigar: ID parameter not provided');
return next(err);
}
Cigar.findOne({_id: req.params.id, status: CigarDB.APPROVED}, '').lean().exec(function (err, doc) {
if (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getCigar: Query failed');
return next(err);
} else if (!doc) {
var err = new restify.ResourceNotFoundError("Cigar not found.");
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getCigar: Query returned no documents');
return next(err);
} else {
var return_obj = {data: {}};
res.status(200);
for (field in doc) {
// Remove Mongoose version field and rename MongoDB _id field for return
if (field == '__v') {
continue;
} else if (field == '_id') {
return_obj.data.id = doc[field];
} else {
return_obj['data'][field] = doc[field];
}
}
res.send(return_obj);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: getCigar: All clear');
return next();
}
});
};
// TODO handle querying status (e.g.: admins looking for documents in the queue)
CigarDB.createCigar = function (req, res, next) {
// Create a new Cigar entry (aka: Where the Magic Happens)
// Minimum required fields are brand and name
var
return_obj = {data: {}, message: ''},
cigar = new Cigar();
for (param in req.params) {
if (req.list_fields.indexOf(param) != -1 && !util.isArray(req.params[param])) {
req.params[param] = CigarDB.cleanEmptyList(req.params[param].split(','));
}
cigar[param] = req.params[param];
}
// Admins skip the queue
if (req.access_level == CigarDB.MODERATOR) {
cigar.status = CigarDB.APPROVED;
} else {
cigar.status = CigarDB.CREATE_PENDING;
}
// Let's make sure the brand they specified already exists. createCigar() is no place to createBrand()
// Don't check status so that users can create brands and cigars together without waiting for brands to get approved.
Brand.find({name: cigar.brand, $or: [
{status: CigarDB.APPROVED},
{status: CigarDB.CREATE_PENDING}
]}, 'name').exec().then(
function (brands) {
if (brands.length == 0) {
throw new restify.ResourceNotFoundError("The Brand you specified was not found in the database. If you want to add a new brand and associated cigars, please create the brand first.");
}
// Mongoose.Model.save() doesn't return a promise! Lame!
cigar.save(function (err, cigar) {
if (err) {
throw new Error('Failed to save new cigar.')
} else {
res.status(202);
return_obj.message = "The cigar has been created and is awaiting approval."
return_obj.data = {"id": cigar.id};
res.send(return_obj);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: createCigar: All clear');
return next();
}
});
}
).then(null, function (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: createCigar: ' + err.message);
return next(err);
});
};
CigarDB.updateCigar = function (req, res, next) {
var
cigar_updates = {};
if (!req.params.id) {
var err = new restify.MissingParameterError("You must supply an ID.");
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: updateCigar: ID parameter not provided');
return next(err);
}
if (req.access_level === CigarDB.MODERATOR) {
for (param in req.params) {
if (req.list_fields.indexOf(param) != -1 && !util.isArray(req.params[param])) {
req.params[param] = CigarDB.cleanEmptyList(req.params[param].split(','));
}
cigar_updates[param] = req.params[param];
}
cigar_updates.updated = Date.now();
Cigar.findByIdAndUpdate(req.params.id, cigar_updates).exec().then(function (updated_cigar) {
if (!updated_cigar) {
throw new Error('Cigar update failed.');
} else {
res.status(200);
var data = {"message": "The update has been processed."};
res.send(data);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: updateCigar MODERATOR: All clear');
return next();
}
}).then(null, function (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: updateCigar MODERATOR: ' + err.message);
return next(err);
});
} else {
var update_req = new UpdateRequest();
update_req.type = 'cigar';
update_req.target_id = req.params.id;
update_req.api_key = req.api_key;
update_req.data = req.params;
update_req.status = CigarDB.PENDING;
update_req.save(function (err, update_req) {
if (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: updateCigar: Save failed');
return next(err);
} else {
res.status(202);
var data = {"message": "The update has been submitted and is awaiting approval."};
res.send(data);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: updateCigar: All clear');
return next();
}
})
}
};
CigarDB.removeCigar = function (req, res, next) {
var
err,
reason,
data = {};
if (!req.params.id) {
err = new restify.MissingParameterError('You must supply an ID.');
} else if (!req.params.reason && req.access_level < CigarDB.MODERATOR) {
err = new restify.MissingParameterError('You must provide a reason.');
}
if (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: removeCigar: Required parameter not provided');
return next(err);
}
if (req.access_level == CigarDB.MODERATOR) {
reason = req.params.reason || '';
Cigar.findByIdAndUpdate(req.params.id, {status: CigarDB.DELETED, moderator_notes: reason}).exec().then(function (removed_cigar) {
if (!removed_cigar) {
throw new Error('Cigar update failed.');
} else {
res.status(200);
data = {"message": "The cigar was marked as deleted."};
res.send(data);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: removeCigar MODERATOR: All clear');
return next();
}
}).then(null, function (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: removeCigar MODERATOR: ' + err.message);
return next(err);
}
);
} else {
var delete_req = new DeleteRequest();
delete_req.target_id = req.params.id;
delete_req.reason = req.params.reason;
delete_req.api_key = req.api_key;
delete_req.type = 'cigar';
delete_req.status = CigarDB.PENDING;
delete_req.save(function (err, delete_req) {
if (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: removeCigar: Save failed');
return next(err);
} else {
res.status(202);
data = {"message": "The delete request has been submitted and is awaiting approval."};
res.send(data);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: removeCigar: All clear');
return next();
}
});
}
};
CigarDB.getCigarsCreateRequests = function (req, res, next) {
/*
Return a list of all cigars with status 'create_pending'
*/
var
doc_count = 0,
sort_field = 'updated',
query_obj = {status: CigarDB.CREATE_PENDING},
return_obj = {};
// Moderators only!
if (req.access_level < CigarDB.MODERATOR) {
var err = new restify.NotAuthorizedError("You are not authorized!");
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getCigarsCreateRequests: ' + err.message);
return next(err);
}
if (req.params.sort_field) {
sort_field = req.params.sort_field;
if (req.params.sort_direction && req.params.sort_direction == 'desc') {
sort_field = '-' + sort_field;
}
}
// Get a count of documents in this query
Cigar.find(query_obj, 'name').count().exec().then(
function (count) {
doc_count = count;
// Query that mofo!
return Cigar.find(query_obj).sort(sort_field).lean().exec();
}
).then(
function (cigars) {
if (cigars.length == 0) {
throw new restify.ResourceNotFoundError("No records found!");
} else {
return_obj.numberOfDocuments = doc_count;
return_obj.data = [];
for (var i = 0; cigars[i]; i++) {
var current_doc = {};
for (field in cigars[i]) {
// Remove Mongoose version field and rename MongoDB _id field for return
if (field == '__v') {
continue;
} else if (field == '_id') {
current_doc.id = cigars[i][field];
} else {
current_doc[field] = cigars[i][field];
}
}
return_obj.data.push(current_doc);
}
res.status(200);
res.send(return_obj);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: getCigarsCreateRequests: All clear');
return next();
}
}
).then(null, function (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getCigarsCreateRequests: ' + err.message);
return next(err);
});
};
CigarDB.approveCigarCreation = function (req, res, next) {
// Approve a create cigar request
var
return_obj = {data: {}, message: ''},
cigar = {};
for (param in req.params) {
if (req.list_fields.indexOf(param) != -1) {
req.params[param] = CigarDB.cleanEmptyList(req.params[param].split(','));
}
cigar[param] = req.params[param];
}
// Moderators only!
if (req.access_level < CigarDB.MODERATOR) {
var err = new restify.NotAuthorizedError("You are not authorized!");
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: approveCigarCreation: ' + err.message);
return next(err);
} else {
cigar.status = CigarDB.APPROVED;
}
// Let's make sure the brand they specified already exists.
Brand.find({name: cigar.brand, status: CigarDB.APPROVED}, 'name').exec().then(
function (brands) {
if (brands.length == 0) {
throw new restify.ResourceNotFoundError("The Brand you specified was not found in the database. If you want to add a new brand and associated cigars, please create the brand first.");
}
return Cigar.update({_id: req.params.id}, cigar).exec();
}
).then(
function (numberAffected, raw) {
if (numberAffected != 1) {
throw new restify.ResourceNotFoundError('No records where updated (Check your query).');
} else {
res.status(200);
return_obj.message = 'Cigar approved!';
return_obj.data = raw;
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: approveCigarCreation: All clear');
return next();
}
}
).then(null, function (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: approveCigarCreation: ' + err.message);
return next(err);
});
};
CigarDB.denyCigarCreation = function (req, res, next) {
// Deny a create cigar request
var
return_obj = {data: {}, message: ''},
cigar = {moderator_notes: req.params.moderator_notes};
// Moderators only!
if (req.access_level < CigarDB.MODERATOR) {
var err = new restify.NotAuthorizedError("You are not authorized!");
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: denyCigarCreation: ' + err.message);
return next(err);
} else {
cigar.status = CigarDB.DENIED;
}
Cigar.update({_id: req.params.id}, cigar).exec().then(
function (numberAffected, raw) {
if (numberAffected != 1) {
throw new restify.ResourceNotFoundError('No records where updated (Check your query).');
} else {
res.status(200);
return_obj.message = 'Cigar denied!';
return_obj.data = raw;
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: denyCigarCreation: All clear');
return next();
}
}
).then(null, function (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: denyCigarCreation: ' + err.message);
return next(err);
});
};
CigarDB.getCigarsUpdateRequests = function (req, res, next) {
/*
Return a list of all cigars update requests
*/
var
doc_count = 0,
sort_field = 'date_submitted',
query_obj = {type: 'cigar', status: CigarDB.PENDING},
return_obj = {};
// Moderators only!
if (req.access_level < CigarDB.MODERATOR) {
var err = new restify.NotAuthorizedError("You are not authorized!");
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getCigarsUpdateRequests: ' + err.message);
return next(err);
}
if (req.params.sort_field) {
sort_field = req.params.sort_field;
if (req.params.sort_direction && req.params.sort_direction == 'desc') {
sort_field = '-' + sort_field;
}
}
// Get a count of documents in this query
UpdateRequest.find(query_obj, 'name').count().exec().then(
function (count) {
doc_count = count;
// Query that mofo!
return UpdateRequest.find(query_obj).sort(sort_field).lean().exec();
}
).then(
function (update_reqs) {
if (update_reqs.length == 0) {
throw new restify.ResourceNotFoundError("No records found!");
} else {
return_obj.numberOfDocuments = doc_count;
return_obj.data = [];
for (var i = 0; update_reqs[i]; i++) {
var current_doc = {};
for (field in update_reqs[i]) {
// Remove Mongoose version field and rename MongoDB _id field for return
if (field == '__v') {
continue;
} else if (field == '_id') {
current_doc.id = update_reqs[i][field];
} else {
current_doc[field] = update_reqs[i][field];
}
}
return_obj.data.push(current_doc);
}
res.status(200);
res.send(return_obj);
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: getCigarsUpdateRequests: All clear');
return next();
}
}
).then(null, function (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getCigarsUpdateRequests: ' + err.message);
return next(err);
});
};
CigarDB.approveCigarUpdate = function (req, res, next) {
// Approve an update cigar request
var
return_obj = {data: {}, message: ''},
mod_changes = {};
for (param in req.params) {
if (req.list_fields.indexOf(param) != -1) {
req.params[param] = CigarDB.cleanEmptyList(req.params[param].split(','));
}
mod_changes[param] = req.params[param];
}
// Moderators only!
if (req.access_level < CigarDB.MODERATOR) {
var err = new restify.NotAuthorizedError("You are not authorized!");
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: approveCigarUpdate: ' + err.message);
return next(err);
} else {
mod_changes.status = CigarDB.APPROVED;
}
UpdateRequest.findByIdAndUpdate(req.params.id, {status: CigarDB.APPROVED}).exec().then(
function (update_req) {
if (!update_req) {
throw new restify.ResourceNotFoundError('Update request was not archived (Check your query).');
} else {
return Cigar.update({_id: mod_changes.target_id}, mod_changes).exec();
}
}
).then(
function (numberAffected, raw) {
if (numberAffected != 1) {
throw new restify.ResourceNotFoundError('No records where updated (Check your query).');
} else {
res.status(200);
return_obj.message = 'Cigar update approved!';
return_obj.data = raw;
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: approveCigarUpdate: All clear');
return next();
}
}
).then(null, function (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: approveCigarUpdate: ' + err.message);
return next(err);
});
};
CigarDB.denyCigarUpdate = function (req, res, next) {
// Deny an update cigar request
var
return_obj = {data: {}, message: ''},
update_req = {
moderator_notes: req.params.moderator_notes,
status: CigarDB.DENIED
};
// Moderators only!
if (req.access_level < CigarDB.MODERATOR) {
var err = new restify.NotAuthorizedError("You are not authorized!");
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: denyCigarUpdate: ' + err.message);
return next(err);
}
UpdateRequest.update({_id: req.params.id}, update_req).exec().then(
function (numberAffected, raw) {
if (numberAffected != 1) {
throw new restify.ResourceNotFoundError('No records where updated (Check your query).');
} else {
res.status(200);
return_obj.message = 'Cigar update denied!';
return_obj.data = raw;
req.log.info(CigarDB.buildCustomLogFields(req), 'SUCCESS: denyCigarUpdate: All clear');
return next();
}
}
).then(null, function (err) {
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: denyCigarUpdate: ' + err.message);
return next(err);
});
};
CigarDB.getCigarsDeleteRequests = function (req, res, next) {
/*
Return a list of all cigars delete requests
*/
var
doc_count = 0,
sort_field = 'date_submitted',
query_obj = {type: 'cigar', status: CigarDB.PENDING},
return_obj = {};
// Moderators only!
if (req.access_level < CigarDB.MODERATOR) {
var err = new restify.NotAuthorizedError("You are not authorized!");
req.log.info(CigarDB.buildCustomLogFields(req, err), 'ERROR: getCigarsDeleteRequests: ' + err.message);
return next(err);
}
if (req.params.sort_field) {
sort_field = req.params.sort_field;
if (req.params.sort_direction && req.params.sort_direction === 'desc') {
sort_field = '-' + sort_field;
}
}
// Get a count of documents in this query
DeleteRequest.find(query_obj, 'name').count().exec().then(
function (count) {
doc_count = count;
// Query that mofo!
return DeleteRequest.find(query_obj).sort(sort_field).lean().exec();
}
).then(
function (delete_reqs) {
if (delete_reqs.length == 0) {
throw new restify.ResourceNotFoundError("No records found!");
} else {
return_obj.numberOfDocuments = doc_count;
return_obj.data = [];
for (var i = 0; delete_reqs[i]; i++) {
var current_doc = {};
for (field in delete_reqs[i]) {
// Remove Mongoose version field and rename MongoDB _id field for return
if (field == '__v') {
continue;
} else if (field == '_id') {
current_doc.id = delete_reqs[i][field];
} else {
current_doc[field] = delete_reqs[i][field];
}
}
return_obj.data.push(current_doc);