-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
626 lines (411 loc) · 16.7 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
import fetch from "node-fetch"; // for HTTP requests
import express, { response } from "express"; // for HTTP requests
import session from 'express-session';
import bodyParser from 'body-parser';
import path from "path";
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';
import { getOptions } from './utils/getFetchOptions.js';
import { fetchOrUseCache } from "./utils/fetchHelper.js";
import User from "./models/user.js";
import { PasswordStrengthChecker, PasswordImplementer} from "./utils/password.js";
import { MemoryCache } from "./utils/memCache.js";
import {MemoryDB, CacheSaveTypes} from "./utils/cache.js";
import { saveDynamicPageSection } from "./utils/pageSectionService.js";
import Movie from "./models/movie.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
const SECRET_KEY = process.env.SECRET_KEY;
let memoryDB = null;
// Serve static files from the "static" directory
app.use(express.static(path.join(__dirname, "public")));
// render where we want to serve the files
app.set("views", path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
import rateLimit from 'express-rate-limit';
import { accessSync } from "fs";
// // Create a rate limiter middleware
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again later'
});
// Apply the rate limiter to all requests
app.use(limiter);
// Session Middleware
app.use(session({
secret: SECRET_KEY,
resave: false,
saveUninitialized: true,
cookie: { secure: false } // Adjust secure option based on your deployment environment
}));
app.use((req, res, next) => {
res.locals.userId = req.session.userId;
res.locals.isAdmin = req.session.isAdmin;
next();
});
// Initialization the cache when the server starts
function initializeCache(req, res, next) {
const memCache = new MemoryCache();
if (!memoryDB) {
memoryDB = new MemoryDB(memCache);
memoryDB.createTables();
}
next();
}
function isAuthenticated (req, res, next) {
if (req.session.userId) {
return res.redirect("/landing-page");
}
next();
};
const authenticateUser = (req, res, next) => {
if (req.session.userId) {
next();
} else {
res.status(401).send("Unauthorized access. Please log in.");
}
};
app.use(initializeCache);
// Parse JSON bodies
app.use(bodyParser.json());
app.use(express.json()); // Middleware to parse JSON request bodies
// Parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
const authorizationKey = process.env.MOVIE_API_READ_ACCESS_TOKEN;
const options = getOptions(authorizationKey);
// Route to handle requests for jokes
app.get("/joke", async (req, res) => {
try {
// Request to JokeAPI
const response = await fetch("https://v2.jokeapi.dev/joke/Any?contains=pint");
// const data = await response.json();
// const joke = data.contents.jokes[0].joke.text;
// Send the joke back as JSON
// res.json({ joke });
} catch (error) {
console.error("Error fetching joke:", error);
res.status(500).json({ error: "Failed to fetch joke" });
}
});
// Dashboard
app.get("/admin", authenticateUser, async(req, res) => {
const userObj = memoryDB.getCacheByName(req.session.userId);
if (!userObj) {
return res.status(500).send("Something went wrong!!");
}
const user = User.setDataFromCache(userObj);
if (!user) {
throw new Error("Something went wrong the user was not found!!")
}
res.render("admin/admin", {joined: user.dateJoined,
hashedPassword: user.password,
email: user.email,
remainingSpace: memoryDB.remainingSpace,
maximumSize: memoryDB.maximumSize,
noOfSearchTermsMade: user.countSearchTerms(),
ratings: user.countRatings(),
favourites: user.countFavourites(),
watchList: user.countWatchlistItems(),
NO_OF_API_REQUESTS: user.countAPIRequests(),
});
})
app.post("/admin", authenticateUser, async(req, res) => {
res.render("admin/admin");
})
// Admin form
app.post("/admin-form", async(req, res) => {
const username = req.body.username;
const password = req.body.password;
let invalid;
const userObj = memoryDB.getCacheByName(username);
if (userObj) {
const user = User.setDataFromCache(userObj);
// Take the user's plaintext password entered and compared to the one in the database
const result = await PasswordImplementer.verifyPassword(password, user.password);
if (result && user.isActive && user.isAdmin) {
req.session.userId = user.username;
req.session.isAdmin = true;
return res.status(200).redirect("/landing-page");
}
}
invalid = "Incorrect email and username";
res.render("authentication/admin-form", {invalid: invalid});
})
app.get("/admin-form", async(req, res) => {
let invalid;
res.render("authentication/admin-form", {invalid: invalid});
})
// register
app.get("/register", isAuthenticated, async(req, res) => {
res.render("authentication/register");
})
app.post("/register", async(req, res) => {
const form = req.body;
if (!form) {
return res.status(400).send("No form data provided");
}
const user = User.createNewUser(memoryDB, form.username);
user.setUsername(form.username);
user.setEmail(form.email);
const passwordImplementer = new PasswordImplementer(form.password);
try {
const hashedPassword = await passwordImplementer.hashPassword();
user.setPassword(hashedPassword);
user.save()
} catch (error) {
res.status(500).send(`Something went wrong couldn't encrypt the password! ${error}`);
}
return res.redirect("/login");
})
// login
app.get("/login", isAuthenticated, async(req, res) => {
let invalid;
res.render("authentication/login", {invalid: invalid});
})
app.post("/login", isAuthenticated, async(req, res) => {
const username = req.body.username;
const password = req.body.password;
let invalid;
const userObj = memoryDB.getCacheByName(username);
// Takes the complicated nested user data stored in the cache and stores it a way that can be accessed by "dot notation"
const user = User.setDataFromCache(userObj);
if (user) {
// Take the user's plaintext password entered and compared to the one in the database
const result = await PasswordImplementer.verifyPassword(password, user.password);
if (result && user.isActive) {
req.session.userId = user.username;
return res.status(200).redirect("/landing-page");
}
}
invalid = "Incorrect email and username";
return res.render("authentication/login", {invalid: invalid});
})
//landing page
app.get("/landing-page", async(req, res) => {
res.render("landing-page");
})
// index
app.get("/", async (req, res) => {
const tableName = "default";
const mainCache = memoryDB.getCacheByName(tableName);
if (!mainCache) {
res.status(500).send("Something went wrong!");
}
const sectionArray = mainCache?.homePage;
if (!sectionArray) {
res.status(404).send("Something went wrong!!");
}
return res.render("index", { sectionArray: sectionArray});
});
// search movies
app.post("/movies", async (req, res) => {
const searchQuery = req.body.search;
const url = `https://api.themoviedb.org/3/search/movie?query=${searchQuery}&include_adult=false&language=en-US&page=`;
const data = {};
let movieData = {};
data.error = "Something went wrong and we couldn't find your search";
data.consoleError = "Error fetching movie data: ";
data.saveAs = CacheSaveTypes.search;
data.fetcError = "Failed to fetch movie data : ";
data.tableName = searchQuery;
const category = CacheSaveTypes.search;
const username = req.session.userId;
const cache = username ? memoryDB.getCacheByName(username) : memoryDB.getDefaultCache();
data.tableArray = cache.searchTerms;
try {
movieData = await fetchOrUseCache(url, options, req, data, memoryDB);
} catch (error) {
console.error(data.consoleError + error);
return res.status(500).json({ error: "Failed to fetch your search query" });
}
return res.render("movies/movies.ejs",
{movies: movieData.data,
url:process.env.MOVIE_IMAGE_BASE_URL,
category: category,
searchQuery: searchQuery },
);
});
app.get("/movies", async(req, res) => {
const searchQuery = null;
const movies = {};
return res.render("movies/movies.ejs", {searchQuery: searchQuery, movies: movies});
})
// details page
app.get("/detail/:id/:category/:searchQuery?", async(req, res) => {
const id = req.params.id;
const userId = req.session.userId;
const category = req.params.category;
const searchQuery = req.params.searchQuery || null;
const cache = userId ? memoryDB.getCacheByName(userId) : memoryDB.getDefaultCache();
const movie = new Movie(cache);
let results;
movie.setCategory(category);
if (searchQuery) {
results = movie.findMovieByIdAndQuery(id, searchQuery);
} else {
results = movie.getMovieByID(id);
}
if (results === null) {
return res.redirect("/not-found")
}
return res.render("movies/detail", { id: id, movieData: results, url: process.env.MOVIE_IMAGE_BASE_URL});
;
});
app.get("/latest-films", async(req, res) => {
const url = 'https://api.themoviedb.org/3/discover/movie?include_adult=false&include_video=false&language=en-US&page=1&sort_by=popularity.desc';
const data = {}
let movieData = {};
data.consoleError = "Error fetching the latest films";
data.fetcError = "Failed to fetch the latest films";
data.tableName = "latest-films";
data.error = data.consoleError;
data.saveAs = CacheSaveTypes.movies;
const username = req.session.userId;
let cache = username ? memoryDB.getCacheByName(username) : memoryDB.getDefaultCache();
data.tableArray = cache.movies;
const category = CacheSaveTypes.movies;
try {
movieData = await fetchOrUseCache(url, options, req, data, memoryDB);
} catch (error) {
console.error(data.consoleError + error);
return res.status(500).json({ error: "Failed to fetch your search query" });
}
return res.render("movies/films.ejs", {movies: movieData.data,
category: category,
url:process.env.MOVIE_IMAGE_BASE_URL })
})
app.get("/tv-shows", async(req, res) => {
const url = 'https://api.themoviedb.org/3/trending/tv/day?language=en-US';
const data = {};
const category = CacheSaveTypes.tvShows;
const username = req.session.userId;
let tvShowsData = {}
let cache = username ? memoryDB.getCacheByName(username) : memoryDB.getDefaultCache();
data.consoleError = "Error fetching the latest TV shows";
data.fetcError = "Failed to fetch the latest show";
data.tableName = "tv-shows";
data.error = data.consoleError;
data.saveAs = CacheSaveTypes.tvShows;
data.tableArray = cache.tvShows;
try {
tvShowsData = await fetchOrUseCache(url, options, req, data, memoryDB );
} catch (error) {
console.error("Error fetching movie data:", error);
return res.status(500).json({ error: "Failed to fetch movie data" });
}
return res.render("movies/tv-shows.ejs", {tvShows: tvShowsData.data,
category: category,
url:process.env.MOVIE_IMAGE_BASE_URL })
})
app.get("/change-password", authenticateUser, async(req, res) => {
res.render("passwords/change-password");
})
app.post("/change-password", authenticateUser, async(req, res) => {
res.render("passwords/change-password");
})
app.get("/forgotten-password", async(req, res) => {
res.render("passwords/forgotten-password");
})
app.post("/forgotten-password", async(req, res) => {
res.render("passwords/forgotten-password");
})
app.get("/logout", authenticateUser, async (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error("Error destroying session:", err);
return res.status(500).send("Error logging out");
}
res.redirect("/"); // Redirect to the homepage or any other page after logout
});
});
app.post("/check-password-strength", (req, res) => {
let passwordObj = {};
if (!req.body || !("password" in req.body)) {
const error = {};
error.ERROR = "Something went wrong, and the password couldn't be extracted!!";
return res.json(error);
}
const password = req.body.password.trim();
if (password.length > 0) {
const passwd = new PasswordStrengthChecker(password);
passwordObj = passwd.checkPasswordStrength();
}
return res.json(passwordObj)
});
app.post("/is-email-unique", (req, res) => {
if (!("email" in req.body)) {
throw new Error("Something went wrong and the email couldn't be retrieved!!!")
}
// If the an obj is returned it means that the email is not unique
// then in that case return false otherwise true
const email = req.body.email;
const userCache = memoryDB.getByEmail(email);
const userObj = {}
userObj.IS_EMAIL_UNIQUE = userCache === null ? true : false
return res.json(userObj);
})
app.post("/edit-homepage-section/:id", authenticateUser, (req, res) => {
const sectionID = req.params.id;
const tableName = "default";
let sectionName = null;
switch (sectionID) {
case "1":
sectionName = "SectionOne";
saveDynamicPageSection(req, sectionName, tableName, memoryDB);
break;
case "2":
sectionName = "SectionTwo";
saveDynamicPageSection(req, sectionName, tableName, memoryDB);
break;
case "3":
sectionName = "SectionThree";
saveDynamicPageSection(req, sectionName, tableName, memoryDB);
break;
case "4":
sectionName = "SectionFour";
saveDynamicPageSection(req, sectionName, tableName, memoryDB);
break;
default:
res.status(400).send("Invalid section ID");
return;
}
res.status(200).send("Section updated successfully");
});
app.post("/handle-form-submission", (req, res) => {
const userForm = req.body.userForm;
if (!userForm) {
res.json(userForm)
return res.status(400).send("Something went wrong and we couldn't register you");
}
const userFormObj = {};
let cacheObj = memoryDB.getCacheByName(userForm.username);
switch (true) {
case cacheObj:
userFormObj.MSG = "Invalid - A user by that name already exists!";
break;
case cacheObj === null:
const emailObj = memoryDB.getByEmail(userForm.email);
userFormObj.EMAIL_MSG = emailObj ? "Invalid - A user by that email already exists!": "Valid email address";
case true:
const passwordChecker = new PasswordStrengthChecker(userForm.password);
const response = passwordChecker.isValid();
const validPasswordMsg = "Valid password";
const validEmailMsg = "Valid email address";
userFormObj.PASSWORD_MSG = response ? validPasswordMsg : "Invalid - The password doesn't meet the strength requirements";
userFormObj.IS_SUCCESS = userFormObj.PASSWORD_MSG === validPasswordMsg && userFormObj.EMAIL_MSG === validEmailMsg;
}
return res.json(userFormObj);
})
app.get("/not-found", async(req, res)=> {
return res.render("errors/404.ejs");
})
app.get("*", async(req, res)=> {
return res.render("errors/404.ejs");
})
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});