Skip to content
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
18 changes: 16 additions & 2 deletions final_project/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
72 changes: 61 additions & 11 deletions final_project/router/auth_users.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,74 @@ 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.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;
Expand Down
176 changes: 170 additions & 6 deletions final_project/router/general.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,205 @@ 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) => {
//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"});
// ✅ 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
return res.status(300).json({message: "Yet to be implemented"});
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
return res.status(300).json({message: "Yet to be implemented"});
const author = req.params.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
return res.status(300).json({message: "Yet to be implemented"});
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
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;