-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
459 lines (419 loc) · 11.9 KB
/
index.js
File metadata and controls
459 lines (419 loc) · 11.9 KB
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
import express, { query } from "express";
import axios, { all } from "axios";
import bodyParser from "body-parser";
import pg from "pg";
import bcrypt from "bcrypt";
import passport from "passport";
import { Strategy } from "passport-local";
import session from "express-session";
import env from "dotenv";
const app = express();
const port = process.env.PORT || 3000;
const saltRounds = 10;
env.config();
app.use(session({
secret: process.env.SESSION_SECRET, // Add a secret key here
resave: false, // Optional, depending on your requirements
saveUninitialized: true, // Optional, depending on your requirements
cookie: { secure: false } // Adjust this based on your environment (use true in production with HTTPS)
}));
// Middleware
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(passport.session());
// Connect to database
const db = new pg.Client({
user: process.env.PG_USER,
host: process.env.PG_HOST,
database: process.env.PG_DATABASE,
password: process.env.PG_PASSWORD,
port: process.env.PG_PORT,
});
db.connect();
// Variables
let featured = [];
let random = [];
let latest = [];
let invalidISBN = "";
let specifiedBook = [];
let allBooks = [];
let sortOption = "date";
let allGenres = [];
let selectedGenre = "";
let booksByAuthor = [];
let userQuery = "";
let userAlreadyExist = "";
let userNotFound = "";
let incorrectPsswrd = "";
let userID = 0;
function isAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login'); // Redirect if not authenticated
};
async function getFeatured() {
try {
const result = await db.query("SELECT * FROM books WHERE user_id = $1 AND rating = 10 LIMIT 10;", [ userID ]);
featured = result.rows;
} catch (err) {
console.err(err);
}
};
async function randomBook() {
if (allBooks != 0) {
const num = Math.floor(Math.random() * allBooks.length);
random = allBooks[num];
} else {};
};
async function getLatest() {
try {
const result = await db.query("SELECT * FROM books WHERE user_id = $1 ORDER BY date_read DESC LIMIT 5;", [ userID ]);
latest = result.rows;
} catch (err) {
console.err(err);
}
};
async function getAllBooks() {
try {
const result = await db.query("SELECT * FROM books WHERE user_id = $1 ORDER BY date_read DESC;", [ userID ]);
allBooks = result.rows;
} catch (err) {
console.error(err);
}
};
async function sortBooks() {
if (sortOption === "date") {
allBooks.sort((a, b) => new Date(b.date_read) - new Date(a.date_read))
} else if (sortOption === "title") {
allBooks.sort((a, b) => {
if (a.title < b.title) return -1;
if (a.title > b.title) return 1;
return 0; // equal titles
});
} else if (sortOption === "rating") {
allBooks.sort((a, b) => b.rating - a.rating);
}
};
async function getGenres() {
try {
const result = await db.query("SELECT DISTINCT genre from books WHERE user_id = $1 ORDER BY genre ASC;", [ userID ]);
allGenres = result.rows;
} catch (err) {
console.error(err);
}
};
async function getBooksByGenre() {
const genre = selectedGenre ? selectedGenre.toLowerCase() : '';
const results = allBooks.filter(book => book.genre.toLowerCase().includes(genre));
allBooks = results;
};
async function getBooksByAuthor() {
const author = specifiedBook.author;
try {
const result = await db.query("SELECT * from books WHERE user_id = $1 AND author = $2 ORDER BY date_read DESC", [ userID, author ]);
booksByAuthor = result.rows;
} catch (err) {
console.error(err);
}
}
// GET to sign-up page
app.get("/signup", (req, res) => {
res.render("signup.ejs", {
alreadyExist: userAlreadyExist
});
});
// GET to login page
app.get("/login", (req, res) => {
res.render("login.ejs", {
notFound: userNotFound,
wrongPsswrd: incorrectPsswrd
});
});
// GET to home page
app.get("/", isAuthenticated, async (req, res) => {
await getAllBooks();
await randomBook();
await getFeatured();
await getLatest();
res.render("index.ejs",
{
lucky: random,
featuredBooks: featured,
latestBooks: latest,
isbnError: invalidISBN,
});
});
// GET to about page
app.get("/about.ejs", isAuthenticated, async (req, res) => {
res.render("about.ejs");
});
// GET to contact page
app.get("/contact.ejs", isAuthenticated, async (req, res) => {
res.render("contact.ejs");
});
// GET log out
app.get("/logout", (req, res) => {
// reset values
userAlreadyExist = "";
userNotFound = "";
incorrectPsswrd = "";
random = [];
req.logout(function (err) {
if (err) {
return next(err);
}
res.redirect("/login");
})
})
// GET to new book page
app.get("/new.ejs", isAuthenticated, async (req, res) => {
res.render("new.ejs",
{
isbnError: invalidISBN,
}
);
});
// POST new book journal
app.post("/add", async (req, res) => {
const isbn = req.body.isbn;
const title = req.body.title.trim();
const author = req.body.author.trim();
const genre = req.body.genre.trim();
const date = req.body.dateRead;
const rating = req.body.rating;
const review = req.body.review;
const notes = req.body.notes;
try {
// GET book cover from API
const result = await axios.get(`https://bookcover.longitood.com/bookcover/${isbn}`);
const img_URL = result.data.url;
// INSERT data
try {
await db.query("INSERT INTO books (isbn, title, author, genre, img_URL, date_read, rating, review, notes, user_id)VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);", [ isbn, title, author, genre, img_URL, date, rating, review, notes, userID ]);
invalidISBN = "";
res.redirect("/books.ejs");
} catch (err) {
console.error(err);
}
} catch (err) {
console.error(err);
invalidISBN = "Invalid input: Please use ISBN-13.";
res.redirect("/new.ejs");
}
});
// GET to specific book journal by id
app.get("/journal/:id", isAuthenticated, async (req, res) => {
const rawId = req.params.id.trim();
const id = parseInt(rawId, 10);
if (isNaN(id)) {
return res.status(400).send('Invalid ID');
}
try {
const result = await db.query("SELECT * FROM books WHERE id = $1", [ id ]);
specifiedBook = result.rows[0];
await getBooksByAuthor();
res.render("journal.ejs",
{
book: specifiedBook,
authorBooks: booksByAuthor,
}
);
} catch (err) {
console.log(err);
}
});
// GET to edit page
app.get("/edit.ejs", isAuthenticated, async (req, res) => {
const dateTimeString = specifiedBook.date_read;
let dateOnly;
if (typeof dateTimeString === 'string') {
dateOnly = dateTimeString.split('T')[0];
} else if (dateTimeString instanceof Date) {
dateOnly = dateTimeString.toISOString().split('T')[0];
} else {
console.error('Invalid date format');
}
specifiedBook.date_read = dateOnly;
res.render("edit.ejs",
{
book: specifiedBook,
isbnError: invalidISBN,
}
);
});
// UPDATE book journal
app.post("/modify", async (req, res) => {
const isbn = req.body.isbn;
const title = req.body.title.trim();
const author = req.body.author.trim();
const genre = req.body.genre.trim();
const date = req.body.dateRead;
const rating = req.body.rating;
const review = req.body.review;
const notes = req.body.notes;
const id = specifiedBook.id
try {
// GET book cover from API
const result = await axios.get(`https://bookcover.longitood.com/bookcover/${isbn}`);
const img_URL = result.data.url;
// UPDATE data
try {
await db.query("UPDATE books set isbn = $1, title = $2, author = $3, genre = $4, img_URL = $5, date_Read = $6, rating = $7, review = $8, notes = $9 WHERE id = $10;", [ isbn, title, author, genre, img_URL, date, rating, review, notes, id ]);
invalidISBN = "";
res.redirect(`/journal/${id}`);
} catch (err) {
console.error(err);
}
} catch (err) {
console.error(err);
invalidISBN = "Invalid input: Please use ISBN-13.";
res.redirect("/edit.ejs");
}
});
// DELETE a book journal
app.post("/delete/:id", async (req, res) => {
const id = specifiedBook.id;
try {
await db.query("DELETE FROM books WHERE id = $1", [id]);
res.redirect("/");
} catch (err) {
console.error(err);
res.status(500).json({ message: "Error deleting post" });
}
});
// GET to books page
app.get("/books.ejs", isAuthenticated, async (req, res) => {
await getAllBooks();
await getGenres();
selectedGenre = "";
sortOption = "date";
res.render("books.ejs",
{
typed: userQuery,
books: allBooks,
genres: allGenres
}
);
});
// POST sort books
app.post("/sort", async (req, res) => {
sortOption = req.body.sort;
await sortBooks();
res.json({
books: allBooks,
sort: sortOption,
genre: selectedGenre
});
});
// POST sort by genre
app.post("/genre", async (req, res) => {
selectedGenre = req.body.genre;
await getAllBooks();
await getBooksByGenre();
const results = allBooks;
res.json({
books: allBooks,
sort: sortOption,
genre: selectedGenre
});
});
// GET search book
app.get('/search', async (req, res) => {
await getAllBooks();
await getBooksByGenre();
await sortBooks();
const query = req.query.q ? req.query.q.toLowerCase() : '';
const results = allBooks.filter(book => book.title.toLowerCase().includes(query));
allBooks = results;
res.json({
books: allBooks,
sort: sortOption,
genre: selectedGenre
});
});
// POST login authentication
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login"
})
);
// POST register account
app.post("/register", async (req, res) => {
const email = req.body.username;
const password = req.body.password;
try {
const checkResult = await db.query("SELECT * FROM users WHERE email = $1", [ email ]);
if (checkResult.rows.length > 0 ) {
// user already exists
userAlreadyExist = "Email already in used, try logging in."
res.redirect("/signup");
} else {
// password hashing
bcrypt.hash(password, saltRounds, async (err, hash) => {
if (err) {
console.error("Error hashing password: ", err);
} else {
// insert user to the database
const result = await db.query(
"INSERT INTO users (email, password) VALUES ($1, $2) RETURNING *;",
[ email, hash]
);
const user = result.rows[0];
req.login(user, (err) => {
console.log("success");
userID = user.id;
res.redirect("/");
});
}
});
}
} catch (err) {
console.log(err);
}
});
passport.use(
new Strategy(async function verify(username, password, cb) {
try {
const result = await db.query("SELECT * FROM users WHERE email = $1;", [ username ]);
if (result.rows.length > 0) {
const user = result.rows[0];
const storedHashedPassword = user.password;
bcrypt.compare(password, storedHashedPassword, (err, valid) => {
if (err) {
// Error with password check
console.error("Error comparing password: ", err);
return cb(err);
} else {
if (valid) {
// Passed password check
userID = user.id;
return cb(null, user);
} else {
// Did not pass password check
incorrectPsswrd = "The password you’ve entered is incorrect.";
return cb(null, false);
}
}
});
} else {
userNotFound = "The email you entered isn’t a registered account.";
return cb(null, false);
}
} catch (err) {
console.log(err);
}
})
);
passport.serializeUser((user, cb) => {
cb(null, user);
});
passport.deserializeUser((user, cb) => {
cb(null, user);
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});