Skip to content

Express book reviews project #309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions final_project/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,20 @@ app.use("/customer",session({secret:"fingerprint_customer",resave: true, saveUni

app.use("/customer/auth/*", function auth(req,res,next){
//Write the authenication mechanism here
const token = req.session.token; // Retrieve token from session

if (!token) {
return res.status(403).json({ message: "Access Denied. No token provided." });
}

jwt.verify(token, secretKey, (err, decoded) => {
if (err) {
return res.status(401).json({ message: "Invalid token." });
}
req.user = decoded; // Attach user info to request
next();

});
});

const PORT =5000;
Expand All @@ -20,3 +34,4 @@ 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"));
89 changes: 85 additions & 4 deletions final_project/router/auth_users.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,108 @@ const jwt = require('jsonwebtoken');
let books = require("./booksdb.js");
const regd_users = express.Router();

let users = [];
// let users = [];
let users=[
{
username:"admin",
password:"1234"
}
];

const isValid = (username)=>{ //returns boolean
//write code to check is the username is valid
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.
return users.some((user)=>user.username===username && user.password===password);

}

//only registered users can login
regd_users.post("/login", (req,res) => {
regd_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 required"});
}

if(isValid(username)){
console.log("not valid");
return res.status(409).json({message:"user already found"});
}
// if(!authenticatedUser(username,password)){
// console.log("In valid");

// return res.status(401).json({message:"Invalid Credentials"});
// }
users.push({username,password});

return res.status(200).json({message: "user registered successfully"});
});
regd_users.post("/login", (req, res) => {
const { username, password } = req.body;

if (!username || !password) {
return res.status(400).json({ message: "Username and password required." });
}

if (!isValid(username)) {
return res.status(404).json({ message: "User not found." });
}

if (!authenticatedUser(username, password)) {
return res.status(401).json({ message: "Invalid credentials." });
}

// ✅ Generate JWT token
const token = jwt.sign({ username }, "secret_key", { expiresIn: "1h" });

return res.status(200).json({ message: "Login successful.", token });
});

// Add 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.query;
const username=req.session.username;
if (!review) {
return res.status(400).json({ message: "Review is required" });
}

// Check if the user has already reviewed this ISBN
const existingReviewIndex = books.reviews.findIndex(r => r.isbn === isbn && r.username === username);

if (existingReviewIndex !== -1) {
// Modify the existing review
books.reviews[existingReviewIndex].review = review;
return res.status(200).json({ message: "Review updated successfully" });
} else {
// Add a new review
books. reviews.push({ isbn, username, review });
return res.status(201).json({ message: "Review added successfully" });
}
});
// if(!username){
// return res.status(401).json({message:"Unauthorized. Please log in first."});
// }
// if(!books[isbn]){
// return res.status(404).json({message:"Book not found"});
// }
// if(!review){
// return res.status(404).json({message:"Review cannot be empty"});

// }
// if(!books[isbn].reviews){
// books[isbn].reviews={};
// }
// books[isbn].reviews[username]=review;
// return res.status(300).json({message: "Review added/updated successfully",book:books[isbn]});
// });

module.exports.authenticated = regd_users;
module.exports.isValid = isValid;
Expand Down
100 changes: 89 additions & 11 deletions final_project/router/general.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,117 @@ let users = require("./auth_users.js").users;
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"});
});
// public_users.post("/register", (req,res) => {
// //Write your code here
// return res.status(300).json({message: "Yet to be implemented"});
// });

// Get the book list available in the shop
public_users.get('/',function (req, res) {
return res.json({message: "All Books"},books);
// res.send(b00ks);
//Write your code here
return res.status(300).json({message: "Yet to be implemented"});
// res.send(JSON.stringify(books));
// return res.status(300).json({message: "All Books"});this gives error as already res.send there
});
public_users.get('/books',async (req,res)=>{
try{
res.json({books});
}
catch(error){
return res.status(500).json({message: "Error Fetching books",error});

}
})

// Get book details based on ISBN
public_users.get('/isbn/:isbn',function (req, res) {
try{
const isbn=req.params.isbn;
if(!books[isbn]){
return res.status(404).json({message:"not Found with Isbn"})
}
const bookDetails={...books[isbn],isbn};

// const filtered_book=books.filter((book)=>book.isbn===isbn);filter only for arrays
//Write your code here
return res.status(300).json({message: "Yet to be implemented"});
return res.json({message: `book with isbn ${isbn}`,book:books[isbn]});
}
catch(error){
console.log("Error",error);
return res.status(500).json({message:"Internal Error"});
}
});

// Async
public_users.get('/books/isbn/:isbn',async (req,res) => {
const isbn=req.params.isbn;
try{

if (!books[isbn]) {
return res.status(404).json({ message: "Not Found with ISBN" });
}
const bookDetails=await new Promise((resolve)=>{
resolve({...books[isbn],isbn});
});
return res.status(200).json({ message: `Book with ISBN ${isbn}`, book: bookDetails });
}
catch(error){
return res.status(500).json({ message: "Internal Error" });

}

})
// 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;
const bookByAuthor=Object.values(books).filter((book)=>book.author===author);
return res.status(300).json({message: "book by author",book:bookByAuthor});
});
// Async
public_users.get('/books/author/:author',async (req, res)=> {
//Write your code here
try{
const author=req.params.author;
const bookByAuthor=await new Promise((resolve)=>{
resolve(Object.values(books).filter((book)=>book.author===author))
});
return res.status(300).json({message: "book by author",book:bookByAuthor});
}
catch(error){
return res.status(500).json({ message: "Internal Error" });

}
});
// 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;
const bookbyTitle=Object.values(books).filter((book)=>book.title===title);
return res.status(300).json({message: "book by author",book:bookbyTitle});
});
// Async
public_users.get('/books/title/:title',async (req, res) =>{
//Write your code here
try{
const title=req.params.title;
const bookbyTitle=await new Promise((resolve)=>{
resolve(Object.values(books).filter((book)=>book.title===title))});
return res.status(300).json({message: "book by author",book:bookbyTitle});
}
catch(error){
return res.status(500).json({ message: "Internal Error" });

}
});

// 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 bookByReviews=books[isbn].reviews;
// return res.status(300).json({message: "Book Reviews by isbn",book:bookByReviews});
return res.status(300).json({message: "book by author",reviews:bookByReviews});

});

module.exports.general = public_users;