Skip to content
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

Done #204

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open

Done #204

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
19 changes: 17 additions & 2 deletions final_project/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +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

if (req.session.authorization) {
token = req.session.authorization['accessToken'];
jwt.verify(token, "access", (err, user) => {
if (!err) {
req.user = user;
next();
} else {
return res.status(403).json({message: "User not authenticated"});
}
});
} else {
return res.status(403).json({message: "User not logged in"});
}
});


const PORT =5000;

Expand Down
103 changes: 88 additions & 15 deletions final_project/router/auth_users.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,103 @@
const express = require('express');
const jwt = require('jsonwebtoken');
const express = require("express");
const jwt = require("jsonwebtoken");
let books = require("./booksdb.js");
const regd_users = express.Router();
//let users = [];
let users = [{"username":"Sai","password":"test"}];

let users = [];
const isValid = (username) => {
//returns boolean
//write code to check if username is already present in records.
//return users[username] !== undefined;
let userswithsamename = users.filter((user)=>{
return user.username === username
});
if(userswithsamename.length > 0){
return true;
} else {
return false;
}
}


const isValid = (username)=>{ //returns boolean
//write code to check is the username is valid
}
const authenticatedUser = (username,password) => {
//returns boolean
//write code to check if username and password are present in records.
let validusers = users.filter((user)=>{
return (user.username === username && user.password === password)
});
if(validusers.length > 0){
return true;
} else {
return false;
}
//write code to check if username and password match the one we have in records.
}

//only registered users can login
regd_users.post("/login", (req,res) => {
//Write your code here
//const username = req.body.username;
const username = req.body.username;
const password = req.body.password;

const authenticatedUser = (username,password)=>{ //returns boolean
//write code to check if username and password match the one we have in records.
if (!username || !password) {
return res.status(404).json({message: "Error logging in"});
}

//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"});
if (authenticatedUser(username,password)) {
let accessToken = jwt.sign({
data: password
}, 'access', { expiresIn: 60 * 60 });
// }, 'access', { expiresIn: 60 });

req.session.authorization = {
accessToken,username
}
return res.status(200).send("User successfully logged in");
}
else {
return res.status(208).json({message: "Invalid Login. Check username and password"});
}
//return res.status(300).json({message: "Yet to be implemented"});
});


// 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"});
regd_users.put("/auth/review/:isbn", async(req, res) => {

const username = req.session.authorization.username

const isbn = req.params.isbn;
let filtered_book = books[isbn]
if (filtered_book) {
let review = req.query.review;
let reviewer = req.session.authorization['username'];
if(review) {
filtered_book['reviews'][reviewer] = review;
books[isbn] = await filtered_book;
}
res.send(`The review for the book with ISBN ${isbn} has been added/updated.`);
} else{
res.send("Unable to find this ISBN!");
}

});

regd_users.delete("/auth/review/:isbn", async (req, res) => {
//*Write your code here

const isbn = req.params.isbn
const username = req.session.authorization.username
if (books[isbn]) {
let book = await 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;
199 changes: 171 additions & 28 deletions final_project/router/general.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,186 @@
const express = require('express');
const express = require("express");
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 doesExist = (username)=>{
let userswithsamename = users.filter((user)=>{
return user.username === username
});
if(userswithsamename.length > 0){
return true;
} else {
return false;
}
}

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) => {
//public_users.post("/login", (req, res) => {
//Write your code here
const username = req.body.username;
const password = req.body.password;

if (username && password) {
if (!doesExist(username)) {
users.push({"username":username,"password":password});
return res.status(200).json({message: "User" +username+ "successfully registred. Now you can login"});
} else {
return res.status(404).json({message: "User" +username+ " already exists!"});
}
}
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"});
});

// Get the book list available in the shop
public_users.get("/", function (req, res) {
//Write your code here
//return res.status(200).json({ message: "Book list:", books: books });
res.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"});
});

// 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"});
public_users.get("/isbn/:isbn",function (req, res) {
//Write your code here
const isbn = req.params.isbn;
res.send(books[isbn])
//res.send(JSON.stringify({isbn},null,4));
});

// Get book details based on author
public_users.get("/author/:author", function (req, res) {
//Write your code here
/* const author = req.params.author;
// res.send(books[author])
var filtered_book;
let i = 1;
while(books[i]){
if (books[i]["author"]===author) {
filtered_book = books[i];
break;
}
i++;
}
res.send(filtered_book)
});*/

let ans = []
for(const [key, values] of Object.entries(books)){
const book = Object.entries(values);
for(let i = 0; i < book.length ; i++){
if(book[i][0] == 'author' && book[i][1] == req.params.author){
ans.push(books[key]);
}
}
}
if(ans.length == 0){
return res.status(300).json({message: "Author not found"});
}
res.send(ans);
});


// 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"});
public_users.get("/title/:title", function (req, res) {
//Write your code here
/* const review = req.params.isbn;
var filtered_book;
let i = 1;
while(books[i]){
if (books[i]["isbn"]===review) {
filtered_book = books[i];
break;
}
i++;
}
res.send(filtered_book)
});*/
let ans = []
for(const [key, values] of Object.entries(books)){
const book = Object.entries(values);
for(let i = 0; i < book.length ; i++){
if(book[i][0] == 'title' && book[i][1] == req.params.title){
ans.push(books[key]);
}
}
}
if(ans.length == 0){
return res.status(300).json({message: "Title not found"});
}
res.send(ans);
});

// 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"});
});

module.exports.general = public_users;
public_users.get('/review/:isbn',function (req, res) {
//Write your code here
const ISBN = req.params.isbn;
res.send(books[ISBN].reviews)
});

// Task 10
// Add the code for getting the list of books available in the shop (done in Task 1) using Promise callbacks or async-await with Axios

function getBookList(){
return new Promise((resolve,reject)=>{
resolve(books);
})
}

// Get all books – Using async callback function
function getAllBooks() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(books);
}, 2000);

return;
});
}

// Search by ISBN – Using Promises
function getBookByISBN(isbn) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const book = books[isbn];
if (!book) {
reject("Book not found");
}
resolve(book);
}, 2000);
});
}

// Search by author – Using async callback function
function getBookByAuthor(author) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const booksByAuthor = [];
for (const key in books) {
if (books[key].author === author) {
booksByAuthor.push(books[key]);
}
}
if (booksByAuthor.length === 0) {
reject("Book not found");
}
resolve(booksByAuthor);
}, 2000);
});
}

// Search by title – Using async callback function
function getBookByTitle(title) {
return new Promise((resolve, reject) => {
setTimeout(() => {
for (const key in books) {
if (books[key].title === title) {
resolve(books[key]);
}
}
reject("Book not found");
}, 2000);
});
}

module.exports.general = public_users;