From 611a191bd199506891b985e6c1cdd08a5fe5b75a Mon Sep 17 00:00:00 2001 From: Lalo Date: Wed, 14 May 2025 15:42:31 -0700 Subject: [PATCH 1/3] Update auth_users.js Final Project --- final_project/router/auth_users.js | 66 +++++++++++++++++++++++------- 1 file changed, 52 insertions(+), 14 deletions(-) diff --git a/final_project/router/auth_users.js b/final_project/router/auth_users.js index 8cb6ef6e40..1240dc248b 100644 --- a/final_project/router/auth_users.js +++ b/final_project/router/auth_users.js @@ -5,26 +5,64 @@ const regd_users = express.Router(); let users = []; -const isValid = (username)=>{ //returns boolean -//write code to check is the username is valid +const isValid = (username)=>{ + const userMatches = users.filter((user) => user.username === username); + return userMatches.length > 0; } - -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)=>{ + const matchingUsers = users.filter((user) => user.username === username && user.password === password); + return matchingUsers.length > 0; } - -//only registered users can login + +// Task 7 +// Login as a Registered user regd_users.post("/login", (req,res) => { - //Write your code here - return res.status(300).json({message: "Yet to be implemented"}); -}); + const username = req.body.username; + const password = req.body.password; -// Add a book review + if (authenticatedUser(username, password)) { + // Generate a JWT token with the username and password as payload + let accessToken = jwt.sign({data:password}, "access", {expiresIn: 3600}); + req.session.authorization = {accessToken,username}; + return res.status(200).send("User successfully logged in"); + } + else { + return res.status(208).json({message: "Invalid username or password"}); + } +}); + +// Task 8 +// Add/Modify 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 (books[isbn]) { + let book = books[isbn]; + book.reviews[username] = review; + return res.status(200).send("Review successfully posted"); + } + else { + return res.status(404).json({message: `ISBN ${isbn} not found`}); + } }); - + +// Task 9 +// Delete book review added by that particular user +regd_users.delete("/auth/review/:isbn", (req, res) => { + const isbn = req.params.isbn; + const username = req.session.authorization.username; + if (books[isbn]) { + let book = books[isbn]; + delete book.reviews[username]; + return res.status(200).send("Review successfully deleted"); + } + else { + return res.status(404).json({message: `ISBN ${isbn} not found`}); + } +}); + module.exports.authenticated = regd_users; module.exports.isValid = isValid; module.exports.users = users; From 28697f4339188a31e95ccdbad933ed24be241d08 Mon Sep 17 00:00:00 2001 From: Lalo Date: Wed, 14 May 2025 15:42:58 -0700 Subject: [PATCH 2/3] Update general.js Final Project --- final_project/router/general.js | 100 +++++++++++++++++++++++++------- 1 file changed, 80 insertions(+), 20 deletions(-) diff --git a/final_project/router/general.js b/final_project/router/general.js index 9eb0ac1a91..710302ddf8 100644 --- a/final_project/router/general.js +++ b/final_project/router/general.js @@ -4,40 +4,100 @@ let isValid = require("./auth_users.js").isValid; let users = require("./auth_users.js").users; const public_users = express.Router(); - +// Task 6 +// Register New user public_users.post("/register", (req,res) => { //Write your code here - return res.status(300).json({message: "Yet to be implemented"}); + const username = req.body.username; + const password = req.body.password; + + // Check if both username and password are provided + if (username && password) { + // Check if the user does not already exist + if (!isValid(username)) { + // Add the new user to the users array + users.push({"username": username, "password": password}); + return res.status(200).json({message: "User <<" + (username) + ">> successfully registered. Now you can login"}); + } else { + return res.status(404).json({message: "User <<" + (username) + ">> already exists!"}); + } + } + // Return error if username or password is missing + return res.status(404).json({message: "Unable to register user."}); }); -// 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"}); +// Task 1 +// Get the book list available in the shop +public_users.get('/',async function (req, res) { + try { + const bookList = await getBooks(); + res.json(bookList); // Neatly format JSON output + } catch (error) { + console.error(error); + res.status(500).json({ message: "Error retrieving book list" }); + } }); -// Get book details based on ISBN +// Task 10 +// Get all books – Using async callback function +const getBooks = () => { + return new Promise((resolve, reject) => { + resolve(books); + }); +}; + +// Task 2 +// Get the books 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"}); - }); - -// Get book details based on author + getByISBN(req.params.isbn) + .then( + result => res.send(result), + error => res.status(error.status).json({message: error.message}) + ); +}); + +// Task 11 +// Search by ISBN – Using Promises +const getByISBN = (isbn) => { + return new Promise((resolve, reject) => { + let isbnNum = parseInt(isbn); + if (books[isbnNum]) { + resolve(books[isbnNum]); + } else { + reject({ status: 404, message: `ISBN ${isbn} not found` }); + } + }); +}; + +// Task 3 & Task 12 +// Get all books by Author | Search by 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; + getBooks() + .then((bookEntries) => Object.values(bookEntries)) + .then((books) => books.filter((book) => book.author === author)) + .then((filteredBooks) => res.send(filteredBooks)); }); -// Get all books based on title +// Task 4 & Task 13 +// Get all books based on Title | Search by 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; + getBooks() + .then((bookEntries) => Object.values(bookEntries)) + .then((books) => books.filter((book) => book.title === title)) + .then((filteredBooks) => res.send(filteredBooks)); }); -// Get book review +// Task 5 +// 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; + getByISBN(req.params.isbn) + .then( + result => res.send(result.reviews), + error => res.status(error.status).json({message: error.message}) + ); }); module.exports.general = public_users; From 2fb828a117ee5b7edff9b348f2e9650b36ab99b8 Mon Sep 17 00:00:00 2001 From: Lalo Date: Wed, 14 May 2025 15:44:03 -0700 Subject: [PATCH 3/3] Update index.js Final Project --- final_project/index.js | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/final_project/index.js b/final_project/index.js index b890c1d380..5096e316b5 100644 --- a/final_project/index.js +++ b/final_project/index.js @@ -11,7 +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 + //Write the authenication mechanism here + // Check if user is logged in and has valid access token + if (req.session.authorization) { + let token = req.session.authorization['accessToken']; + + // Verify JWT token + jwt.verify(token, "access", (err, user) => { + if (!err) { + req.user = user; + next(); // Proceed to the next middleware + } else { + return res.status(403).json({ message: "User not authenticated" }); + } + }); + } else { + return res.status(403).json({ message: "User not logged in " + (req.body.username) + " / aut:" + (req.session.authorization) }); + } }); const PORT =5000; @@ -19,4 +35,4 @@ const PORT =5000; app.use("/customer", customer_routes); app.use("/", genl_routes); -app.listen(PORT,()=>console.log("Server is running")); +app.listen(PORT,()=>console.log("Server is running on port " + (PORT) + " and is ready to accept requests!"));