-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
887 lines (797 loc) · 30.3 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
require('dotenv').config()
// Comment out these config and tunnel if not
// connecting to remote database like we are
// If you are, add the .env variables to your .env
// =========================================
var config = {
host: process.env.REMOTE_HOST,
username: process.env.DB_USER,
dstHost: process.env.REMOTE_HOST,
dstPort: process.env.REMOTE_DEST_PORT,
localPort: process.env.DB_PORT,
password: process.env.DB_PASS,
keepAlive: true,
};
var tunnel = require('tunnel-ssh');
tunnel(config, function (error, server) {
if (error) {
console.log(error);
}
});
// Comment out until here
// =========================================
var express = require('express');
var app = express();
var passport = require('passport');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var session = require('express-session');
var flash = require('connect-flash');
var expressValidator = require('express-validator');
var moment = require('moment-timezone');
// =====================================
// APP SETUP ===========================
// =====================================
app.use(morgan('dev')); // log every request to the console
// get information from html forms
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// validate forms
app.use(expressValidator());
// display messages
app.use(flash());
// set default view engine
app.set("view engine", "ejs");
// set default css
app.use(express.static(__dirname + '/public'));
// =====================================
// PASSPORT (AUTH) FUNCTIONS ===========
// =====================================
require('./config/passport')(passport); // pass passport for configuration
// required for passport
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(function(req,res,next){
res.locals.currentUser = req.user;
res.locals.prevUrl = req.session.returnTo;
res.locals.moment = moment;
next();
})
// =====================================
// ** ROUTES BEGIN HERE ** =============
// =====================================
const executer = require('./db/executer');
// executer.dropTables();
// // Creates Tables + Views + Functions when server starts
executer.createAllTables();
executer.createAllViews();
executer.dropAllExtensions();
executer.dropAllFunctions();
executer.createAllExtensions();
executer.createAllFunctions();
executer.createAllIndexes();
// Toggle methods to populate or delete populated tasks
// must be in this order
// executer.populateCategories();
// executer.populatePersons();
// executer.populateTaskStatuses();
// executer.populateOfferStatuses();
// executer.populateTasks();
// executer.populateOffers();
// executer.deletePopulatedTasks();
app.get("/", function(req, res) {
res.render("landing");
});
// =====================================
// LOGIN APIS ==========================
// =====================================
// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated()) {
return next();
}
// if they aren't redirect them to the login page
res.redirect('/login');
}
// route middleware to make sure a user is admin
function isAdmin(req, res, next) {
if (typeof res.locals.currentUser != 'undefined' && res.locals.currentUser.role == 'admin') {
return next();
}
// not admin
res.render('404');
}
// save previous returnTo so user can seamlessly join back
function redirection(req, res, next) {
req.session.returnTo = req.originalUrl;
return next();
}
// show the login form
app.get('/login', function(req, res) {
// render the page and pass in any flash data if it exists
res.render('login', { message: req.flash('loginMessage') });
});
// process the login form
// app.post('/login', do all our passport stuff here);
// process the login form
app.post('/login', login_validation, passport.authenticate('local-login', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/login', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
// app.get('/hidden', isLoggedIn, function(req, res) {
// res.redirect(req.session.returnTo);
// });
function login_validation(req, res, next){
req.checkBody('username', 'Username is Required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
//validate
var errors = req.validationErrors();
if (errors) {
res.render('login', { message: errors[0].msg });
} else {
next();
}
}
app.get("/signup", function(req, res) {
res.render('signup', { message: req.flash('signupMessage') });
})
// process the signup form
app.post('/signup', signup_validation, passport.authenticate('local-signup', {
successRedirect : '/profile', // redirect to the secure profile section
failureRedirect : '/signup', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
function signup_validation(req, res, next){
req.checkBody('username', 'Username is Required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('password', 'Password is required').notEmpty();
//validate
var errors = req.validationErrors();
if (errors) {
res.render('signup', { message: errors[0].msg });
} else {
next();
}
}
// =====================================
// PROFILE APIS ========================
// =====================================
// we will want this protected so you have to be logged in to visit
// we will use route middleware to verify this (the isLoggedIn function)
app.get('/profile', isLoggedIn, function(req, res) {
var numTasks;
var promise = executer.getNumTasksByUsername(req.user.username)
.then(results => {
numTasks = results.rows[0].count;
});
promise = executer.getNumOffersByUsername(req.user.username)
.then(results => {
var numOffers = results.rows[0];
res.render('profile', {
user : req.user, // get the user out of session and pass to template
numOffers: numOffers,
numTasks: numTasks
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
})
});
app.get('/profile/:username', function(req, res) {
var numTasks;
var promise = executer.getNumTasksByUsername(req.params['username'])
.then(results => {
numTasks = results.rows[0].count;
});
promise = executer.getUserByName(req.params['username'])
.then(results => {
var user = results.rows[0];
promise = executer.getNumOffersByUsername(req.params['username'])
.then(results => {
var numOffers = results.rows[0];
res.render('view_profile', {
user : user,
targetUser: req.params['username'],
numOffers: numOffers,
numTasks: numTasks
});
})
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
})
})
// Task related starts here
app.get('/profile/:username/tasks', function(req, res) {
var promise = executer.getTasksByRequester(req.params['username'])
.then(results => {
var tasks = results.rows;
res.render("user_tasks", {
targetUser: req.params['username'],
tasks: tasks
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
app.get('/profile/:username/tasks/open', function(req, res) {
var promise = executer.getTasksWithOpenStatusByRequester(req.params['username'])
.then(results => {
var tasks = results.rows;
res.render("user_tasks_open", {
tasks: tasks,
targetUser: req.params['username'],
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
app.get('/profile/:username/tasks/offered', function(req, res) {
var promise = executer.getTasksWithOfferedStatusByRequester(req.params['username'])
.then(results => {
var tasks = results.rows;
res.render("user_tasks_offered", {
tasks: tasks,
targetUser: req.params['username'],
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
app.get('/profile/:username/tasks/accepted', function(req, res) {
var promise = executer.getTasksWithAcceptedStatusByRequester(req.params['username'])
.then(results => {
var tasks = results.rows;
res.render("user_tasks_accepted", {
tasks: tasks,
targetUser: req.params['username'],
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
// Offers related starts here
app.get('/profile/:username/offers', function(req, res) {
var promise = executer.getTasksWithOffersByOfferAssignee(req.params['username'])
.then(results => {
var tasks = results.rows;
res.render("user_offers", {
tasks: tasks,
targetUser: req.params['username'],
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
app.get('/profile/:username/offers/pending', function(req, res) {
var promise = executer.getTasksWithPendingOffersByOfferAssignee(req.params['username'])
.then(results => {
var tasks = results.rows;
res.render("user_offers_pending", {
tasks: tasks,
targetUser: req.params['username'],
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
app.get('/profile/:username/offers/accepted', function(req, res) {
var promise = executer.getTasksWithAcceptedOffersByOfferAssignee(req.params['username'])
.then(results => {
var tasks = results.rows;
res.render("user_offers_accepted", {
tasks: tasks,
targetUser: req.params['username'],
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
app.get('/profile/:username/offers/rejected', function(req, res) {
var promise = executer.getTasksWithRejectedOffersByOfferAssignee(req.params['username'])
.then(results => {
var tasks = results.rows;
res.render("user_offers_rejected", {
tasks: tasks,
targetUser: req.params['username'],
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
// =====================================
// LOGOUT ==============================
// =====================================
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
// =====================================
// TASKS APIs ==========================
// =====================================
app.get("/tasks/", redirection, function(req, res) {
var promise = executer.getAllTasks()
.then(results => {
var tasks = results.rows;
res.render("tasks", { tasks: tasks,
message: req.flash('message'),
success: req.flash('success'),
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
app.get("/tasks/new", isLoggedIn, function(req, res) {
var promise = executer.getCategories()
.then(results => {
var categories = results.rows;
res.render("new_task", { categories: categories, message: req.flash('message') });
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
app.get("/tasks/:id", redirection, function(req, res) {
var promise = executer.getTaskById(req.params['id'])
.then(results => {
var task = results.rows[0];
promise = executer.getOffersByTaskId(task.id)
.then(results => {
var offers = results.rows;
promise = executer.getAcceptedOfferByTaskId(task.id)
.then(results => {
var acceptedOffer = results.rows[0];
if (res.locals.currentUser != null) {
promise = executer.getOffersByAssigneeAndTaskId(req.user.username, task.id)
.then(results => {
var offerByUser = results.rows[0];
res.render("task_page", { task: task,
offers: offers,
offerByUser: offerByUser,
acceptedOffer: acceptedOffer,
message: req.flash('message'),
offer_success: req.flash('offer_success')});
})
} else {
res.render("task_page", { task: task, offers: offers, acceptedOffer: acceptedOffer});
}
})
})
})
.catch(err => {
res.render("deleted_task_page", { title: "Sorry, task not found"});
})
})
app.post("/tasks", isLoggedIn, function(req, res) {
// get data from form and add to tasks array
var title = req.body.title;
var description = req.body.description;
var category_id = req.body.category_id;
var location = req.body.location;
var requester = req.user.username;
var start_dt = moment(req.body.start_dt, 'DD/MM/YYYY, h:mm A').format();
var end_dt = moment(req.body.end_dt, 'DD/MM/YYYY, h:mm A').format();
var price = req.body.price;
var promise = executer.addTask(title, description, category_id, location, requester, start_dt, end_dt, price)
.then(function() {
var redirectUrl = "/profile/" + req.user.username + "/tasks";
res.redirect(redirectUrl); // to user's projects page
})
.catch(err => {
req.flash('message', err.message);
var redirectUrl = "/tasks/new";
res.redirect(redirectUrl); // to updated task page
});
});
app.get("/edit/task/:id", isLoggedIn, redirection, function(req, res) {
var promise = executer.getTaskById(req.params['id'])
.then(results => {
var task = results.rows[0];
promise = executer.getCategories()
.then(results => {
var categories = results.rows;
res.render("edit_task", { task: task, categories: categories, message: req.flash('message') });
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
})
app.post("/edit/task/:id", isLoggedIn, function(req, res) {
var task_id = req.body.id;
var title = req.body.title;
var description = req.body.description;
var category_id = req.body.category_id;
var location = req.body.location;
var start_dt = moment(req.body.start_dt, 'DD/MM/YYYY, h:mm A').format();
var end_dt = moment(req.body.end_dt, 'DD/MM/YYYY, h:mm A').format();
var price = req.body.price;
var promise = executer.updateTaskById(task_id, title, description, category_id, location, start_dt, end_dt, price)
.then(function() {
var redirectUrl = "/tasks/" + task_id;
res.redirect(redirectUrl); // to updated task page
})
.catch(err => {
req.flash('message', err.message)
var redirectUrl = "/edit/task/" + task_id;
res.redirect(redirectUrl); // to updated task page
});
})
app.post("/delete/task/:id", isLoggedIn, function(req, res) {
var task_id = req.body.id;
var promise = executer.deleteTaskById(task_id)
.then(function() {
console.log("Task successfully deleted!")
req.flash('success', "Task successfully deleted!")
res.redirect("/tasks");
})
.catch(err => {
req.flash('message', err.message)
res.redirect("/tasks"); // to updated task page
})
})
// =====================================
// OFFER APIs ==========================
// =====================================
app.post("/new/offer/:id", isLoggedIn, function(req, res) {
var task_id = req.params['id'];
var price = req.body.price;
var assignee = res.locals.currentUser.username;
var offered_dt = new Date().toISOString();
var promise = executer.addOffer(task_id, price, assignee, offered_dt)
.then(function() {
req.flash('offer_success', "Offer successfully added!");
var redirectUrl = "/tasks/" + task_id;
res.redirect(redirectUrl); // back to task page
})
.catch(err => {
req.flash('message', err.message)
var redirectUrl = "/tasks/" + task_id;
res.redirect(redirectUrl); // to updated task page
});
});
app.post("/edit/offer/:id", isLoggedIn, function(req, res) {
var task_id = req.params['id'];
var assignee = req.body.assignee;
var newPrice = req.body.price;
var newOffered_dt = new Date().toISOString();
var promise = executer.updateOfferByAssigneeAndTaskId(assignee, task_id, newPrice, newOffered_dt)
.then(function() {
req.flash('offer_success', "Offer successfully updated!");
var redirectUrl = "/tasks/" + task_id;
res.redirect(redirectUrl); // back to task page
})
.catch(err => {
req.flash('message', err.message)
var redirectUrl = "/tasks/" + task_id;
res.redirect(redirectUrl); // back to page to display errors
});
});
app.post("/delete/offer/:id", isLoggedIn, function(req, res) {
var task_id = req.body.task_id;
var assignee = req.body.assignee;
// extra check
if (assignee != res.locals.currentUser.username && res.locals.currentUser.role != 'admin') {
req.flash('message', "Oops, you tried to do something you shouldn't have!")
var redirectUrl = "/tasks/" + task_id;
res.redirect(redirectUrl); // back to page to display errors
}
var promise = executer.deleteOfferByAssigneeAndTaskId(assignee, task_id)
.then(function() {
req.flash('offer_success', "Offer successfully deleted!");
var redirectUrl = "/tasks/" + task_id;
res.redirect(redirectUrl); // back to task page
})
.catch(err => {
req.flash('message', err.message)
var redirectUrl = "/tasks/" + task_id;
res.redirect(redirectUrl); // back to page to display errors
})
});
app.post("/accept/offer/:id", isLoggedIn, function(req, res) {
var task_id = req.body.task_id;
var requester = req.body.requester;
var assignee = req.body.assignee;
var offer_price = req.body.offer_price;
if (!(requester == res.locals.currentUser.username)) {
var redirectUrl = "/tasks/" + task_id;
req.flash('message', "You are not the user who requested for this task!")
res.redirect(403, redirectUrl);
}
var promise = executer.updateTaskUponAcceptingOfferByTaskID(task_id, assignee, offer_price)
.then(function() {
req.flash('offer_success', "Offer accepted!");
var redirectUrl = "/tasks/" + task_id;
res.redirect(redirectUrl); // back to task page
})
.catch(err => {
req.flash('message', err.message)
var redirectUrl = "/tasks/" + task_id;
res.redirect(redirectUrl); // back to page to display errors
})
});
app.post("/reject/offer/:id", isLoggedIn, function(req, res) {
var task_id = req.body.task_id;
var requester = req.body.requester;
var offer_id = req.body.offer_id;
if (!(requester == res.locals.currentUser.username)) {
var redirectUrl = "/tasks/" + task_id;
req.flash('message', "You are not the user who requested for this task!")
res.redirect(403, redirectUrl);
}
var promise = executer.updateTaskUponRejectingOfferByTaskID(task_id, offer_id)
.then(function() {
req.flash('offer_success', "Offer rejected!");
var redirectUrl = "/tasks/" + task_id;
res.redirect(redirectUrl); // back to task page
})
.catch(err => {
req.flash('message', err.message)
var redirectUrl = "/tasks/" + task_id;
res.redirect(redirectUrl); // back to page to display errors
})
});
// =====================================
// CATEGORIES APIs =====================
// =====================================
app.get("/categories", redirection, function(req, res) {
var promise = executer.getCategories()
.then(results => {
var categories = results.rows;
res.render("categories", { categories: categories });
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
app.get("/categories/:id", redirection, function(req, res) {
var promise = executer.getCategories()
.then(results => {
var categories = results.rows;
promise = executer.getTasksByCategoryId(req.params['id'])
.then(results => {
var tasks = results.rows;
var categoryName = categories[req.params['id'] - 1].name;
res.render("tasks", { tasks: tasks, categoryName: categoryName });
})
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
// =====================================
// SEARCH APIs =========================
// =====================================
app.get("/search/advanced/", function(req, res) {
var promise = executer.getCategories()
.then(results => {
var categories = results.rows;
res.render("adv_search", {categories: categories});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
app.get("/search/", function(req, res) {
var search_string = req.query.search;
var category_id = req.query.category_id;
var location = req.query.location;
var requester = req.query.requester;
var start_dt = req.query.start_dt;
if (typeof start_dt != 'undefined' && start_dt != '') {
start_dt = moment(req.query.start_dt, 'DD/MM/YYYY').format();
}
var min_price = req.query.min_price;
var max_price = req.query.max_price;
var status_task = req.query.status_task;
var assignee = req.query.assignee;
var categories;
var promise = executer.getCategories()
.then(results => {
categories = results.rows;
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
promise = executer.getTasksByAdvancedSearch(search_string, category_id, location, requester, start_dt, min_price, max_price, status_task, assignee)
.then(results => {
var tasks = results.rows;
res.render("tasks", { tasks: tasks, categories: categories });
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
// =====================================
// ADMIN APIs ==========================
// =====================================
app.get("/admin", isAdmin, function(req, res) {
// getNoOfTasksByCategory returns 3 things - cat_id, cat_name, count
var labels = [];
var dataset = [];
var userCountLabel = [];
var userCountData = [];
var userCountLabel_date = [];
var userCountData_date = [];
var taskCountLabel = [];
var taskCountData = [];
var taskCountLabel_date = [];
var taskCountData_date = [];
var offerCountData = [];
var offerCountLabel = [];
var offerCountData_date = [];
var offerCountLabel_date = [];
var countedTasks = 0;
var countUser = 0;
var promise = executer.getNoOfTasksByCategory()
.then(results => {
results.rows.map(function(obj) {
labels.push(obj.name);
dataset.push(obj.no_task);
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
promise = executer.getTotalUsersByMonth()
.then(results => {
results.rows.map(function(obj) {
userCountLabel.push(obj.month);
userCountData.push(obj.usercount);
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
promise = executer.getTotalTasksByMonth()
.then(results => {
results.rows.map(function(obj) {
taskCountLabel.push(obj.month);
taskCountData.push(obj.taskcount);
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
promise = executer.getTotalOffersByMonth()
.then(results => {
results.rows.map(function(obj) {
offerCountData.push(obj.offercount);
offerCountLabel.push(obj.month);
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
//// By date
promise = executer.getTotalUsersByDate()
.then(results => {
results.rows.map(function(obj) {
userCountLabel_date.push(obj.date);
userCountData_date.push(obj.usercount);
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
promise = executer.getTotalTasksByDate()
.then(results => {
results.rows.map(function(obj) {
taskCountLabel_date.push(obj.date);
taskCountData_date.push(obj.taskcount);
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
promise = executer.getTotalOffersByDate()
.then(results => {
results.rows.map(function(obj) {
offerCountLabel_date.push(obj.date);
offerCountData_date.push(obj.offercount);
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
promise = executer.getTotalNoOfTasks()
.then(results => {
countedTasks = results.rows[0].count;
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
promise = executer.getTotalNoOfUsers()
.then(results => {
countUser = results.rows[0].count;
labels = JSON.stringify(labels);
dataset = JSON.stringify(dataset);
userCountLabel = JSON.stringify(userCountLabel);
userCountData = JSON.stringify(userCountData);
taskCountLabel = JSON.stringify(taskCountLabel);
taskCountData = JSON.stringify(taskCountData);
offerCountData = JSON.stringify(offerCountData);
offerCountLabel = JSON.stringify(offerCountLabel);
userCountLabel_date = JSON.stringify(userCountLabel_date);
userCountData_date = JSON.stringify(userCountData_date);
taskCountLabel_date = JSON.stringify(taskCountLabel_date);
taskCountData_date = JSON.stringify(taskCountData_date);
offerCountLabel_date = JSON.stringify(offerCountLabel_date);
offerCountData_date = JSON.stringify(offerCountData_date);
res.render("admin", {countedTasks: countedTasks, countUser: countUser,
labels: labels, data: dataset,
userCountLabel: userCountLabel, userCountData: userCountData,
taskCountLabel: taskCountLabel, taskCountData: taskCountData,
offerCountData: offerCountData, offerCountLabel: offerCountLabel,
userCountLabel_date: userCountLabel_date, userCountData_date: userCountData_date,
taskCountLabel_date: taskCountLabel_date, taskCountData_date: taskCountData_date,
offerCountData_date: offerCountData_date, offerCountLabel_date: offerCountLabel_date
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
app.get("/admin/users", isAdmin, function(req, res) {
var promise = executer.getUserData()
.then(results => {
var userData = results.rows;
res.render("admin_users", {
userData: userData,
message: req.flash('message'),
success: req.flash('success'),
});
})
.catch(err => {
res.status(500).render('500', { title: "Sorry, internal server error", message: err });
});
});
app.post("/delete/user/:id", isLoggedIn, function(req, res) {
var user_id = req.body.id;
// extra check
if (res.locals.currentUser.role != 'admin') {
req.flash('message', "Oops, you tried to do something you shouldn't have!")
var redirectUrl = "/tasks/";
res.redirect(redirectUrl); // back to page to display errors
}
var promise = executer.deleteUserByUserId(user_id)
.then(function() {
req.flash('success', "User successfully deleted!");
var redirectUrl = "/admin/users";
res.redirect(redirectUrl); // back to admin page
})
.catch(err => {
req.flash('message', err.message)
var redirectUrl = "/admin/users";
res.redirect(redirectUrl); // back to page to display errors
})
});
// =====================================
// MISC APIs ===========================
// =====================================
//404
app.use(function(req, res, next){
res.status(404).render('404', { title: "Sorry, page not found" });
});
app.listen(5000, 'localhost', function() {
console.log("Taskrr server has started!");
});