From 52af02f93f23f525be852041ce896ad9f4b39b8b Mon Sep 17 00:00:00 2001 From: Aishwayao11k Date: Wed, 23 Jul 2025 10:22:13 +0530 Subject: [PATCH 1/3] Describe your changes --- final_project/index.js | 18 ++++++++- final_project/router/auth_users.js | 60 ++++++++++++++++++++++++------ final_project/router/general.js | 45 +++++++++++++++++++--- 3 files changed, 104 insertions(+), 19 deletions(-) diff --git a/final_project/index.js b/final_project/index.js index b890c1d380..a7a0f0e6ef 100644 --- a/final_project/index.js +++ b/final_project/index.js @@ -11,9 +11,23 @@ app.use(express.json()); app.use("/customer",session({secret:"fingerprint_customer",resave: true, saveUninitialized: true})) app.use("/customer/auth/*", function auth(req,res,next){ -//Write the authenication mechanism here + const token = req.session.authorization?.accessToken; + + if (!token) { + return res.status(403).json({ message: "Access token missing" }); + } + + jwt.verify(token, "access", (err, user) => { + if (err) { + return res.status(403).json({ message: "Invalid token" }); + } + + // If token is valid, proceed to the next middleware/route + req.user = user; + next(); + }); }); - + const PORT =5000; app.use("/customer", customer_routes); diff --git a/final_project/router/auth_users.js b/final_project/router/auth_users.js index 8cb6ef6e40..b43c513e4f 100644 --- a/final_project/router/auth_users.js +++ b/final_project/router/auth_users.js @@ -5,24 +5,62 @@ const regd_users = express.Router(); let users = []; -const isValid = (username)=>{ //returns boolean -//write code to check is the username is valid +const isValid = (username) => { + return users.some((user) => user.username === username); } -const authenticatedUser = (username,password)=>{ //returns boolean -//write code to check if username and password match the one we have in records. +const authenticatedUser = (username, password) => { + return users.some((user) => user.username === username && user.password === password); } -//only registered users can login -regd_users.post("/login", (req,res) => { - //Write your code here - return res.status(300).json({message: "Yet to be implemented"}); +// Only registered users can login +regd_users.post("/login", (req, res) => { + const { username, password } = req.body; + + // Check for missing credentials + if (!username || !password) { + return res.status(400).json({ message: "Username and password required" }); + } + + // Authenticate user + if (!authenticatedUser(username, password)) { + return res.status(401).json({ message: "Invalid login credentials" }); + } + + // Generate JWT + const accessToken = jwt.sign({ username }, 'access', { expiresIn: '1h' }); + + // Save token and username in session + req.session.authorization = { + accessToken, + username, + }; + + return res.status(200).json({ message: "User successfully logged in" }); }); -// Add a book review +// Add or update a book review regd_users.put("/auth/review/:isbn", (req, res) => { - //Write your code here - return res.status(300).json({message: "Yet to be implemented"}); + const isbn = req.params.isbn; + const review = req.body.review; + const username = req.session.authorization?.username; + + if (!username) { + return res.status(401).json({ message: "Unauthorized: Please login first" }); + } + + if (!books[isbn]) { + return res.status(404).json({ message: "Book not found" }); + } + + if (!review) { + return res.status(400).json({ message: "Review cannot be empty" }); + } + + // Add or update the review + books[isbn].reviews[username] = review; + + return res.status(200).json({ message: "Review added/updated successfully" }); }); module.exports.authenticated = regd_users; diff --git a/final_project/router/general.js b/final_project/router/general.js index 9eb0ac1a91..c6c5f30878 100644 --- a/final_project/router/general.js +++ b/final_project/router/general.js @@ -7,37 +7,70 @@ const public_users = express.Router(); public_users.post("/register", (req,res) => { //Write your code here - return res.status(300).json({message: "Yet to be implemented"}); + const { username, password } = req.body; + + if (!username || !password) { + return res.status(400).json({ message: "Username and password are required" }); + } + + const userExists = users.some((user) => user.username === username); + + if (userExists) { + return res.status(409).json({ message: "User already exists" }); + } + + users.push({ username, password }); + return res.status(200).json({ message: "User registered successfully" });; }); // Get the book list available in the shop public_users.get('/',function (req, res) { //Write your code here - return res.status(300).json({message: "Yet to be implemented"}); + res.send(users); }); // Get book details based on ISBN public_users.get('/isbn/:isbn',function (req, res) { //Write your code here - return res.status(300).json({message: "Yet to be implemented"}); + const isbn = req.params.isbn; + // Filter the users array to find users whose lastName matches the extracted lastName parameter + let filtered_isbn = users.filter((user) => user.isbn === isbn); + // Send the filtered_lastname array as the response to the client + res.send(filtered_isbn); }); // Get book details based on author public_users.get('/author/:author',function (req, res) { //Write your code here - return res.status(300).json({message: "Yet to be implemented"}); + const author = req.params.author; + // Filter the users array to find users whose lastName matches the extracted lastName parameter + let filtered_author = users.filter((user) => user.author === author); + // Send the filtered_lastname array as the response to the client + res.send(filtered_author); }); // Get all books based on title public_users.get('/title/:title',function (req, res) { //Write your code here - return res.status(300).json({message: "Yet to be implemented"}); + const title = req.params.title; + // Filter the users array to find users whose lastName matches the extracted lastName parameter + let filtered_title = users.filter((user) => user.title === title); + // Send the filtered_lastname array as the response to the client + res.send(filtered_title); }); // Get book review public_users.get('/review/:isbn',function (req, res) { //Write your code here - return res.status(300).json({message: "Yet to be implemented"}); + + const isbn = req.params.isbn; + const book = books[isbn]; + + if (book) { + res.status(200).json({ reviews: book.reviews }); + } else { + res.status(404).json({ message: "Book not found" }); + } }); module.exports.general = public_users; From ee2852dc73323f42734a3b7ff1cd92524fc44bbb Mon Sep 17 00:00:00 2001 From: Aishwayao11k Date: Wed, 23 Jul 2025 10:28:56 +0530 Subject: [PATCH 2/3] Final changes --- final_project/router/general.js | 104 ++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) diff --git a/final_project/router/general.js b/final_project/router/general.js index c6c5f30878..7a61fd0746 100644 --- a/final_project/router/general.js +++ b/final_project/router/general.js @@ -3,6 +3,110 @@ let books = require("./booksdb.js"); let isValid = require("./auth_users.js").isValid; let users = require("./auth_users.js").users; const public_users = express.Router(); +const axios = require('axios'); + +// ----------------------------- +// 📚 Task 10: Get all books +// ----------------------------- + +// Async/Await version +const getAllBooksAsync = async () => { + try { + const response = await axios.get('http://localhost:5000/'); + console.log("Task 10 (Async) - All Books:\n", response.data); + } catch (error) { + console.error("Error in Task 10 (Async):", error.message); + } +}; + +// Promise version +const getAllBooksPromise = () => { + axios.get('http://localhost:5000/') + .then(response => { + console.log("Task 10 (Promise) - All Books:\n", response.data); + }) + .catch(error => { + console.error("Error in Task 10 (Promise):", error.message); + }); +}; + +// ----------------------------- +// 📘 Task 11: Get book by ISBN +// ----------------------------- + +// Async/Await version +const getBookByISBNAsync = async (isbn) => { + try { + const response = await axios.get(`http://localhost:5000/isbn/${isbn}`); + console.log(`Task 11 (Async) - Book with ISBN ${isbn}:\n`, response.data); + } catch (error) { + console.error("Error in Task 11 (Async):", error.message); + } +}; + +// Promise version +const getBookByISBNPromise = (isbn) => { + axios.get(`http://localhost:5000/isbn/${isbn}`) + .then(response => { + console.log(`Task 11 (Promise) - Book with ISBN ${isbn}:\n`, response.data); + }) + .catch(error => { + console.error("Error in Task 11 (Promise):", error.message); + }); +}; + +// ----------------------------- +// 🧑‍💼 Task 12: Get book by Author +// ----------------------------- + +// Async/Await version +const getBooksByAuthorAsync = async (author) => { + try { + const response = await axios.get(`http://localhost:5000/author/${author}`); + console.log(`Task 12 (Async) - Books by author "${author}":\n`, response.data); + } catch (error) { + console.error("Error in Task 12 (Async):", error.message); + } +}; + +// Promise version +const getBooksByAuthorPromise = (author) => { + axios.get(`http://localhost:5000/author/${author}`) + .then(response => { + console.log(`Task 12 (Promise) - Books by author "${author}":\n`, response.data); + }) + .catch(error => { + console.error("Error in Task 12 (Promise):", error.message); + }); +}; + +// ----------------------------- +// 📖 Task 13: Get book by Title +// ----------------------------- + +// Async/Await version +const getBooksByTitleAsync = async (title) => { + try { + const response = await axios.get(`http://localhost:5000/title/${title}`); + console.log(`Task 13 (Async) - Books with title "${title}":\n`, response.data); + } catch (error) { + console.error("Error in Task 13 (Async):", error.message); + } +}; + +// Promise version +const getBooksByTitlePromise = (title) => { + axios.get(`http://localhost:5000/title/${title}`) + .then(response => { + console.log(`Task 13 (Promise) - Books with title "${title}":\n`, response.data); + }) + .catch(error => { + console.error("Error in Task 13 (Promise):", error.message); + }); +}; + + + public_users.post("/register", (req,res) => { From fff344a7c1bd5be75a3da57e3bc60bc8b41251cd Mon Sep 17 00:00:00 2001 From: Aishwayao11k Date: Wed, 23 Jul 2025 15:18:22 +0530 Subject: [PATCH 3/3] rectifying the mistakes --- final_project/router/auth_users.js | 52 ++++++++++++++++----------- final_project/router/general.js | 57 ++++++++++++++++++++++-------- 2 files changed, 74 insertions(+), 35 deletions(-) diff --git a/final_project/router/auth_users.js b/final_project/router/auth_users.js index b43c513e4f..aac2b128c4 100644 --- a/final_project/router/auth_users.js +++ b/final_project/router/auth_users.js @@ -41,26 +41,38 @@ regd_users.post("/login", (req, res) => { // Add or update a book review regd_users.put("/auth/review/:isbn", (req, res) => { - const isbn = req.params.isbn; - const review = req.body.review; - const username = req.session.authorization?.username; - - if (!username) { - return res.status(401).json({ message: "Unauthorized: Please login first" }); - } - - if (!books[isbn]) { - return res.status(404).json({ message: "Book not found" }); - } - - if (!review) { - return res.status(400).json({ message: "Review cannot be empty" }); - } - - // Add or update the review - books[isbn].reviews[username] = review; - - return res.status(200).json({ message: "Review added/updated successfully" }); + const isbn = req.params.isbn; + const review = req.query.review; + const username = req.session.authorization?.username; + + // Check if user is logged in + if (!username) { + return res.status(401).json({ message: "Unauthorized: Please log in" }); + } + + // Validate input + if (!review) { + return res.status(400).json({ message: "Review is required in query" }); + } + + if (!books[isbn]) { + return res.status(404).json({ message: "Book not found" }); + } + + // Add or update review + books[isbn].reviews[username] = review; + + req.session.authorization = { + accessToken, + username, + }; + + return res.status(200).json({ + message: "Review added/updated successfully", + reviews: books[isbn].reviews + }); + + }); module.exports.authenticated = regd_users; diff --git a/final_project/router/general.js b/final_project/router/general.js index 7a61fd0746..886f6145db 100644 --- a/final_project/router/general.js +++ b/final_project/router/general.js @@ -130,37 +130,63 @@ public_users.post("/register", (req,res) => { // Get the book list available in the shop public_users.get('/',function (req, res) { //Write your code here - res.send(users); + // ✅ Get list of books + + return res.status(200).send(JSON.stringify(books, null, 4)); + }); // Get book details based on ISBN public_users.get('/isbn/:isbn',function (req, res) { //Write your code here - const isbn = req.params.isbn; - // Filter the users array to find users whose lastName matches the extracted lastName parameter - let filtered_isbn = users.filter((user) => user.isbn === isbn); - // Send the filtered_lastname array as the response to the client - res.send(filtered_isbn); + const isbn = req.params.isbn; + + if (books[isbn]) { + return res.status(200).send(JSON.stringify(books[isbn], null, 4)); + } else { + return res.status(404).json({ message: 'Book not found' }); + } }); // Get book details based on author public_users.get('/author/:author',function (req, res) { //Write your code here const author = req.params.author; - // Filter the users array to find users whose lastName matches the extracted lastName parameter - let filtered_author = users.filter((user) => user.author === author); - // Send the filtered_lastname array as the response to the client - res.send(filtered_author); + const matchingBooks = []; + + // Get all keys (ISBNs) and check each book + Object.keys(books).forEach(isbn => { + if (books[isbn].author.toLowerCase() === author.toLowerCase()) { + matchingBooks.push({ isbn, ...books[isbn] }); + } + }); + + if (matchingBooks.length === 0) { + return res.status(404).json({ message: "No books found for the given author" }); + } + + return res.status(200).send(JSON.stringify(matchingBooks, null, 4)); }); + // Get all books based on title public_users.get('/title/:title',function (req, res) { //Write your code here - const title = req.params.title; - // Filter the users array to find users whose lastName matches the extracted lastName parameter - let filtered_title = users.filter((user) => user.title === title); - // Send the filtered_lastname array as the response to the client - res.send(filtered_title); + const title = req.params.title; + const matchingBooks = []; + + Object.keys(books).forEach(isbn => { + if (books[isbn].title.toLowerCase() === title.toLowerCase()) { + matchingBooks.push({ isbn, ...books[isbn] }); + } + }); + + if (matchingBooks.length === 0) { + return res.status(404).json({ message: "No books found with the given title" }); + } + + return res.status(200).send(JSON.stringify(matchingBooks, null, 4)); + }); // Get book review @@ -178,3 +204,4 @@ public_users.get('/review/:isbn',function (req, res) { }); module.exports.general = public_users; +