Skip to content

Final Project #340

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
20 changes: 18 additions & 2 deletions final_project/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,28 @@ 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;

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!"));
66 changes: 52 additions & 14 deletions final_project/router/auth_users.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
100 changes: 80 additions & 20 deletions final_project/router/general.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;