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 CSOC #9

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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*


config.env
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

Expand Down
24 changes: 19 additions & 5 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ var auth = require("./controllers/auth");
var store = require("./controllers/store");
var User = require("./models/user");
var localStrategy = require("passport-local");
var dotenv=require('dotenv')
//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;

dotenv.config( { path : 'config.env'} )

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

Expand All @@ -33,10 +35,20 @@ app.set("view engine", "ejs");
//THIS MIDDLEWARE ALLOWS US TO ACCESS THE LOGGED IN USER AS currentUser in all views
app.use(function (req, res, next) {
res.locals.currentUser = req.user;
// console.log(currentUser);
next();
});

/* TODO: CONNECT MONGOOSE WITH OUR MONGO DB */
mongoose.connect(process.env.URL,{

useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
})
.then(()=>{console.log("connected");
})

app.get("/", (req, res) => {
res.render("index", { title: "Library" });
Expand All @@ -52,16 +64,18 @@ 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);

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

app.post("/books/return", middleware.isLoggedIn,store.returnBook);

/* TODO: WRITE VIEW TO RETURN AN ISSUED BOOK YOURSELF */

/*-----------------AUTH ROUTES
Expand All @@ -80,6 +94,6 @@ app.post("/register", auth.postRegister);

app.get("/logout", auth.logout);

app.listen(port, () => {
console.log(`App listening on port ${port}!`);
app.listen(process.env.PORT || 3000, () => {
console.log(`App listening on port ${process.env.PORT || 3000}!`);
});
24 changes: 20 additions & 4 deletions controllers/auth.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,39 @@
var passport = require('passport');
var Account = require('../models/user');

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

var postLogin = (req, res) => {
// TODO: authenticate using passport
//On successful authentication, redirect to next page
};
var postLogin = passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
})

var logout = (req, res) => {
// TODO: write code to logout user and redirect back to the page
req.logOut()
res.redirect('/');
};

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

var postRegister = (req, res) => {
// TODO: Register user to User db using passport
//On successful authentication, redirect to next page
Account.register(new Account({ username : req.body.username }), req.body.password, function(err, account) {
if (err) {
res.send("Choose a different username");
}
passport.authenticate('local')(req, res, function () {
res.redirect('/');
});
});

};

module.exports = {
Expand Down
148 changes: 142 additions & 6 deletions controllers/store.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,170 @@
var getAllBooks = (req, res) => {
const book = require('../models/book.js')
const bookcopy= require('../models/bookCopy.js')


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

// const newbook=new book({
// title: "African Folktales",
// genre:"westerns",
// author:"Lorem Ipsum",
// description:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Blanditiis, dolorem!",
// rating:3,
// mrp:1000
// })
// await newbook.save()
// const newbook1=new book({
// title: "African Folktales",
// genre:"thrillers",
// author:"Roger D. Abrahams",
// description:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Aspernatur, deleniti.",
// rating:2,
// mrp:2000
// })
// await newbook1.save()
// const newbook2=new book({
// title: "Oral Epics from Africa",
// genre:"poetry",
// author:"John William Johnson",
// description:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur similique nulla ipsam.",
// rating:5,
// mrp:699
// })
// await newbook2.save()
// const newbook3=new book({
// title: "Land Apart: A South African Reader",
// genre:" horror",
// author:"J. M. Coetzee",
// description:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Aspernatur, deleniti.",
// rating:4,
// mrp:420
// })
// await newbook3.save()
// const newbook4=new book({
// title: "Love Child",
// genre:"Romance",
// author:"Baby Diana",
// description:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur similique nulla ipsam.",
// rating:1,
// mrp:657
// })
// await newbook4.save()


// const books=await book.find({})
// books.forEach(async(book) => {
// for(let i=0;i<7;i++){
// const newcopy= new bookcopy({
// book: book._id,
// status:true,
// })
// await newcopy.save();
// }
// })
// const bookcop=await bookcopy.find({});
// console.log(bookcop[0]);
// const ji=await bookcop[0].populate("book").execPopulate();
// console.log(bookcop[0].populated("book"));
// console.log(ji);
// const copies= await bookcopy.find({})
// copies.forEach(async(copy)=>{
// const parent=await book.where("_id").equals(copy.book)
// parent[0].instances.push(copy._id);
// await parent[0].save()
// })
const allbook =await book.find({});
res.render("book_list",{title: "Books", books:allbook});
}

var getBook = (req, res) => {
var getBook = async(req, res) => {
//TODO: access the book with a given id and render book detail page
var cnt=0;
const bookdetail=await book.where("_id").equals(req.params.id);
var bookpopulated=await bookdetail[0].populate("instances").execPopulate();
bookpopulated.instances.forEach((copy)=>{
if(copy.status)
cnt++;
})
res.render("book_detail",{book: bookdetail[0],num_available: cnt ,title :"BOOK"})
}

var getLoanedBooks = (req, res) => {
var getLoanedBooks = async(req, res) => {

//TODO: access the books loaned for this user and render loaned books page
var in_loaned=await req.user.populate("loaned_books")
.execPopulate()
var full_loaned=await in_loaned.populate("loaned_books.book")
.execPopulate();
res.render("loaned_books",{books:full_loaned.loaned_books, title:"Loaned Books"})
}

var issueBook = (req, res) => {
var issueBook = async(req, res) => {

// TODO: Extract necessary book details from request
// return with appropriate status
// Optionally redirect to page or display on same
const bookdetail=await book.where("_id").equals(req.body.bid);
var bookpopulated=await bookdetail[0].populate("instances").execPopulate();
for (copy of bookpopulated.instances){
if(copy.status)
{
var book_instance=await bookcopy.where("_id").equals(copy._id);
book_instance[0].status=false;
book_instance[0].borrower=req.user._id;
await book_instance[0].save();
req.user.loaned_books.push(copy._id);
await req.user.save();
break;
}
}
res.redirect('/');
}

var searchBooks = (req, res) => {
var searchBooks = async(req, res) => {
// TODO: extract search details
// query book model on these details
// render page with the above details
var result=[]
const allbook =await book.find({});
allbook.forEach(test => {
if((test.title).includes(req.body.title))
{
if((test.genre).includes(req.body.genre))
{
if((test.author).includes(req.body.author))
result.push(test)
else
return;
}
else
return;
}
else
return;
})
res.render("book_list",{title: "Books", books:result})
}

var returnBook =async (req, res) => {

var book =await bookcopy.where("_id").equals(req.body.bid)
book[0].status=true;
book[0].borrower=undefined;
book[0].borrow_date=undefined;
await book[0].save();
var index = req.user.loaned_books.indexOf(req.body.bid);
req.user.loaned_books.splice(index, 1);
await req.user.save();
res.redirect("/");
}


module.exports = {
getAllBooks,
getBook,
getLoanedBooks,
returnBook,
issueBook,
searchBooks
}
10 changes: 8 additions & 2 deletions middleware/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ middlewareObj.isLoggedIn=function(req,res,next){
If user is logged in: Redirect to next page
else, redirect to login page
*/
}
if (req.isAuthenticated()) {
return next()
}

res.redirect('/login')
}

module.exports=middlewareObj;

module.exports=middlewareObj;
29 changes: 29 additions & 0 deletions models/book.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,34 @@ var bookSchema=new mongoose.Schema({
/*TODO: DEFINE the following attributes-
title, genre, author, description, rating (out of 5), mrp, available_copies(instances).
*/
title: {
type : String,
default : ""
},
genre: {
type: String,
default: ""
},
author: {
type: String,
default: ""
},
description: {
type: String,
default: ""
},
rating: {
type: Number,
default: ""
},
mrp: {
type: Number,
default: ""
},
instances: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Bookcopy",
default: ""
}],
})
module.exports=mongoose.model("Book",bookSchema);
17 changes: 13 additions & 4 deletions models/bookCopy.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,18 @@ var mongoose=require("mongoose");
//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"
},
status: Boolean,
borrow_date: {
type: Date,
default: ()=>new Date()
},
borrower: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
})
module.exports=mongoose.model("Bookcopy",bookCopySchema);
11 changes: 6 additions & 5 deletions models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ var passportLocal=require("passport-local-mongoose");
var userSchema=new mongoose.Schema({

//TODO: DEFINE USERNAME AND PASSSWORD ATTRIBUTES


loaned_books:[
//TODO: embed reference to id's of book copies loaned by this particular user in this array
]
username: String,
password: String,
loaned_books:[{
type: mongoose.Schema.Types.ObjectId,
ref: "Bookcopy"
}]
})
userSchema.plugin(passportLocal);
module.exports=mongoose.model("User",userSchema);
Loading