-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdmincontroller.js
860 lines (842 loc) · 44.7 KB
/
Admincontroller.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
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json());
var User = require('./User');
var Logs = require('./Logs');
var Job = require('./Job');
const Faq = require('./Faq');
const Orders = require('./Orders');
const Main_menu = require('./Main_menu'); //so the admins can modify on JAB, CRUD this schema.
const Nft = require('./Nft');
var Image = require('./Image'); //this one for now do not a controller but can be used anywhere, for now just in admincontroller.
var Img = require('./Img'); //using this one as it seems when created it prints the first config and cannot change later on
var Category = require('./Category');
// TODO: add logs access withint admincontroller and remove it from
// logs- maybe?
// var Logs = require('../logs/Logs');
var jwt = require('jsonwebtoken');
var config = require('./config');
const time = new Date();
const sharp = require('sharp');
//in order to being able to handle images here all definitions on cloudinary + multer
//declarations
//cloudinary CDN images
var cloudinary = require('cloudinary').v2;
//config
cloudinary.config({
cloud_name: config.cloud_name,
api_key: config.api_key,
api_secret: config.api_secret,
});
/////////////
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, callback) {
if(config.testingData){
(file) ? console.log('Destination:::::::File::::::',file) : console.log('No file from client');
}
callback(null, __dirname + '/uploads')
},
filename: function (req, file, callback) {
if(config.testingData){
(file) ? console.log('Filename:::::::File::::::',file) : console.log('No file from client');
}
callback(null, file.fieldname + '_' + Date.now() + "_" + file.originalname);
}
});
const upload = multer({ storage: storage }).single("file");
const uploadMultiple = multer({ storage: storage }).array("file"); //to use on multiple so we can keep the first one as uploading one file only
//////to delete the file after sending it to cloud
const fs = require('fs');
let resultHandler = function (err) {
if (err) {
console.log("unlink failed", err);
} else {
console.log("file deleted from temporary server storage");
}
}
////////////////////////////////////////////////////////////////////
// BAN USER
// ---> TODO: Ask for better logic, maybe just the admins can ban users and not admins.
router.post('/ban/:username', function(req, res){
var token = req.headers['x-access-token'];
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
// console.log(decoded);
// To apply more secufiry we could look up this user as admin....
const data = req.body;
console.log(data);
// console.log(`User to be Banned: ${data.username}\n Reason: ${data.reason}`);
User.findOneAndUpdate({ username: data.username }, { banned: true }, {new: true}, function(err, user){
if(err) return res.status(500).send("There was a problem banning the user.");
//user banned so create log
//create log
// -----> TODO search this Admin on DB and bring his data.
Logs.create({
username: decoded.username,
usertype: 'admin',
createdAt: time,
ipaddress: req.ip,
event: `Banning ${data.username}`,
reason: data.reason,
},
function(err, log){
if(err){console.log('Error trying to add new Log on DB!',err)}
if(log){
console.log(`logID:${log.id}`);
}
}
);
res.status(200).send(user);
console.log(`Updated User on DB. \n username:${user.username} \n time:${time}\nNew Status: Banned!`);
});
}else{
return res.status(500).send({ auth: false, message: 'Error authenticating token GET user.' });
}
});
})
/////////////////////////
//////handle get the images on DB
router.get('/getImgBank',function(req,res){
const token = req.headers['x-access-token'];
const filter = JSON.parse(req.headers['filter']) || {};
const limit = Number(req.headers['limit']) || 0; //just in case no number comes from request.
const sort = JSON.parse(req.headers['sort']) || {}; //as { createdAt: -1 } { field: -1} -1 desc || { field: 1} 1 asc.
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
if(config.testingData){
console.log('filtering on jobs AdminController:',filter);
console.log('Limit:',limit);
console.log('Sort:',sort)
}
Img.find(filter, function(err, imgs){
if(err){
if(config.testingData) {console.log('Error finding on images bank',err)};
return res.status(500).send({ status: 'failed', message: err });
}
return res.status(200).send({ status: 'sucess', result: imgs });
}).sort(sort).limit(limit)
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
}
});
});
//////END handle get the images on DB
//////handle get the images on DB
router.post('/deleteImgOnBank',function(req,res){
// TODO: i have a better idea, we should use the OPlogger right here instead that on client.
// this will improve client's performance as server is much more powerful...DA!!!
const token = req.headers['x-access-token'];
const filter = JSON.parse(req.headers['filter']); //as { _id: '' } in order to handle it better.
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
if(config.testingData){
console.log('filtering to Delete on jobs AdminController:',filter);
}
Img.deleteOne(filter, function(err, ack){
if(err){
if(config.testingData) {console.log('Error deleting on images bank',err)};
return res.status(500).send({ status: 'failed', message: err });
}
return res.status(200).send({ status: 'sucess', result: ack });
})
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
}
});
});
//////END handle get the images on DB
//////Special sections a upload images into Images Bank for the blog
router.post('/uploadImgsToBank',function(req,res){
const token = req.headers['x-access-token'];
const thumbs = req.headers['createthumbs']; //as 'true' or 'false'
if(config.testingData){
console.log(req.headers);
console.log(`thumbs: ${thumbs}`);
};
var thumbImagesUploaded = [];
//TODO check if userType = 'admin'
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
//cloudinary loop depending if at least one image to upload to server and then CDN.
uploadMultiple(req, res, function (err) {
if (err) {
console.log('Err Uploading Multiple Images.',err);
return res.status({ status: 'failed', message: err });
}
if(thumbs === 'true' || thumbs === "true"){
if(config.testingData) { console.log('Creating thumbs as requested!!!')};
let promise_thumbs = req.files.map(file => new Promise((resolve,reject) => {
let outputFile = "thumb-" + Date.now() + file.originalname;
sharp(file.path).resize({ width: 100 }).toFile(outputFile)
.then(function(newFileInfo) {
newFileInfo.path = outputFile;
cloudinary.uploader.upload(newFileInfo.path,{ tags: 'JAB-thumbs'}, function(err, image){
if(err) reject(err)
else {
resolve(image.secure_url);
fs.unlink(newFileInfo.path, resultHandler);
}
})
})
.catch(err => reject(err));
}));
Promise.all(promise_thumbs)
.then(result => { //result is the array holding the thumb images as we need them.
const thumbImages = result;
//from here we can call create on mongoDB passing req,thumbImages.
// return res.status(200).send({ status: 'sucess', result: thumbImages }); //sent for now as created thumbs + uploaded
saveData(req,thumbImages);
}).catch((error) => {
if(config.testingData){ console.log('Error creating/uploading the thumbs.',error)}
return res.status(500).send({'status': 'failed', 'message': error})
});
}else{
// todo and move the create process to it own function and pass just the req.
saveData(req,null);
}
//stoping until here for testing the thumbs processing
//moved as a function bellow but inside the router.
});
//END cloudinary loop
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
}
});
//handle to save into mongoDB
function saveData(req,thumbImages){
if(config.testingData){
console.log(thumbImages ? 'we have thumbs' : 'no thumbs received!');
if(thumbImages) { console.log(thumbImages)};
}
let res_promises = req.files.map(file => new Promise((resolve,reject) => {
cloudinary.uploader.upload(file.path,{ tags: JSON.parse(req.body.tags)}, function(err, image){
if(err) reject(err)
else {
resolve(image.secure_url);
fs.unlink(file.path, resultHandler);
}
})
}))
Promise.all(res_promises)
.then(result => { //result is the array holding the images as we need them.
const images = result;
if(config.testingData){ console.log('To save:',images)};
//at this point if we have thumbImages !== null then we use them.
let save_promises = images.map((image, index) => new Promise((resolve,reject) => {
const imgRecord = !thumbImages ? { image: image, title: req.body.title, createdAt: req.body.createdAt, relatedTo: JSON.parse(req.body.relatedTo), tags: JSON.parse(req.body.tags)}
: { image: image, title: req.body.title, createdAt: req.body.createdAt, relatedTo: JSON.parse(req.body.relatedTo), tags: JSON.parse(req.body.tags), thumb: thumbImages[index] }
Img.create(imgRecord, function(err,createdImg){
if(err) reject(err)
else {
resolve(createdImg);
}
})
}))
Promise.all(save_promises)
.then(result =>{//result is the array holding the images as we need them.
if(config.testingData){ console.log('Created new images:', result)};
return res.status(200).send({ status: 'sucess', result: result }) //sucess
})
.catch((error) => { res.status(500).send({'status': 'failed', 'message': error})});
})
.catch((error) => { res.status(400).send({'status': 'failed', 'message': error})});
}
});
//////END Special sections a upload images into Images Bank for the blog
///////Main_menu handling CRUD///////
//as a way to start standarization i will use the better approach as used in /getJob using: jwt+filter+limit+sort
router.get('/getMmenuJab', function(req,res){
const token = req.headers['x-access-token'];
const filter = JSON.parse(req.headers['filter']) || {}; //if not provided by default brings all.
const limit = Number(req.headers['limit']) || 0; //just in case no number comes from request.
const sort = JSON.parse(req.headers['sort']) || {}; //as { createdAt: -1 } { field: -1} -1 desc || { field: 1} 1 asc.
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
if(config.testingData){
console.log('filtering on Main_Menu AdminController:',filter);
console.log('Limit:',limit);
console.log('Sort:',sort);
}
Main_menu.find(filter, function(err, menus){
if(err){
if(config.testingData) {console.log('Error finding Main_menu',err)};
return res.status(500).send({ status: 'failed', message: err });
}
return res.status(200).send({ status: 'sucess', result: menus });
}).sort(sort).limit(limit)
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
}
});
});
router.post('/addMmenuJab', function(req,res){
const token = req.headers['x-access-token'];
const titlemenu = req.headers['titlemenu']; //must be provided to search first to be sure it doesnt exists.
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
if(config.testingData){ console.log('Trying to add on Main Menu:', titlemenu)};
Main_menu.findOne({ title: titlemenu }, function(err, found){
if(err){ if(config.testingData) {console.log('Error finding Main_menu', err)};
return res.status(500).send({ status: 'failed', message: err });
}
if(found){ return res.status(404).send({ status: 'failed', message: 'Menu with that title already added. Please choose another title.'})};
upload(req, res, function(err){
if(err){
if(config.testingData){ console.log('Error processing on multer.',err) };
return res.status(500).send({ status: 'failed', message: err});
};
if(config.testingData){ console.log('As not found on Main_menu, trying to add:', req.body) };
Main_menu.create(req.body, function(err, menu){
if(err){
if(config.testingData){ console.log('Error trying to add new menu.', err) };
return res.status(500).send({ status: 'failed', message: err });
}
return res.status(200).send({ status: 'sucess', result: menu });
})
});
});
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
}
});
});
//handle updates/edition on main_menus JAB.
router.post('/updateMmenuJab', function(req,res){
const token = req.headers['x-access-token'];
const titlemenu = req.headers['titlemenu']; //must be provided to search first to be sure it doesnt exists.
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
if(config.testingData){ console.log('Trying to Update on Main Menu:', titlemenu)};
upload(req, res, function(err){
if(err){
if(config.testingData){ console.log('Error processing on multer.',err) };
return res.status(500).send({ status: 'failed', message: err});
};
if(config.testingData){ console.log('Trying to update:', req.body) };
Main_menu.findOneAndUpdate({ title: titlemenu }, req.body, { new: true }, function(err, updated){
if(err){
if(config.testingData){ console.log('Error trying to update menu.', err) };
return res.status(500).send({ status: 'failed', message: err });
}
return res.status(200).send({ status: 'sucess', result: updated });
})
});
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
}
});
});
///////END Main_menu handling CRUD///////
///////handle FAQ section///////////
//////GET query on FAQs
//Important Note: leaving as public query for now.
router.get('/getFaq', function(req,res){
const token = req.headers['x-access-token']; //query= {'filter': {}, 'limit': 0, 'sort': {} }; sort as { createdAt: -1 };
const query = JSON.parse(req.headers['query']);
if(!query) return res.status(404).send({ status: 'failed', message: 'No query provided!' });
if(config.testingData){ console.log('filtering on FAQ Admin', query); };
Faq.find(query.filter, function(err, faqs){
if(err){
if(config.testingData) {console.log('Error finding FAQ',err)};
return res.status(500).send({ status: 'failed', message: err });
}
return res.status(200).send({ status: 'sucess', result: faqs });
}).sort(query.sort).limit(query.limit);
});
router.post('/handleFaq', function(req,res){
const token = req.headers['x-access-token'];
const query = JSON.parse(req.headers['query']); //as query = { 'operation': 'create,delete', 'faq_id': 'String' };
if(!query || !query.operation){ return res.status(404).send({ status: 'failed', message: 'Operation or query not provided!'})};
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
uploadMultiple(req, res, function(err){
if(err){
if(config.testingData){ console.log('Error multer, faq processing.', err)};
return res.status(500).send({ status: 'failed', message: err });
}
if(req.files && query.operation === 'create'){
let res_promises = req.files.map(file => new Promise((resolve,reject) => {
cloudinary.uploader.upload(file.path,{ tags: ['imageFAQ','jobabord']}, function(err, image){
if(err) reject(err)
else {
resolve(image.secure_url);
fs.unlink(file.path, resultHandler);
}
})
}));
Promise.all(res_promises).then(result => { //result is the array holding the images as we need them.
const images = result;
saveDataFAQ(req, images);
}).catch((error) => res.status(500).send({ status: 'failed', message: error }) );
}else{
saveDataFAQ(req, null);
}
});
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
}
});
function saveDataFAQ(req, images){
if(query.operation === 'create'){
const data = req.body;
data.questions_list = JSON.parse(data.questions_list);
if(images){
data.images = images;
}
Faq.create(data, function(err, newFaq){
if(err){
if(config.testingData){ console.log('Error handling FAQ', err)};
return res.status(500).send({ status: 'failed', message: err });
}
return res.status(200).send({ status: 'sucess', message: `FAQ created.`, result: newFaq });
});
}else{ //just delete for now. Edit later on.
Faq.findByIdAndDelete(query.faq_id, function(err, result){
if(err){
if(config.testingData){ console.log('Error deleting FAQ', err)};
return res.status(500).send({ status: 'failed', message: err });
}
return res.status(200).send({ status: 'sucess', message: `FAQ Deleted.`, result: result });
});
}
}
});
//////END Get query on FAQs
///////END handle FAQ section///////////
///////Job sections controlled by Admins
///////////handling job queries from admins
router.get('/getJob', function(req,res){
const token = req.headers['x-access-token'];
const filter = JSON.parse(req.headers['filter']) || {};
const limit = Number(req.headers['limit']) || 0; //just in case no number comes from request.
const sort = JSON.parse(req.headers['sort']) || {}; //as { createdAt: -1 } { field: -1} -1 desc || { field: 1} 1 asc.
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
if(config.testingData){
console.log('filtering on jobs AdminController:',filter);
console.log('Limit:',limit);
console.log('Sort:',sort)
}
Job.find(filter, function(err, jobs){
if(err){
if(config.testingData) {console.log('Error finding jobs',err)};
return res.status(500).send({ status: 'failed', message: err });
}
return res.status(200).send({ status: 'sucess', result: jobs });
}).sort(sort).limit(limit)
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
}
});
});
///////////END handling job queries from admins
//////////handling update one field on job by admins || system - originally just to handle blocked, note.
router.post('/updateJobField', function(req,res){
const token = req.headers['x-access-token'];
const filter = JSON.parse(req.headers['filter']);//as { username: '', _id: ''} mandatory to process the update
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
upload(req, res, function(err){
if(err){
console.log('Error processing on multer.',err);
return res.status(500).send({ status: 'failed', message: err});
};
//upload the data and grab the results.
if(config.testingData){
console.log('filtering on Update/job AdminController:',filter);
console.log('Admin:', decoded.usernameHive);
console.log('About to update:',req.body);
}
if(req.file){
//for now we don't use this but leave it for future use.
}else{
Job.findOneAndUpdate(filter, req.body, { returnNewDocument: true },function(err, updatedJob){
if(err){
if(config.testingData) {console.log('Error updating fields on jobs',err)};
return res.status(500).send({ status: 'failed', message: err });
}
return res.status(200).send({ status: 'sucess', result: updatedJob });
});
}
});
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
}
});
});
///////END Job sections controlled by Admins
////////Web content section
///handling delete category
router.post('/deleteCat', function(req,res){
// TODO, for each of the admin methods we MUST check if admin as user_type
// make a method that by using the username.decoded, finds on user and return true if admin. false otherwise.
const token = req.headers['x-access-token'];
const catid = req.headers['catid'];
if(!catid){
if(config.testingData){ console.log('Cat deletion request no id provided.')}
return res.status(404).send({ status: 'failed', message: 'I cannot delete no Id cat. Funny guy!'});
}
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
Category.deleteOne({ _id: catid }, function(err,deleted){
if(err){
if(config.testingData){ console.log('Error when deleting Category.',err)};
return res.status(500).send({ status: 'failed', message: err });
}
return res.status(200).send({ status: 'sucess', result: deleted });
});
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
};
});
});
////handling update a cat.
router.post('/updateCat', function(req,res){
var image,thumb;
const token = req.headers['x-access-token'];
const query = req.headers['query']; //as { name: 'string', query: 'string'} name of category and query in order to search if already exists or not.
if(!query){
if(config.testingData){ console.log('Not query provided.')};
return res.status(404).send({ status:'failed', message: 'I cannot process empty queries. Funny boy!'});
}
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
const filter = JSON.parse(query);
Category.findOne(filter, function(err,catFound){
if(err){
if(config.testingData){console.log('Error searching for category.',err)};
return res.status(500).send({ status: 'failed', message: err});
}
if(!catFound){
if(config.testingData){console.log('Category not exists.')};
return res.status(404).send({ status: 'failed', message: 'Category not present on DB.'});
}
//as we don't find any, we add so multer get to work from here.
upload(req, res, function(err){
if(err){
console.log('Error processing on multer.',err);
return res.status(500).send({ status: 'failed', message: err});
};
//upload the data and grab the results.
if(req.file){
if(config.testingData) {console.log('There is file on new cat, so lets use it!')};
cloudinary.uploader.upload(req.file.path,{ tags: 'newCat'}, function(error, result){
if(error){
console.log('Error uploading img to cloudinary.',error);
//as we really need the image to make the cat work we stop here and return err
return res.status(500).send({ status: 'failed', message: error});
}
//image is the uploaded img
image = result.secure_url;
if(config.testingData) {console.log(`Image uploaded. ${image}`)};
//here we should apply the transformation and upload it also.
// we will test sharp to resize the image and upload it as well, then we take both fields and save into db
let inputFile = req.file.path;
let outputFile = "thumb-" + Date.now() + req.file.originalname;
sharp(inputFile).resize({ width: 200 }).toFile(outputFile) //thumb for cats is 200px wide for now
.then(function(newFileInfo) {
// newFileInfo holds the output file properties
// console.log(`Success resizing ${inputFile}`);
newFileInfo.path = outputFile;
console.log(`Now we handle to upload:`);
console.log(newFileInfo);
cloudinary.uploader.upload(newFileInfo.path,{ tags: 'newCatThumb'}, function(error, thumbUploaded){
if(error){
if(config.testingData) {console.log('Error uploading thumb.',error)}
return res.status(500).send({ status: 'failed', message: error});
}
console.log('Sucess, thumb uploaded. Now we get the new name.');
thumb = thumbUploaded.secure_url;
console.log(`Thumb uploaded. ${thumb}`);
// after resizing + uploading then we erase the file from storage
// now delete the files from local storage.
fs.unlink(req.file.path, resultHandler);
fs.unlink(newFileInfo.path, resultHandler);
updateCat(req,filter);
});
})
.catch(function(err) {
console.log("Error occured when resizing img",err);
return res.status(500).send({ status: 'failed', message: err});
});
});
}else{
//no img file but we update the rest of data!
updateCat(req,filter);
}
});
});
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
}
});
//function to handle the updating process
function updateCat(req,filter){
//we create it or at leaast we try to
var data = req.body;
if(image && thumb){
data.image = image;
data.thumb = thumb;
}
const sub_category = JSON.parse(data.sub_category);
data.sub_category = [...sub_category];
// data.authorizedIssuingAccounts = JSON.parse(data.authorizedIssuingAccounts);
console.log("We're about to update::::");
console.log(data);
Category.updateOne(filter, data, function(err,updatedCat){
if(err){
console.log('Error when updating Category.',err);
return res.status(500).send({ status: 'failed', message: err});
}
console.log('Updated Category',updatedCat);
return res.status(200).send({ status: 'sucess', result: updatedCat});
})
};
});
/////handling adding a new cat if not found under same name & query as those are the important fields
router.post('/addCat', function(req,res){
var image,thumb;
const token = req.headers['x-access-token'];
const query = req.headers['query']; //as { name: 'string', query: 'string'} name of category and query in order to search if already exists or not.
if(!query){
if(config.testingData){ console.log('Not query provided.')};
return res.status(404).send({ status:'failed', message: 'I cannot process empty queries. Funny boy!'});
}
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
const filter = JSON.parse(query);
Category.findOne(filter, function(err,catFound){
if(err){
if(config.testingData){console.log('Error searching for category.',err)};
return res.status(500).send({ status: 'failed', message: err});
}
if(catFound){
if(config.testingData){console.log('Category already exists.', catFound)};
return res.status(404).send({ status: 'failed', message: 'Please choose another category Name and query.'});
}
//as we don't find any, we add so multer get to work from here.
upload(req, res, function(err){
if(err){
console.log('Error processing on multer.',err);
return res.status(500).send({ status: 'failed', message: err});
};
//upload the data and grab the results.
if(req.file){
if(config.testingData) {console.log('There is file on new cat, so lets use it!')};
cloudinary.uploader.upload(req.file.path,{ tags: 'newCat'}, function(error, result){
if(error){
console.log('Error uploading img to cloudinary.',error);
//as we really need the image to make the cat work we stop here and return err
return res.status(500).send({ status: 'failed', message: error});
}
//image is the uploaded img
image = result.secure_url;
if(config.testingData) {console.log(`Image uploaded. ${image}`)};
//here we should apply the transformation and upload it also.
// we will test sharp to resize the image and upload it as well, then we take both fields and save into db
let inputFile = req.file.path;
let outputFile = "thumb-" + Date.now() + req.file.originalname;
sharp(inputFile).resize({ width: 200 }).toFile(outputFile) //thumb for cats is 200px wide for now
.then(function(newFileInfo) {
// newFileInfo holds the output file properties
// console.log(`Success resizing ${inputFile}`);
newFileInfo.path = outputFile;
console.log(`Now we handle to upload:`);
console.log(newFileInfo);
cloudinary.uploader.upload(newFileInfo.path,{ tags: 'newCatThumb'}, function(error, thumbUploaded){
if(error){
if(config.testingData) {console.log('Error uploading thumb.',error)}
return res.status(500).send({ status: 'failed', message: error});
}
console.log('Sucess, thumb uploaded. Now we get the new name.');
thumb = thumbUploaded.secure_url;
console.log(`Thumb uploaded. ${thumb}`);
// after resizing + uploading then we erase the file from storage
// now delete the files from local storage.
fs.unlink(req.file.path, resultHandler);
fs.unlink(newFileInfo.path, resultHandler);
saveCat(req);
});
})
.catch(function(err) {
console.log("Error occured when resizing img",err);
return res.status(500).send({ status: 'failed', message: err});
});
});
}else{
//no img file we ureturn error as image must be provided for any cat.
return res.status(404).send({ status: 'failed', message: 'Each new category must have an image. Please retry but adding an image, following the specifications.'});
}
});
});
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
};
});
//function to handle the saving process
function saveCat(req){
//we create it or at leaast we try to
var data = req.body;
if(image && thumb){
data.image = image;
data.thumb = thumb;
}
const sub_category = JSON.parse(data.sub_category);
data.sub_category = [...sub_category];
// data.authorizedIssuingAccounts = JSON.parse(data.authorizedIssuingAccounts);
console.log("We're about to save::::");
console.log(data);
Category.create(data, function(err,newCat){
if(err){
console.log('Error when adding new Category.',err);
res.status(500).send({ status: 'failed', message: err});
}
console.log('Added new Category',newCat);
res.status(200).send({ status: 'sucess', result: newCat});
})
};
});
/////handling the categories + sub cats
router.get('/getCats', function(req,res){
const token = req.headers['x-access-token'];
const jsonQuery = JSON.parse(req.headers['query']);
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
//as soon as we decode we search to verify is an admin.
User.findOne({ username: decoded.usernameHive }, function(err,admin){
if(err){
if(config.testingData){console.log('Error searching for admin.',err)};
return res.status(500).send({ status: 'failed', message: err});
}
if(admin.usertype != 'admin'){
if(config.testingData){ console.log('User not admin.',admin)};
return res.status(404).send({ status: 'failed', message: 'User not an admin!'});
}else{
const filter = jsonQuery.query === "all" ? {} : jsonQuery;
Category.find(filter, function(err,category){
if(err){
if(config.testingData){console.log('Error searching for categories.',err)};
return res.status(500).send({ status: 'failed', message: err});
}
return res.status(200).send({ status: 'sucess', result: category});
});
}
})
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
}
});
});
////////END Web content section
//////////Handling NFTs///////////
///////Query NFTs on MongoDB
//get all token based on query, handling the query on headers.
router.get('/getNFTquery', function(req,res){
const token = req.headers['x-access-token'];
const query = req.headers['query'];
const limit = Number(req.headers['limit']);
const sortby = JSON.parse(req.headers['sortby']);
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
const jsonQuery = JSON.parse(query);
if(!jsonQuery) {
console.log('A null || empty query has been made!');
return res.status(404).send({ status: 'funny', message: "I cannot process that!"});
}
//TODO process the query check for nulls || "" and create teh newQuery.
const newNode = {};
Object.entries(jsonQuery).forEach(([key, val]) => {
if(val !== null && val !== ""){
return (newNode[key] = val);
}
});
console.log('New query to process::::');
console.log(newNode, `Limit:${limit}`);
console.log('Sortby:',sortby);
Nft.find(newNode,function(err,tokens){
if(err){
if(config.testingData){
console.log('Error finding Nft',err);
}
return res.status(500).send({ error: 'Error searching for Nft', message: err});
}
return res.status(200).send({ status: 'sucess', result: tokens });
}).limit(limit).sort(sortby.hasOwnProperty("null") ? null : sortby);
}else{
res.status(404).send({ auth: false, message: 'Failed to decode user!!!.'});
}
});
});
///////End Query NFTs on mongoDB
/////////END Handling NFTs////////
/////////////////////////////////////////////////
///////Order section controlled by Admins
///////////handling Order get from admins
////Testing how to do a get that can be used in order and another schems at the same time.
// this can allow us to modify the code and refactor later on.
router.get('/getRequest', function(req,res){
const token = req.headers['x-access-token'];
const schema = req.headers['schema']; //defines the schema you want to query as "./Orders", "./Nft", etc.
const filter = JSON.parse(req.headers['filter']) || {};
const limit = Number(req.headers['limit']) || 0; //just in case no number comes from request.
const sort = JSON.parse(req.headers['sort']) || {}; //as { createdAt: -1 } { field: -1} -1 desc || { field: 1} 1 asc.
if(!token) return res.status(404).send({ auth: false, message: 'No token provided!' });
jwt.verify(token, config.secret, function(err, decoded){
if(err) return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
if(decoded){
if(config.testingData){
console.log(`Checking on ${schema} data by Admin: ${decoded.usernameHive}`);
console.log('filtering on jobs AdminController:', filter);
console.log('Limit:', limit);
console.log('Sort:', sort)
}
const _Schema = require(schema);
_Schema.find(filter, function(err, result){
if(err){
if(config.testingData) {console.log(`Error finding ${schema} `, err)};
return res.status(500).send({ status: 'failed', message: err, schema: schema });
}
return res.status(200).send({ status: 'sucess', result: result, schema: schema });
}).sort(sort).limit(limit)
}else{
return res.status(500).send({ auth: false, message: 'Failed to decode token.' });
}
});
});
///////////END handling order queries from admins
///////END Order section controlled by Admins
/////////////////////////////////////////////////
module.exports = router;