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

Week 4 All Tasks Done #10

Open
wants to merge 1 commit 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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,7 @@ dist
.yarn/install-state.gz
.pnp.*
{"mode":"full","isActive":false}

#env
.env
.env.test
37 changes: 29 additions & 8 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ var auth = require("./controllers/auth");
var store = require("./controllers/store");
var User = require("./models/user");
var localStrategy = require("passport-local");

//importing the middleware object to use its functions
var middleware = require("./middleware"); //no need of writing index.js as directory always calls index.js by default
var port = process.env.PORT || 3000;

app.use(express.static("public"));
app.use(express.static("favicon.ico"));

/* CONFIGURE WITH PASSPORT */
app.use(
Expand All @@ -20,11 +22,16 @@ app.use(
saveUninitialized: false,
})
);
passport.serializeUser(function (user, done) {
done(null, user);
});

passport.deserializeUser(function (user, done) {
done(null, user);
});
app.use(passport.initialize()); //middleware that initialises Passport.
app.use(passport.session());
passport.use(new localStrategy(User.authenticate())); //used to authenticate User model with passport
passport.serializeUser(User.serializeUser()); //used to serialize the user for the session
passport.use(new localStrategy(User.authenticate())); //used to authenticate User model with passportpassport.serializeUser(User.serializeUser()); //used to serialize the user for the session
passport.deserializeUser(User.deserializeUser()); // used to deserialize the user

app.use(express.urlencoded({ extended: true })); //parses incoming url encoded data from forms to json objects
Expand All @@ -37,6 +44,13 @@ app.use(function (req, res, next) {
});

/* TODO: CONNECT MONGOOSE WITH OUR MONGO DB */
const db = require("./config/keys").MONGOURL;
mongoose.set("useCreateIndex", true);
mongoose.set("useUnifiedTopology", true);
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("Database connected successfully"))
.catch((err) => console.log(err));

app.get("/", (req, res) => {
res.render("index", { title: "Library" });
Expand All @@ -52,13 +66,19 @@ app.get("/books", store.getAllBooks);

app.get("/book/:id", store.getBook);

app.get("/books/loaned",
//TODO: call a function from middleware object to check if logged in (use the middleware object imported)
store.getLoanedBooks);
app.get(
"/books/loaned",
//TODO: call a function from middleware object to check if logged in (use the middleware object imported)
middleware.isLoggedIn,
store.getLoanedBooks
);

app.post("/books/issue",
//TODO: call a function from middleware object to check if logged in (use the middleware object imported)
store.issueBook);
app.post(
"/books/issue",
//TODO: call a function from middleware object to check if logged in (use the middleware object imported)
middleware.isLoggedIn,
store.issueBook
);

app.post("/books/search-book", store.searchBooks);

Expand All @@ -69,6 +89,7 @@ TODO: Your task is to complete below controllers in controllers/auth.js
If you need to add any new route add it here and define its controller
controllers folder.
*/
app.post("/books/return", middleware.isLoggedIn, store.returnBook);

app.get("/login", auth.getLogin);

Expand Down
3 changes: 3 additions & 0 deletions config/keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
MONGOURL: "mongodb://localhost:27017",
};
44 changes: 43 additions & 1 deletion controllers/auth.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,65 @@
const { application } = require("express");
const passport = require("passport");
const Book = require("../models/book");
const User = require("../models/user");

var getLogin = (req, res) => {
//TODO: render login page
if (!req.isAuthenticated()) {
res.render("login", { title: "Login" });
} else {
res.status(200).redirect("/");
}
};

var postLogin = (req, res) => {
// TODO: authenticate using passport
//On successful authentication, redirect to next page
const user = new User({
username: req.body.username,
password: req.body.password,
});

req.login(user, function (err) {
if (err) {
res.status(500).render(`Error: ${err}`);
} else {
passport.authenticate("local")(req, res, function () {
res.status(200).redirect("/");
});
}
});
};

var logout = (req, res) => {
// TODO: write code to logout user and redirect back to the page
try {
req.logout();
res.status(200).redirect("/login");
} catch (err) {
res.status(500).send("Sorry, some error occurred!");
}
};

var getRegister = (req, res) => {
// TODO: render register page
// TODO: render register pages
res.status(200).render("register", { title: "Register" });
};

var postRegister = (req, res) => {
// TODO: Register user to User db using passport
//On successful authentication, redirect to next page
try {
User.register({ username: req.body.username }, req.body.password, (err) => {
if (!err) {
passport.authenticate("local")(req, res, () => {
res.status(200).redirect("/");
});
}
});
} catch (err) {
res.status(500).send("Internal Server Error");
}
};

module.exports = {
Expand Down
181 changes: 154 additions & 27 deletions controllers/store.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,161 @@
var getAllBooks = (req, res) => {
//TODO: access all books from the book model and render book list page
res.render("book_list", { books: [], title: "Books | Library" });
}
const Book = require("../models/book");
const User = require("../models/user");
const Bookcopy = require("../models/bookCopy");
const { default: mongoose } = require("mongoose");

var getBook = (req, res) => {
//TODO: access the book with a given id and render book detail page
}
var getAllBooks = async (req, res) => {
//TODO: access all books from the book model and render book list page
try {
const allBooks = await Book.find();
res
.status(200)
.render("book_list", { books: allBooks, title: "Library Books" });
} catch (err) {
res.status(500).render("Sorry, some error occurred!");
}
};

var getLoanedBooks = (req, res) => {
var getBook = async (req, res) => {
//TODO: access the book with a given id and render book detail page
const returnBookId = req.params.id;
try {
const book = await Book.findById(returnBookId);
if (book) {
res
.status(200)
.render("book_detail", { book: book, title: "Books | " + book.title });
} else res.status(404).send("No such book");
} catch (err) {
res.status(500).send("Sorry, some error occurred!");
}
};

//TODO: access the books loaned for this user and render loaned books page
}
var getLoanedBooks = (req, res) => {
//TODO: access the books loaned for this user and render loaned books page
User.findOne({ username: req.user.username }, function (err, user) {
if (!err) {
if (user) {
Bookcopy.find({ borrower: user._id })
.populate("book")
.populate("borrower")
.exec((err, userBooks) => {
if (!err) {
if (userBooks) {
res.status(200).render("loaned_books", {
books: userBooks,
title: "Books Loaned",
});
}
}
});
}
}
});
};

var issueBook = (req, res) => {

// TODO: Extract necessary book details from request
// return with appropriate status
// Optionally redirect to page or display on same
}

var searchBooks = (req, res) => {
// TODO: extract search details
// query book model on these details
// render page with the above details
}
// TODO: Extract necessary book details from request
// return with appropriate status
// Optionally redirect to page or display on same
Book.findOne({ _id: req.body.bid }, function (err, bookFound) {
if (!err) {
if (bookFound) {
if (bookFound.available_copies) {
var quantity = bookFound.available_copies - 1;
Book.updateOne(
{ _id: req.body.bid },
{ available_copies: quantity },
(err) => {
if (err) res.status(500).render(`Error: ${err}`);
}
);

let isAvailable = quantity ? true : false;
const issuedBook = new Bookcopy({
book: bookFound._id,
status: isAvailable,
borrower: req.user._id,
});
issuedBook.save();
User.findOneAndUpdate(
{ username: req.user.username },
{ $push: { loaned_books: issuedBook } },
{ safe: true, upsert: true, new: true },
(err, found) => {
if (err) res.status(500).render(`Error: ${err}`);
}
);

Bookcopy.update(
{ book: bookFound },
{ status: isAvailable },
(err) => {
res.status(500).render(`Error: ${err}`);
}
);
res.status(200).redirect("/books/loaned");
} else {
res.send("No copy of the book available to loan!");
}
}
}
});
};

var searchBooks = async (req, res) => {
// TODO: extract search details
// query book model on these details
// render page with the above details

const matchingBooks = await Book.find(
// { title: req.body.title, author: req.body.author, genre: req.body.genre },
{
title: { $regex: `.*${req.body.title}.*`, $options: "i" },
author: { $regex: `.*${req.body.author}.*`, $options: "i" },
genre: { $regex: `.*${req.body.genre}.*`, $options: "i" },
}
);

res.render("book_list", { books: matchingBooks });
};

var returnBook = (req, res) => {
const returnBookId = req.body.bid;

Book.findById(returnBookId).then((book) => {
if (book) {
new_available_copies = book.available_copies + 1;
Book.updateOne(
{ _id: returnBookId },
{ available_copies: new_available_copies },
(err) => {
if (err) res.status(500).render(`Error: ${err}`);
}
);
Bookcopy.findOneAndDelete({ book: book }).then((foundBook) => {
User.findOneAndUpdate(
{ username: req.user.username },
{ $pull: { loaned_books: foundBook._id } },
(err) => {
if (err) res.status(500).render(`Error: ${err}`);
}
);
});
Bookcopy.updateOne({ book: book }, { status: true }, (err) => {
res.status(500).render(`Error: ${err}`);
});
res.redirect("/books/loaned");
} else {
console.log("Sorry, some error occurred!");
}
});
};

module.exports = {
getAllBooks,
getBook,
getLoanedBooks,
issueBook,
searchBooks
}
getAllBooks,
getBook,
getLoanedBooks,
issueBook,
returnBook,
searchBooks,
};
15 changes: 10 additions & 5 deletions middleware/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
var middlewareObj={};
var middlewareObj = {};
//middleware object to check if logged in
middlewareObj.isLoggedIn=function(req,res,next){
/*
middlewareObj.isLoggedIn = function (req, res, next) {
/*
TODO: Write function to check if user is logged in.
If user is logged in: Redirect to next page
else, redirect to login page
*/
}
if (!req.isAuthenticated()) {
res.redirect("/login");
} else {
next(); //process function //check!
}
};

module.exports=middlewareObj;
module.exports = middlewareObj;
21 changes: 16 additions & 5 deletions models/book.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
var mongoose=require("mongoose");
var mongoose = require("mongoose");
//DEFINING THE BOOK MODEL
var bookSchema=new mongoose.Schema({
/*TODO: DEFINE the following attributes-
var bookSchema = new mongoose.Schema({
/*TODO: DEFINE the following attributes-
title, genre, author, description, rating (out of 5), mrp, available_copies(instances).
*/
})
module.exports=mongoose.model("Book",bookSchema);
title: String,
genre: String,
author: String,
description: String,
rating: {
type: Number,
min: 0,
max: 5,
},
mrp: Number,
available_copies: Number,
});
module.exports = mongoose.model("Book", bookSchema);
Loading