-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
2427 lines (2020 loc) · 103 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* The app.js file contains the core processes
* that create the different features of the
* Team Aptiv web application. The file is, in
* essence, the server code that connects to the
* MongoDB database as well as handles different
* requests to the web application. Given the
* numerous lines of code in this file, sections
* have been used to break apart the different
* functionalities. To understand the code, read
* the comments throughout the app.js file and
* analyze the information section by section.
* ----------------------------------------------------------------------------------
* The first section contains the installed
* packages used to help run the server for
* the website application. The second section
* defines different schemas (blueprints) for
* the types of documents that will be stored
* in the database and connects to the database.
* The third section contains the information
* that enables the web application to utilize
* Google OAuth so that the user can register
* or login using their Google account. The
* fourth section contains a series of get
* requests. These requests are used to render
* the initial state of a page in the browser.
* Within the fourth section, the fifth section
* is used to account for the admin account in
* terms of get requests. The sixth section, also
* contained within the fourth section, is used
* to create a get request for a specific event
* when it is regarded by the user. A function
* for simplifying the date and time display
* exists in the seventh section (contained
* within the fourth section). The eigth
* section, also contained within section four,
* helps with the process of rendering a specifc
* event on the page. The ninth section handles
* the post requests made to the server, which
* is used to handle events that occur after
* the initial state (for example, the user
* clicking a button would be handled by a
* post request route). Contained within the
* ninth section are the tenth and eleventh
* sections, which handle the admin information
* for post requests and the user volunteer sign
* up for post requests respectively. The twelfth
* section contains code for listening for server
* requests.
* ----------------------------------------------------------------------------------
* The sections present in the code are listed
* below in order in all caps:
*
* 1. SECTION: INSTALLED PACKAGES AND INITIALIZATION
* 2. SECTION: USER, PROGRAM, AND EVENTS FOR DATABASE VIA MONGOOSE AND MONGODB
* 3. SECTION: AUTHENTICATE USERS AND USE GOOGLE OAUTH
* 4. SECTION: GET INFORMATION FROM SERVER (GET) --> Has sections 5-8 within it
* -->5. ADMIN SECTION (GET)
* -->6. SINGLE EVENT SECTION (GET)
* -->7. SECTION WITHIN GET: FUNCTIONS FOR SIMPLIFYING THE DATE/TIME DISPLAY OF EVENTS
* -->8. SECTION WITHIN GET: RENDERING A PAGE ON THE SCREEN SPECIFIC TO AN EVENT
* 9. SECTION: PROCESS REQUESTS MADE TO SERVER (POST) --> Has sections 10-13 within it
* -->10. ADMIN SECTION (POST)
* -->11. USER EVENT CANCELLATION (POST)
* -->12. USER VOLUNTEER SIGN-UP (POST)
* -->13. USER DONATION (POST)
* 14. SECTION: LISTEN FOR SERVER REQUESTS
* ----------------------------------------------------------------------------------
*
* Project: Aptiv Web Application
* Authors: Andrew Krause, Riley Radle,
* Anthony Musbach, Zach Gephart
* Class: Software Design IV (CS 341)
* Group: #2
* Date: 12/15/2021
*
*/
//jshint esversion:6
/* SECTION: INSTALLED PACKAGES AND INITIALIZATION */
// Security package. Encrypts sensitive data. No variable storage needed.
require('dotenv').config();
// Require packages for the server that were installed.
const express = require("express");
const flash = require("connect-flash");
const ejs = require("ejs");
const _ = require("lodash");
const mongoose = require("mongoose");
var user_ID = mongoose.Types.ObjectId();
// Require additional security packages for login information
const session = require('express-session');
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const LocalStrategy = require("passport-local");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const findOrCreate = require("mongoose-findorcreate");
// Create a string for the current ADMIN username.
const ADMIN_NAME = "$ADMIN$@ACCOUNT-2023";
// Create a string for the only organization item.
// Also create a boolean to determine if org data item exists.
const TEAM_APTIV = "Team-Aptiv-Org";
// Create web app using express and set view engine to EJS
const app = express();
app.use(express.static("public"));
app.set('view engine', 'ejs');
// Use the body parser within the express module.
app.use(express.urlencoded({extended: true}));
// The code for SESSIONS is set up here.
app.use(session({
secret: "Confidential information.",
resave: false,
saveUninitialized: false
}));
// Use the flash module to transmit messages
// to the user as well as the developers.
app.use(flash());
// Initialize the passport package. Use passport in the session.
app.use(passport.initialize());
app.use(passport.session());
// ============================================================================================================
/* SECTION: USER, PROGRAM, AND EVENTS FOR DATABASE VIA MONGOOSE AND MONGODB */
// Create variables to store values for connecting to the MongoDB database.
var mongodbUsername;
var mongodbPassword;
var mongodbDatabaseName;
var mongodbUri;
// If the Team Aptiv application is being hosted on Heroku or another
// server platform, see if any of the following environment variables
// exist.
if(process.env.MONGODB_USERNAME &&
process.env.MONGODB_PASSWORD &&
process.env.MONGODB_DB_NAME) {
mongodbUsername = encodeURIComponent(process.env.MONGODB_USERNAME);
mongodbPassword = encodeURIComponent(process.env.MONGODB_PASSWORD);
mongodbDatabaseName = process.env.MONGODB_DB_NAME;
mongodbUri = `mongodb+srv://${mongodbUsername}:${mongodbPassword}@cluster1.vuowc.mongodb.net/${mongodbDatabaseName}?retryWrites=true&w=majority&appName=Cluster1`;
// Otherwise, if the above if-statement does not evaluate to true,
// assume the application is being run locally and use the local
// connection string.
} else {
mongodbUri = "mongodb://localhost:27017/aptivDB";
}
// Set up a connection to the database using mongoose.
mongoose.connect(mongodbUri, {useNewUrlParser: true, useUnifiedTopology: true});
// Create a mongoose schema (blueprint) for the users in the database.
const userSchema = new mongoose.Schema({
// User identification number.
userID: {
type: String,
unique: true,
sparse: true
},
// First name, last name, and picture of user.
firstName: String,
lastName: String,
picture: String,
// Boolean value to determine if the user's account is active.
isActive: Boolean,
// Username of user.
username: {
type: String,
unique: true,
sparse: true
},
// Password and google identification number of user.
password: String,
googleId: String,
// Status of user. Default status is "Volunteer"
status: {
type: String,
default: "Volunteer"
},
// Total number of donations to all events.
givenDonations: Number,
// Total time spent volunteering.
volunteeredTime: {
type: String,
default: "0:00"
},
// Array of times that the user is attending.
// Also contains the date of the event.
timesAttending: [{
type: String,
unique: true,
sparse: true
}],
// Array of the event identification numbers user has signed up for.
userEvents: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Event'
}]
});
// Create a mongoose schema for the main organization. This
// Schema is created for the sole purpose of receiving unrestricted
// donations for users.
const orgSchema = new mongoose.Schema({
// Create organization id, name, and received donations.
orgID: String,
orgName: String,
receivedDonations: Number
});
// Create a mongoose schema for the events in the database.
const eventSchema = new mongoose.Schema({
// Identification number and name of event.
eventID: String,
eventName: String,
// Date of event.
eventDate: {
type: Date,
default: Date.now
},
// Labels for the event start and end time.
eventStartTime: String,
eventEndTime: String,
// Boolean value to determine if the event
// has been cancelled by the ADMIN or not.
eventActive: Boolean,
// Array for the time slots available.
eventTimeIncrements: [{
type: String,
unique: true,
sparse: true
}],
// Location, description, needed volunteers and needed donations
eventLocation: String,
eventDescription: {
type: String,
unique: true,
sparse: true
},
numVolunteersNeeded: Number,
neededDonations: Number,
// Users who have volunteered for the event.
numVolunteers: {
type: Number,
default: 0
},
// Donations received for the event.
numDonations: {
type: Number,
default: 0
}
});
// Create a plugin for the user Schema. Also create
// a plugin for the findOrCreate function.
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
// Create mongoose models based on the above schemas.
const UserModel = new mongoose.model("User", userSchema);
const OrgModel = new mongoose.model("Org", orgSchema);
const EventModel = new mongoose.model("Event", eventSchema);
// ============================================================================================================
/* SECTION: AUTHENTICATE USERS AND USE GOOGLE OAUTH */
// Set up passport-local-mongoose configurations.
passport.use(UserModel.createStrategy());
// Serialize the user.
passport.serializeUser(function(user, done){
done(null, user.id);
});
// Deserialize user.
passport.deserializeUser(function(id, done){
UserModel.findById(id, function(err, user){
done(null, user);
});
});
// Implement the verify callback function as well as other features
// for the Google OAuth package, which is applied to the Aptiv path.
// IMPORTANT: When a user uses OAuth to create an account/sign in,
// they will only have 9 fields in the database. We do not worry about
// the username and user_ID being stored in our database. Google
// handles the security features for the username and password fields.
// Users that DO NOT use Google OAuth will have 10 fields in the db.
passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/team-aptiv",
},
function(accessToken, refreshToken, profile, cb) {
// Generate a unique id for the user using Google OAuth.
var user_ID = mongoose.Types.ObjectId();
var user_IDString = user_ID.toString();
// Use the "findOne" method to check if the user already
// exists in the user database. If the user does not already
// exist, then create a new user and add the user to the db.
UserModel.findOne({
googleId: profile.id
}, function(err, user) {
if (err) {
return cb(err);
}
// If no user was found, create a new user using the findOrCreate method.
if (!user) {
// Use the method to create a new user for the web app. In this
// case, the "find" in the "findOrCreate" is never used for the site.
UserModel.findOrCreate({googleId: profile.id, firstName: profile.name.givenName, lastName: profile.name.familyName, picture: profile._json.picture, isActive: true, givenDonations: 0, username: user_ID}, function (err, user) {
// If the user has not already been created, update the timesAttending array
// by adding a unique id to it as the first element in order to maintain uniqueness.
if(user.timesAttending.length == 0) {
// Add the initial id to the user's timeslots attribute.
UserModel.findOneAndUpdate(
{ _id: user.id },
{ $push: { timesAttending: user_IDString } },
function (error, success) {
if (error) {
console.log("Error: " + error);
} else {
// console.log("User Success: " + success);
}
}
);
}
return cb(err, user);
});
} else {
// Found user. Return
return cb(err, user);
}
});
}
));
// ============================================================================================================
/* SECTION: GET INFORMATION FROM SERVER (GET) */
// Default route, which is the home page.
app.get("/", function(req, res){
// Determine how many documents exist in the org model.
// Create ONE org document if there are none that exist.
OrgModel.find().count(function(err, count){
// If the count is greater than zero, the org already exists.
// Otherwise, create a new org and add that org to the database.
if(count > 0) {
return;
} else {
// Create a new identifier for the organization object.
var org_ID = mongoose.Types.ObjectId();
// Create the new organization data model.
const newOrg = new OrgModel({
orgID: org_ID,
orgName: TEAM_APTIV,
receivedDonations: 0
});
// Save the new organization to the database.
newOrg.save(function(err, result){
if (err){
console.log(err);
}
});
}
});
// Render the home page and determine if user is undefined.
res.render("home", { user: req.user });
});
// Route to render the home page when the user clicks "Team Aptiv".
app.get("/home", function(req, res){
// Determine how many documents exist in the org model.
// Create ONE org document if there are none that exist.
OrgModel.find().count(function(err, count){
// If the count is greater than zero, the org already exists.
// Otherwise, create a new org and add that org to the database.
if(count > 0) {
return;
} else {
// Create a new identifier for the organization object.
var org_ID = mongoose.Types.ObjectId();
// Create the new organization data model.
const newOrg = new OrgModel({
orgID: org_ID,
orgName: TEAM_APTIV,
receivedDonations: 0
});
// Save the new organization to the database.
newOrg.save(function(err, result){
if (err){
console.log(err);
}
});
}
});
// Render the home page and determine if user is undefined.
res.render("home", { user: req.user });
});
// Create a route that the 'Sign Up with Google' button will direct us to.
app.get("/auth/google",
// Initiate authentication with Google.
passport.authenticate("google", {scope: ["profile"]})
);
// Add the Google redirect route.
app.get("/auth/google/team-aptiv",
passport.authenticate("google", { failureRedirect: "/login" }),
function(req, res) {
// Successful authentication, redirect to user profile page.
res.redirect("/user_profile");
});
// Create a route to allow the user to download
// the user help manual from the web application.
app.get("/download_help", function(req, res){
// Download the help manual (PDF) file stored for website.
const file = `${__dirname}/public/files/User-Manual.pdf`;
res.download(file);
});
// Create a route for the user to view the 'about'
// page and make an unrestricted donation.
app.get("/about", function(req, res){
// See if the data model exists and pass that
// through to the about page that is rendered.
OrgModel.find({}, function(err, events){
// Render the about page and create
// a data model behind the scenes.
res.render("about_unrestricted", {
user: req.user,
events: events,
thanksForDonation: req.flash("thanksForDonation")
});
});
});
// Create a route for viewing the events page for Aptiv.
app.get("/events", function(req, res){
// Use the find function to render all of the events in your
// Aptiv database onto the screen.
EventModel.find({}, function(err, events){
// Render the events on the events
// page of the web application.
res.render("events", {
successCancelled: req.flash("successCancelled"),
user: req.user,
events: events,
});
});
});
// Create a route for viewing the login page for Aptiv.
// This page accounts for incorret user input.
app.get("/login", function(req, res, next){
// Create a constant for errors. Use a flash
// message to notify the user that their login
// failed if they have attempted to login and
// have entered the wrong info.
const errors = req.flash().error || [];
res.render("login", {
errors,
permissionDenied: req.flash("permissionDenied"),
});
});
// Create a route for viewing the register page. If the account already
// exists, alert the user that they cannot use that account as their own.
app.get("/register", function(req, res){
res.render("register", {alreadyCreated: req.flash("alreadyCreated")});
});
// Create a route for viewing the user profile page for Aptiv.
// Check if the user is authenticated. If not, redirect to login.
app.get("/user_profile", function(req, res){
// Create an object to store the user information in an object.
const user = req.user;
// If the user is authenticated and is admin, redirect to admin page.
if(req.isAuthenticated() && user.username == ADMIN_NAME) {
// After checking if the user is authenticated and is the ADMIN, determine
// if their account is active. If active, redirect to profile. Otherwise,
// show an error message to the user.
if(user.isActive == true) {
// Redirect the ADMIN profile page and determine if ADMIN is undefined.
res.redirect("/admin_profile");
} else {
req.flash("alreadyCreated", "Your account has been deactivated. Contact admin for assistance");
res.redirect("/register");
}
} else if(req.isAuthenticated()) {
// After checking if the user is authenticated, determine if their account
// is active. If the user account is active, redirect to profile. Otherwise,
// show an error message to the user.
if(user.isActive == true) {
// Create variables to help with storing
// the events associated with a given user.
const userEventIds = user.userEvents;
var listOfUserEvents = [];
// If the user has events they have signed up for, display the events
// on the user's profile page. However, if the user has not signed up
// for any events and has none, simply display the user's profile.
if(userEventIds.length > 0) {
// Create variables to track the objects in the database and
// to determine when to display the objects in the user profile.
var i = 0;
j = userEventIds.length;
// Go through the objects stored in the given user collection and
// look them up in the database by their ID. Then add the objects
// found as a result of the lookup to a list and pass it to the page.
for(i = 0; i < userEventIds.length; i++) {
// Use the find by ID function to return the event object for the user.
EventModel.findById(userEventIds[i], function(err, results){
if(err) {
console.log(err);
} else {
listOfUserEvents.push(results);
j -= 1;
}
// The counter 'j' determines when the results should be returned
// from the callback function and rendered on the user profile page.
if (j == 0) {
// Render the user profile page and determine if user is undefined.
// Flash an error message if the regular user had previously
// attempted to access the ADMIN route.
res.render("user_profile", {
user: req.user,
listOfUserEvents: listOfUserEvents,
permissionDenied: req.flash("permissionDenied"),
successCancelled: req.flash("successCancelled")
});
}
});
}
} else {
res.render("user_profile", {
user: req.user,
listOfUserEvents: listOfUserEvents,
permissionDenied: req.flash("permissionDenied"),
successCancelled: req.flash("successCancelled")
});
}
} else {
req.flash("alreadyCreated", "Your account has been deactivated. Contact admin for assistance");
res.redirect("/register");
}
} else {
res.redirect("/login");
}
});
// Create a route for the user to logout of their account.
app.get("/logout", function(req, res){
req.logout();
res.redirect("/login");
});
// -------------------------------------- ADMIN SECTION (GET) -----------------------------------------------
// Create a route for the admin profile. For this route, include some
// layers of security so that the user cannot access the Admin profile
// unless they are the admin.
app.get("/admin_profile", function(req, res){
// Create an object to store the user information in an object.
const user = req.user;
// If the user is authenticated AND their status is set to
// "Admin", then they can access the admin profile page.
if(req.isAuthenticated() && user.username == ADMIN_NAME) {
// After checking if the user is authenticated and is the ADMIN, determine
// if their account is active. If active, redirect to profile. Otherwise,
// show an error message to the user.
if(user.isActive == true) {
// Create variables to help with storing
// the events associated with an ADMIN.
const userEventIds = user.userEvents;
var listOfUserEvents = [];
// Create a variable for storing the user data to be
// passed to the front end for the ADMIN profile.
var listOfUsers;
// Create a variable for storing the event data to be
// passed to the front end for the ADMIN profile.
var listOfCancelledEvents;
// Finnd all of the events in the database and add them
// to a variable that will be passed to the ADMIN profile
// page to be manipulated.
EventModel.find({}, function(err, events){
if(err) {
console.log(err);
} else {
// Create a variable for storing the cancelled
// events in the ADMIN'S profile.
listOfCancelledEvents = events
// Find all of the users in the database and add them
// to a variable that will be passed to the ADMIN
// profile page.
UserModel.find({}, function(err, users){
// Obtain the user data from the database.
if(err) {
console.log(err);
} else {
// Create a variable for storing the users in the database.
listOfUsers = users;
// If the ADMIN has events they have signed up for, display the events
// on the ADMIN's profile page. However, if the ADMIN has not signed up
// for any events and has none, simply display the ADMIN's profile.
if(userEventIds.length > 0) {
// Create variables to track the objects in the database and
// to determine when to display the objects in the ADMIN profile.
var i = 0;
var j = userEventIds.length;
// Go through the objects stored in the given ADMIN collection and
// look them up in the database by their ID. Then add the objects
// found as a result of the lookup to a list and pass it to the page.
for(i = 0; i < userEventIds.length; i++) {
// Use the find by ID function to return the event object for the ADMIN.
EventModel.findById(userEventIds[i], function(err, results){
if(err) {
console.log(err);
} else {
listOfUserEvents.push(results);
j -= 1;
}
// The counter 'j' determines when the results should be returned
// from the callback function and rendered on the user profile page.
if (j == 0) {
// Obtain the information from the organization data model so
// that the admin can view the donations made to the Team Aptiv
// organization.
OrgModel.find({}, function(err, orgInfo){
if(err) {
console.log(err);
} else {
// Render the ADMIN profile page and determine if ADMIN is undefined.
res.render("admin_profile", {
user: req.user,
listOfUserEvents: listOfUserEvents,
listOfCancelledEvents: listOfCancelledEvents,
listOfUsers: listOfUsers,
orgInfo: orgInfo,
successCreated: req.flash("successCreated"),
failureNotCreated: req.flash("failureNotCreated"),
successCancelled: req.flash("successCancelled"),
permissionDenied: req.flash("permissionDenied")
});
}
});
}
});
}
// If there are no events for the admin, then
// render the admin profile on the screen.
} else {
// Obtain the information from the organization data model so
// that the admin can view the donations made to the Team Aptiv
// organization.
OrgModel.find({}, function(err, orgInfo){
if(err) {
console.log(err);
} else {
// Render the ADMIN profile page and determine if ADMIN is undefined.
res.render("admin_profile", {
user: req.user,
listOfUserEvents: listOfUserEvents,
listOfCancelledEvents: listOfCancelledEvents,
listOfUsers: listOfUsers,
orgInfo: orgInfo,
successCreated: req.flash("successCreated"),
failureNotCreated: req.flash("failureNotCreated"),
successCancelled: req.flash("successCancelled"),
permissionDenied: req.flash("permissionDenied")
});
}
});
}
}
});
}
});
} else {
req.flash("alreadyCreated", "Your account has been deactivated. Contact admin for assistance");
res.redirect("/register");
}
// Otherwise, if the user is authenticated, redirect them to
// their profile page and flash an error message.
} else if (req.isAuthenticated()) {
req.flash("permissionDenied", "You cannot access that page");
res.redirect("/user_profile");
return;
// If the user is not authenticated, redirect them to the
// login page and flash an error message.
} else {
req.flash("alreadyCreated", "You cannot access that page");
res.redirect("/register");
return;
}
});
// Create a route for the ADMIN event creation page.
app.get("/event_creation", function(req, res){
// Get the current user.
const user = req.user;
// If the user is the admin, render the event creation page.
if(req.isAuthenticated() && user.username == ADMIN_NAME) {
res.render("event_creation", {
user: req.user
});
} else {
res.redirect("/user_profile");
}
});
// -------------------------------------- EVENT SECTION (GET) -----------------------------------------------
/* SECTION WITHIN GET: FUNCTIONS FOR SIMPLIFYING THE DATE/TIME DISPLAY OF EVENTS */
// The following function relates to the route, NEW POSTS, created below.
// The function simplifies the date displayed for each event.
function simplifyEventDate(eventDate){
// First split the event into the components that directly
// involve the numberical representations of a date.
var date = eventDate.toISOString().split("T")[0];
// Create variables for workring with
// the nubmers in the date variable.
var arrayDate = date.split('-');
var day = arrayDate[2];
var getMonth = arrayDate[1];
var month = "";
var year = arrayDate[0];
var simplifiedDate = "";
// Use a series of conditionals to determine
// what the name of the month is based on the
// numerical representation of it.
if(getMonth.localeCompare('01') == 0) {
month = 'Jan';
} else if(getMonth.localeCompare('02') == 0) {
month = 'Feb';
} else if(getMonth.localeCompare('03') == 0) {
month = 'Mar';
} else if(getMonth.localeCompare('04') == 0) {
month = 'Apr';
} else if(getMonth.localeCompare('05') == 0) {
month = 'May';
} else if(getMonth.localeCompare('06') == 0) {
month = 'Jun';
} else if(getMonth.localeCompare('07') == 0) {
month = 'Jul';
} else if(getMonth.localeCompare('08') == 0) {
month = 'Aug';
} else if(getMonth.localeCompare('09') == 0) {
month = 'Sep';
} else if(getMonth.localeCompare('10') == 0) {
month = 'Oct';
} else if(getMonth.localeCompare('11') == 0) {
month = 'Nov';
} else if(getMonth.localeCompare('12') == 0) {
month = 'Dec';
} else {
month = 'ERROR';
}
// Create the simplified date and return it.
simplifiedDate = month + " " + day + ", " + year;
return simplifiedDate;
}
// The following function relates to the route, NEW POSTS, created below
// it. The function takes the military time that is stored in the database
// and converts it to regular time. This conversion function is called
// in the route below that displays events on the page.
function convertToStandardTime(eventTime){
// Convert the military time for the parameter passed
// through the function (start and end times).
var time = eventTime;
// Convert the time into an array.
time = time.split(':');
// Create variables for the hours and minutes
// by accessing the first and second array elements.
var hours = Number(time[0]);
var minutes = Number(time[1]);
// Create a variable for calculating
// the regular time value.
var timeValue;
// Convert the military time to regular
// time hours using the conditionals.
if (hours > 0 && hours <= 12) {
timeValue = "" + hours;
} else if (hours > 12) {
timeValue = "" + (hours - 12);
} else if (hours == 0) {
timeValue = "12";
}
// Get the minutes for the time and determine whether it is in AM or PM.
timeValue += (minutes < 10) ? ":0" + minutes : ":" + minutes;
timeValue += (hours >= 12) ? " P.M." : " A.M.";
// Return the converted time variable value.
return timeValue;
}
// The function is used to convert times into military time.
// This is useful in the case where two times or time ranges
// are compared to determine overlaps.
function convertToMilitaryTime(eventTime) {
// Create variables for storing the data for time conversion.
var [time, modifier] = eventTime.split(" ");
let [hours, minutes] = time.split(":");
// If the hours is equal to 12, set to zero for military time.
if (hours == "12") {
hours = "00";
}
// If the modifier is PM, add 12 to it in accordance with MT.
if (modifier == "P.M.") {
hours = parseInt(hours, 10) + 12;
}
// Add the minutes to the hours in decimal form.
hours = hours + (parseInt(minutes, 10) / 100);
// Return the converted value.
// return `${hours}:${minutes}`;
return hours;
}
/* SECTION WITHIN GET: RENDERING A PAGE ON THE SCREEN SPECIFIC TO AN EVENT */
// Create a get request route for NEW POSTS.
app.get("/events/:eventId", function(req, res){
// Create a constant for storing the post ID so that it
// can be retrieved from the database.
const requestedEventId = req.params.eventId;
// Use the findOne function to find the post that the user
// wishes to view from the database based on the post ID.
// The method will look for the post that matches the ID
// that was requested indirectly by the user and render
// that post on the screen.
EventModel.findOne({_id: requestedEventId}, function(err, event){
// Call a function to simplify the date of the event.
const eventDate = simplifyEventDate(event.eventDate);
// Call a function to to convert the event start time and event
// end time, both in military time, to regular time.
const eventStartTime = convertToStandardTime(event.eventStartTime);
const eventEndTime = convertToStandardTime(event.eventEndTime);
// Render the post that was requested by the user on
// the website.
res.render("specific_event", {
user: req.user,
eventID: event.id,
eventName: event.eventName,
eventDate: eventDate,
eventStartTime: eventStartTime,
eventEndTime: eventEndTime,
eventTimeIncrements: event.eventTimeIncrements,
eventLocation: event.eventLocation,
eventDescription: event.eventDescription,
numVolunteersNeeded: event.numVolunteersNeeded,
neededDonations: event.neededDonations,
numDonations: event.numDonations,
successVolunteeredOrDonated: req.flash("successVolunteeredOrDonated"),
alreadyVolunteered: req.flash("alreadyVolunteered"),
});
});
});
// ============================================================================================================
/* SECTION: PROCESS REQUESTS MADE TO SERVER (POST) */
// Create a post request for when user clicks any "Back" button.
app.post("/back", function(req, res){
// Render the home page and determine if user is undefined.
res.redirect("/home");
});
// Create a post request for when the user clicks
// the link to download the user help manual.
app.post("/download_help", function(req, res){
res.redirect("/download_help");
});