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

Fist commit #1

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
32 changes: 26 additions & 6 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ var passport = require("passport");
var auth = require("./controllers/auth");
var store = require("./controllers/store");
var User = require("./models/user");
var book=require("./models/book");
var localStrategy = require("passport-local");
const dbURI ="mongodb+srv://pratapadityasingh2703:[email protected]/library?retryWrites=true&w=majority"
//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;
Expand All @@ -21,12 +23,18 @@ app.use(
})
);


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.deserializeUser(User.deserializeUser()); // used to deserialize the user

passport.serializeUser(function(user, done) {
done(null, user);
});

passport.deserializeUser(function(user, done) {
done(null, user);
});
app.use(express.urlencoded({ extended: true })); //parses incoming url encoded data from forms to json objects
app.set("view engine", "ejs");

Expand All @@ -37,7 +45,18 @@ app.use(function (req, res, next) {
});

/* TODO: CONNECT MONGOOSE WITH OUR MONGO DB */

setTimeout(() => {
mongoose.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('Connected to the database!');
})
.catch((err) => {
console.error('Error connecting to the database:', err);
});
}, 5000);
app.get("/", (req, res) => {
res.render("index", { title: "Library" });
});
Expand All @@ -48,15 +67,16 @@ If you need to add any new route add it here and define its controller
controllers folder.
*/

app.get("/books", store.getAllBooks);

app.get("/books" , store.getAllBooks);

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

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

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

Expand Down
51 changes: 51 additions & 0 deletions controllers/auth.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,72 @@
const passport = require("passport");
const user=require("../models/user")


var getLogin = (req, res) => {
//TODO: render login page
res.render("login",{title:"login"})
};

var postLogin = (req, res) => {
const newuser= new user({
USERNAME:req.body.username,
PASSWORD:req.body.password

})

passport.authenticate("local", function (err, user, info) {
if (err) {
console.log(err);
return res.redirect("/login");
}

if (!user) {

return res.render("login", {title:"Login"})
}

req.login(user, function (err) {
if (err) {
console.log(err);
} else {
res.redirect("/")
}
});
})(req, res);




// TODO: authenticate using passport
//On successful authentication, redirect to next page
};

var logout = (req, res) => {
req.logout();
res.redirect("/");


// TODO: write code to logout user and redirect back to the page
};

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

var postRegister = (req, res) => {
user.register({username:req.body.username}, req.body.password, function(err, user){
if(err){
console.log(err);
res.redirect("/getRegister");
}
else{
passport.authenticate("local")(req,res,function(){
res.redirect("/login");
})
}
})

// TODO: Register user to User db using passport
//On successful authentication, redirect to next page
};
Expand Down
77 changes: 76 additions & 1 deletion controllers/store.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,100 @@
const user = require("../models/user");
const book=require("../models/book")
const bookCopy=require("../models/bookCopy")

var getAllBooks = (req, res) => {
book.find()
.then((foundbooks)=>{
res.render("book_list", { books: foundbooks , title:"Book_list" });

})
.catch((err)=>{
console.log(err)
})


//TODO: access all books from the book model and render book list page
res.render("book_list", { books: [], title: "Books | Library" });

}

var getBook = (req, res) => {
const foundbookid=req.params.id

book.findByID(foundbookid)
.then((bookfound)=>{
res.render("book_detail",{
book:bookfound,
num_available:bookfound.available_copies


})
})
.catch((err)=>{
console.log(err);
})

//TODO: access the book with a given id and render book detail page
}

var getLoanedBooks = (req, res) => {
bookCopy.find({borrower:req.user})
.populate("book")
.exec(function(err, loanedBooks){
if(err){
console.log(err);
} else{
res.render("loaned_books",{books:loanedBooks, title:"Borrowed Books"})
}
})


//TODO: access the books loaned for this user and render loaned books page
}

var issueBook = (req, res) => {
const requestedbookid=req.body.bid;
book.findByID(requestedbookid)
.then((foundbook)=>{
if(foundbook.available_copies!==0){
res.send("Book_issued")
foundbook.available_copies=foundbook.available_copies-1;
foundbook.save();
}
else{
res.send("No copies available")
}
})
.catch((err)=>{
console.log(err)

})








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

var searchBooks = (req, res) => {

title=req.body.title;
genre=req.body.genre;
author=req.body.author;
book.find({title:title, genre:genre, author:author})
.then((foundbooks)=>{
res.render("book_list", {title:"Book Results",books:foundbooks })
})
.catch((err)=>{
console.log(err);
})


// TODO: extract search details
// query book model on these details
// render page with the above details
Expand Down
7 changes: 7 additions & 0 deletions middleware/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,17 @@ var middlewareObj={};
//middleware object to check if logged in
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()){
return next();
}
else{
return res.redirect("/login");
}
}

module.exports=middlewareObj;
12 changes: 12 additions & 0 deletions models/book.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
var mongoose=require("mongoose");
//DEFINING THE BOOK MODEL


var bookSchema=new mongoose.Schema({
title:String,
genre:String,
author:String,
rating:{
type:Number,
max:5,
min:1
},
mrp:Number,
available_copies:Number
/*TODO: DEFINE the following attributes-
title, genre, author, description, rating (out of 5), mrp, available_copies(instances).
*/
Expand Down
20 changes: 16 additions & 4 deletions models/bookCopy.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,22 @@
var mongoose=require("mongoose");
const user = require("./user");
const book = require("./book");
//DEFINING THE BOOK COPIES MODEL
var bookCopySchema=new mongoose.Schema({
//TODO: DEFINE the following attributes-
book: //embed reference to id of book of which its a copy
status: //TRUE IF AVAILABLE TO BE ISSUED, ELSE FALSE
borrow_data: //date when book was borrowed
borrower: //embed reference to id of user who has borrowed it
book: [{
type:mongoose.Schema.Types.ObjectId,
ref:"Book"
}], //embed reference to id of book of which its a copy
status: Boolean,//TRUE IF AVAILABLE TO BE ISSUED, ELSE FALSE
borrow_data: Date,//date when book was borrowed
borrower: [{
type:mongoose.Schema.Types.ObjectId,
ref: "User"

}


]//embed reference to id of user who has borrowed it
})
module.exports=mongoose.model("Bookcopy",bookCopySchema);
7 changes: 7 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
var mongoose=require("mongoose");
var passportLocal=require("passport-local-mongoose");
const book = require("./book");
//DEFINING THE USER MODEL
var userSchema=new mongoose.Schema({
USERNAME:String,
PASSWORD:String,

//TODO: DEFINE USERNAME AND PASSSWORD ATTRIBUTES


loaned_books:[
{
type:mongoose.Schema.Types.ObjectId,
ref:"Book"
}
//TODO: embed reference to id's of book copies loaned by this particular user in this array
]
})
Expand Down
Loading