-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
547 lines (484 loc) · 14.9 KB
/
index.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
//Database setup
require("dotenv").config();
const mongoose = require("mongoose");
const mongoDBURL = process.env.MONGODB_URL;
const uploadImage = require("./uploadCloudinary");
const cloudinary = require("cloudinary");
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
mongoose
.connect(mongoDBURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("MongoDB connectedd");
})
.catch((err) => {
console.error("MongoDB connection error:", err);
});
const start = async () => {
try {
await mongoose
.connect(mongoDBURL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
const port = process.env.PORT || 3000;
const server = app.listen(port, "0.0.0.0", () => {
const addr = server.address();
console.log(`🛸 Server listening at http://localhost:${addr.port}`);
});
});
} catch (error) {
console.error(error);
process.exit(1);
}
};
start();
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors"); //allows our client to access our server locally
const passport = require("passport");
const session = require("express-session");
flash = require("express-flash");
require("dotenv").config();
require("./config/passport");
require("./config/google");
const app = express();
app.use(bodyParser.json());
const allowedOrigins = [
"http://localhost:3001",
"http://localhost:3000",
"https://rdt-backend-production.up.railway.app",
"https://superb-pocket.surge.sh",
"http://enormous-fowl.surge.sh",
];
app.use(
cors({
origin: (origin, callback) => {
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) === -1) {
const msg =
"The CORS policy for this site does not allow access from the specified Origin.";
return callback(new Error(msg), false);
}
return callback(null, true);
},
credentials: true,
})
);
// app.use(cors({ origin: "http://localhost:3001", credentials: true }));
// routes
var authRouter = require("./routes/auth");
app.use(
session({
secret: "anthony_secret_key",
resave: false,
saveUninitialized: true,
cookie: {
secure: "auto", // or true if you're using HTTPS
maxAge: 3600000, // Adjust according to your needs
},
})
);
app.use(flash());
// Initialize Passport and configure it to use sessions
app.use(passport.initialize());
app.use(passport.session());
app.use(authRouter);
const Event = require("./models/Event");
const User = require("./models/User");
const Ticket = require("./models/Ticket");
// this will be your "database"
var database = [
{
name: "Event1",
date: "2024-02-15T00:00:00Z",
deadline: "2024-02-18T12:00:00Z",
description: "This is the first event",
price: [10.99, 15.99, 20.99],
startTime: "2024-02-20T18:00:00Z",
endTime: "2024-02-20T22:00:00Z",
location: "Venue A",
},
{
name: "Event2",
date: "2024-03-15T00:00:00Z",
deadline: "2024-03-10T12:00:00Z",
description: "Another event happening next month",
price: [12.99, 18.99, 25.99],
startTime: "2024-03-15T19:30:00Z",
endTime: "2024-03-15T23:00:00Z",
location: "Venue B",
},
{
name: "Event3",
date: "2024-04-10T00:00:00Z",
deadline: "2024-04-05T12:00:00Z",
description: "An event with a different location",
price: [8.99, 14.99, 19.99],
startTime: "2024-04-10T17:00:00Z",
endTime: "2024-04-10T21:30:00Z",
location: "Venue C",
},
];
// TODO ROUTE #1 - Get all current events
// for admin to be able to see all events (past and future)
//Done
app.get("/getallevents", async (req, res, next) => {
const all_events = await Event.find();
res.json(all_events);
});
// default for client to see all upcoming events - Rahul Done
app.get("/getallfutureevents", async (req, res, next) => {
try {
const currentDate = new Date();
//filtered events to see if date field is greater than or equal to current date
const future_events = await Event.find({
startDate: { $gte: currentDate },
});
res.json(future_events)
} catch (err) {
console.log(err.message);
res.status(405).json({ error: err.message });
}
});
app.get("/getByPromo", async (req, res, next) => {
//assume promo code is entered as a string
//returns events that contain a specific promocode and are future events so
//people can't access past events that contain a same promocode
try {
const promoCode = req.body.promoCode;
const currentDate = new Date();
const events = await Event.aggregate([
{
$addFields: {
redemptionCodesArray: { $objectToArray: "$redemptionCodes" },
},
},
// Match documents where any key matches the specified key
{
$match: {
"redemptionCodesArray.k": promoCode,
startDate: { $gte: currentDate },
},
},
]);
if (events.length != 0) {
res.json(events);
} else {
throw new Error("No Events with that Promo Code");
}
} catch (error) {
console.log(error.message);
res.status(405).json({ error: error.message });
}
});
// TODO ROUTE #2 -> For Next Week
// For client to see their events
app.get("/getMyTickets", async (req, res, next) => {
//assuming the input from the request is the id of
//the user who's finding their tickets
try {
const user = await User.findOne({ _id: req.body.user_id });
const my_tickets = user.tickets;
if (my_tickets.length != 0) {
res.json(my_tickets);
} else {
throw new Error("You don't have any tickets");
}
} catch (error) {
console.log(error.message);
res.status(406).json({ error: error.message });
}
});
// For the admin to get tickets - Tayten
app.get("/getTicketsEvent", async (req, res, next) => {
try {
const event = await Event.findOne({ name: req.body.name });
if (event) {
res.json(event.tickets);
} else {
res.status(404).json({ error: "Event not found" });
}
} catch (error) {
next(error); // Pass the error
}
});
//Get all users - Ashley
app.get("/getusers", async (req, res, next) => {
console.log("test5 ");
const users = await User.find();
res.json(users);
});
// Get ticket -Neyida
app.post("/getticket", async (req, res, next) => {
console.log("test5");
const ticket = await Ticket.find();
res.json(ticket);
});
// Get event- Rachel
app.get("/getevent", async (req, res, next) => {
const eventID = req.query.eventID;
const event = await Event.findOne({ _id: eventID });
res.json(event);
});
// TODO ROUTE #2 - Add a new event Done
app.post("/addevent", async (req, res, next) => {
//Creates an event with empty tickets array
try {
const newEvent = new Event({
name: req.body.name,
date: req.body.date,
startTime: req.body.startTime,
endTime: req.body.endTime,
description: req.body.description,
basePrice: req.body.basePrice,
redemptionCode: req.body.redemptionCode,
location: req.body.location,
studentDiscount: req.body.studentDiscount,
atDoorPrice: req.body.atDoorPrice,
availableSeats: req.body.availableSeats,
coverPhoto: req.body.coverPhoto,
seatingPhoto: req.body.seatingPhoto
});
//loops through each seat in the seating chart and creates a ticket for the seat
//adds the ticket's id to the Event's ticket array
for (let seat of newEvent.availableSeats) {
try {
const newTicket = new Ticket({
seat: seat,
event: newEvent._id,
isPaid: false,
user: null,
buyerName: null,
attendeeName: null,
});
await newTicket.save();
newEvent.tickets.push(newTicket._id);
} catch (error) {
console.error("Error creating ticket: ", error);
res.status(501).send(error.message);
}
}
await newEvent.save();
res.status(201).json({ newEvent: newEvent });
} catch (error) {
console.error("Error creating event: ", error);
res.status(500).send(error.message);
}
});
// Edit profile
app.put("/editprofile", async (req, res, next) => {
try {
// Assuming for now that a user cannot update their email address
// If a user can change their email, need to include functionality to potentially update isRiceStudent field
const updatedUser = await User.findOneAndUpdate(
{ _id: req.body.user_id },
req.body.changes,
{
new: true,
}
); // changes is a mapping of each field to its new value
res.status(201).json({ updatedUserInfo: updatedUser });
} catch (error) {
console.error("Error editing profile: ", error);
res.status(500).send(error.message);
}
});
// Purchase ticket
app.put("/purchaseticket", async (req, res, next) => {
try {
//console.log(req);
console.log(req.body);
const user = await User.findOne({ _id: req.body.user_id });
// Assume iterable of ticket IDs is passed in
// Not sure if front end will know ticket IDs, might only pass in seat numbers
// Need to discuss how seat selection process will work
let purchasedTickets = [];
for (const ticketInfo of req.body.tickets) {
// {
// seat:
// type:
// buyername,
// attendeename
// }
const ticket = await Ticket.findOne({ seat: ticketInfo.seat });
// ticket.user = req.body.user_id;
ticket.type = ticketInfo.type
ticket.buyerName = ticketInfo.buyerName
ticket.attendeeName = ticketInfo.attendeeName
// ticket.isPaid = true;
await ticket.save();
purchasedTickets.push(ticket);
// Push ticket into user's array of tickets
user.tickets.push(ticket);
await user.save();
}
res
.status(201)
.json({ purchasedTickets: purchasedTickets, userTickets: user.tickets });
} catch (error) {
console.error("Error purchasing ticket(s): ", error);
res.status(500).send(error.message);
}
});
app.put("/removeticket", async (req, res, next) => {
try {
// inputs: ticketID and user_id
const ticketToRemove = await Ticket.findOne({ _id: req.body.ticketID });
ticketToRemove.user = null;
ticketToRemove.isPaid = false;
await ticketToRemove.save();
const user = await User.findOne({ _id: req.body.user_id });
// filter out ticketID from user's array of purchased tickets
user.tickets = user.tickets.filter(
(id) => id.toString() !== req.body.ticketID
);
await user.save();
res
.status(201)
.json({ removedTicket: ticketToRemove, userTickets: user.tickets });
} catch (error) {
console.error("Error removing ticket: ", error);
res.status(500).send(error.message);
}
});
app.delete("/deleteevent", async (req, res, next) => {
// delete all tickets associated with the event
try {
const eventToDelete = await Event.findOne({ _id: req.body.event_id });
for (const ticket_id of eventToDelete.tickets) {
await Ticket.findByIdAndDelete(ticket_id);
// if a user already purchased this ticket, delete the ticket from their tickets array
await User.updateOne(
{ tickets: ticket_id },
{ $pull: { tickets: ticket_id } }
);
}
// delete the event
const deletedEvent = await Event.findByIdAndDelete(req.body.event_id);
res.status(200).json({ deletedEvent: deletedEvent });
} catch (error) {
console.error("Error deleting event: ", error);
res.status(404).send(error.message);
}
});
// TODO ROUTE #3 - Remove an existing shopping item
app.delete("/remove", (req, res, next) => {
//console.log(req.body)
try {
let newDatabase = database.filter((item) => item.name != req.body.name);
database = newDatabase;
console.log(newDatabase);
res.json(database);
} catch (error) {
console.error(error);
}
});
// TODO ROUTE #4 - Update event by time/name
app.put("/updateevent", async (req, res, next) => {
// console.log(req);
let filter = req.query;
let update = req.body;
let updatedEvent = await Event.findOneAndUpdate(filter, update);
// res.status(200)
res.json(updatedEvent);
});
app.put(
"/imageCoverUpload",
uploadImage("public_id_field"),
async (req, res) => {
if (!req.fileurl || !req.fileid) {
return res.status(422).send({ message: "Image upload failed" });
}
const event = await Event.findOne({
_id: req.body._id,
}).exec();
if (!event) {
return res.status(404).send({ message: "Event not found" });
}
event.coverPhoto = req.fileurl;
await event.save();
res.json({ name: req.body.name, coverPhoto: req.fileurl });
}
);
app.put(
"/imageSeatingUpload",
uploadImage("public_id_field"),
async (req, res) => {
if (!req.fileurl || !req.fileid) {
return res.status(422).send({ message: "Image upload failed" });
}
const event = await Event.findOne({
_id: req.body._id,
}).exec();
if (!event) {
return res.status(404).send({ message: "Event not found" });
}
event.seatingPhoto = req.fileurl;
await event.save();
res.json({ name: req.body.name, seatingPhoto: req.fileurl });
}
);
app.put(
"/imageRegisterCoverUpload",
uploadImage("public_id_field"),
async (req, res) => {
if (!req.fileurl || !req.fileid) {
return res.status(422).send({ message: "Image upload failed" });
}
// const event = await Event.findOne({
// _id: req.body._id,
// }).exec();
// if (!event) {
// return res.status(404).send({ message: "Event not found" });
// }
// event.seatingPhoto = req.fileurl;
// await event.save();
res.json({ coverPhoto: req.fileurl });
}
);
app.put(
"/imageRegisterSeatingUpload",
uploadImage("public_id_field"),
async (req, res) => {
if (!req.fileurl || !req.fileid) {
return res.status(422).send({ message: "Image upload failed" });
}
// const event = await Event.findOne({
// _id: req.body._id,
// }).exec();
// if (!event) {
// return res.status(404).send({ message: "Event not found" });
// }
// event.seatingPhoto = req.fileurl;
// await event.save();
res.json({ seatingPhoto: req.fileurl });
}
);
app.get("/ticketsforevent", async (req, res, next) => {
// console.log(req)
let name = req.query.name;
const event = await Event.findOne({ name: name });
const ticketIds = event.tickets;
console.log(ticketIds);
try {
// Convert ticketIds to ObjectIDs
const objectIds = ticketIds.map((id) => new mongoose.Types.ObjectId(id));
// Find tickets by IDs
const tickets = await Ticket.find({ _id: { $in: objectIds } });
console.log(tickets);
res.json({ tickets });
} catch (error) {
console.error("Error fetching tickets:", error);
res.status(500).json({ error: "Failed to fetch tickets" });
}
});
// TODO ROUTE #5 - Get shopping items that satisfy a condition/filter (harder)
module.exports = app;