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

Made the Required Changes For Week 4 Express #8

Open
wants to merge 5 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
1 change: 1 addition & 0 deletions Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: node app.js
60 changes: 53 additions & 7 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,16 @@ var auth = require("./controllers/auth");
var store = require("./controllers/store");
var User = require("./models/user");
var localStrategy = require("passport-local");
const flash = require('connect-flash');
const session = require('express-session');
//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;
// var port = process.env.PORT || 3000;

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

// passport config
require('./config/passport')(passport)

/* CONFIGURE WITH PASSPORT */
app.use(
Expand All @@ -20,13 +25,14 @@ app.use(
saveUninitialized: false,
})
);

// Connect flash
app.use(flash());
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

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

Expand All @@ -37,11 +43,32 @@ app.use(function (req, res, next) {
});

/* TODO: CONNECT MONGOOSE WITH OUR MONGO DB */
// DB Config
const db = require('./config/keys').mongoURI;

// Connect to MongoDB
mongoose.connect(db,{ useNewUrlParser: true ,useUnifiedTopology: true})
.then(() => console.log('MongoDB Connected'))
.catch((err) => console.log('MongoDB Not Connected'));

// Express session
app.use(
session({
secret: 'secret',
resave: true,
saveUninitialized: true
})
);


app.get("/", (req, res) => {
res.render("index", { title: "Library" });
});

app.get("/errorPage", (req, res) => {
res.render("errorPage", { title: "Library" });
});

/*-----------------Store ROUTES
TODO: Your task is to complete below controllers in controllers/store.js
If you need to add any new route add it here and define its controller
Expand All @@ -53,15 +80,25 @@ 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)
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",
//TODO: call a function from middleware object to check if logged in (use the middleware object imported)
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-book", store.returnBooks);

// Global variables
app.use((req, res, next)=> {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});

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

/*-----------------AUTH ROUTES
Expand All @@ -78,8 +115,17 @@ app.get("/register", auth.getRegister);

app.post("/register", auth.postRegister);


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

// app.use('/', require('./routes/index.js'));
// app.use('/users', require('./routes/users.js'));

let port = process.env.PORT;
if (port == null || port == "") {
port = 3000;
}

app.listen(port, () => {
console.log(`App listening on port ${port}!`);
});
5 changes: 5 additions & 0 deletions config/keys.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
dbLink='mongodb+srv://Samar1110:[email protected]/?retryWrites=true&w=majority'

module.exports={
mongoURI : dbLink
}
32 changes: 32 additions & 0 deletions config/passport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const LocalStrategy = require('passport-local').Strategy;

// Load User model
const User = require('../models/user');

module.exports = function(passport) {
passport.use(
new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
// Match user
User.findOne({
email: email
}).then(user => {
if (!user) {
return done(null, false, { message: 'That email is not registered' });
}
if(password===user.password)return done(null, user);
else return done(null, false, { message: 'Password incorrect' });

});
})
);

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

passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
};
57 changes: 55 additions & 2 deletions controllers/auth.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,76 @@

var User = require("../models/user");
const passport = require('passport');

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

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

var logout = (req, res) => {
// TODO: write code to logout user and redirect back to the page
req.logout();
req.flash('success_msg', 'You are Succesfully logged out');
res.redirect('/login');
};

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

var postRegister = (req, res) => {
// TODO: Register user to User db using passport
//On successful authentication, redirect to next page
let errors = [];
const { username, email, password, password2 } = req.body;
console.log(req.body)

if (password != password2) {
errors.push({ msg: 'Both Passwords entered by you does not match' });
}
if(password.length<7){
errors.push({ msg: 'Password length must be greater than 7 characters' });
}


if (errors.length > 0) {
console.log(errors)
res.render('register', {errors,username,email,password,password2,title: "Library"});
// console.log('hello')

}
else {

User.findOne({email : email})
.then((user)=>{
if(user){
errors.push({msg:'This Email already exists, Please use another email to Register yourself in the Library' });
res.render('register',{errors,username,email,password,password2,title: "Library"});
console.log(errors)
}
else{
// console.log('bye')
const newUser = new User({username,email,password});
newUser.save()
.then(user => {req.flash('success_msg','You are now Successfully Registered in the Library and can Log in');
res.redirect('/login');
})
.catch(err => console.log(err));
}
})
}
};

module.exports = {
Expand Down
Loading