UnhandledPromiseRejectionWarning MongoTimeoutError - javascript

I am trying to run my app.js locally on my editor, It works in the editor when I try to run it on a browser it loads the first page when I click on a link to enter the site, I get an error UnhandledPromiseRejectionWarning MongoTimeoutError server selection timed out after 30000 ms. I am new at this, this is actually part of a course through udemy. I have searched on google, reddit threads etc. Can't seem to figure this out. Please don't laugh if this is a dumb question. If you need more code let me know I will provide it.
Thanks
here is my app.js
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
flash = require("connect-flash"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
methodOverride = require("method-override"),
Campground = require("./models/campground"),
Comment = require("./models/comment"),
User = require("./models/user")
// seedDB = require("./seeds")
// mongoose.Promise = global.Promise
//requiring routes
var commentRoutes = require("./routes/comments"),
campgroundRoutes = require("./routes/campgrounds"),
indexRoutes = require("./routes/index")
mongoose.connect("mongodb://localhost/yelp_camp_", {
useNewUrlParser: true,
useUnifiedTopology: true,
})
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(methodOverride("_method"));
app.use(flash());
//seedDB(); //seed the database
//PASSPORT CONFIGURATION
app.use(require("express-session")({
secret: "Bodybuilding is fun",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function(req, res, next){
res.locals.currentUser = req.user;
res.locals.error = req.flash("error")
res.locals.success = req.flash("success")
next();
});
app.use("/", indexRoutes);
app.use("/campgrounds", campgroundRoutes);
app.use("/campgrounds/:id/comments", commentRoutes);
app.listen(3000, function (){
console.log('The YelpCamp Server Has Started');
});
Campgrounds.js
var express = require("express");
var router = express.Router();
var Campground = require("../models/campground");
var middleware = require("../middleware");
//INDEX - show all campgrounds
router.get("/", function(req, res){
// Get all campgrounds from DB
Campground.find({}, function(err, allCampgrounds){
if(err){
console.log(err);
} else {
res.render("campgrounds/index",{campgrounds:allCampgrounds});
}
});
});
//CREATE - add new campground to DB
router.post("/", middleware.isLoggedIn, function(req, res){
// get data from form and add to campgrounds array
var name = req.body.name;
var price = req.body.price;
var image = req.body.image;
var desc = req.body.description;
var author = {
id: req.user._id,
username: req.user.username
}
var newCampground = {name: name, price: price, image: image, description: desc, author:author}
// Create a new campground and save to DB
Campground.create(newCampground, function(err, newlyCreated){
if(err){
console.log(err);
} else {
//redirect back to campgrounds page
console.log(newlyCreated);
res.redirect("/campgrounds");
}
});
});
//NEW - show form to create new campground
router.get("/new", middleware.isLoggedIn, function(req, res){
res.render("campgrounds/new");
});
// SHOW - shows more info about one campground
router.get("/:id", function(req, res){
//find the campground with provided ID
Campground.findById(req.params.id).populate("comments").exec(function(err, foundCampground){
if(err || !foundCampground){
req.flash("error", "Campground not found");
res.redirect("back");
} else {
console.log(foundCampground);
//render show template with that campground
res.render("campgrounds/show", {campground: foundCampground});
}
});
});
//EDIT CAMPGROUND ROUTE
router.get("/:id/edit", middleware.checkCampgroundOwnership, function(req, res){
Campground.findById(req.params.id, function(err, foundCampground){
res.render("campgrounds/edit", {campground: foundCampground});
});
});
//UPDATE CAMPGROUND ROUTE
router.put("/:id", middleware.checkCampgroundOwnership, function(req, res){
//find and update the correct campground
Campground.findByIdAndUpdate(req.params.id, req.body.campground, function(err, updatedCampground){
if(err){
res.redirect("/campgrounds");
} else {
res.redirect("/campgrounds/" + req.params.id);
}
});
//redirect somewhere(show page)
});
//DESTROY CAMPGROUND ROUTE
router.delete("/:id", middleware.checkCampgroundOwnership, function(req, res){
Campground.findByIdAndRemove(req.params.id, function(err){
if(err){
res.redirect("/campgrounds");
} else
res.redirect("/campgrounds");
});
});
//middleware
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/login");
}
module.exports = router;

Related

Passportjs Local authetication is not working properly

After implementing using passport-local not able to open profile page
I'm getting this below error
This page isn’t workinglocalhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
passport-local-strategy.js
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const User = require('../models/user');
passport.use(new LocalStrategy({
usernameField: 'email'
},
function(email, password, done){
User.findOne({email: email}, function(err, user){
if(err){
console.log('Error in finding user --> Passport');
return done(err);
}
if(!user || user.password!=password){
console.log("Invalid username/password");
return done(null, false);
}
return done(null, user);
});
}
));
// serialize user function
passport.serializeUser(function(user, done){
done(null, user.id);
});
//deserialize the user fn
passport.deserializeUser(function(id, done){
User.findById(id, function(err, user){
if(err){
console.log("Error in finding user --> passport");
return done(err);
}
return done(null, user);
});
});
// check if user is authenticated
passport.checkAuthenticated = function(req, res, next){
if(req.isAuthenticated()){
return next();
}
// if the user is not signed in
return res.redirect('/users/sign-in');
}
passport.setAuthenticatedUser = function(req, res, next){
if(req.isAuthenticated()){
// req.user contains current signed in user data from the login page
res.locals.user = req.user;
}
next();
}
module.exports = passport;
users_controller.js
const User = require('../models/user')
module.exports.profile = function(req, res){
if(req.cookies.user_id){
User.findById(req.cookies.user_id, function(err, user){
if(user){
return res.render('profile',{
title:"Profile",
user:user
});
}
else{
return res.redirect('/users/sign-in')
}
})
}
else{
return res.redirect('/users/sign-in');
}
}
// render the sign up and in page
module.exports.signUp = function(req, res){
if(req.isAuthenticated()){
return res.redirect('/users/profile')
}
return res.render('user_sign_up', {
title: "Codeial | Sign Up"
})
}
module.exports.signIn = function(req, res){
if(req.isAuthenticated()){
return res.redirect('/users/profile')
}
return res.render('user_sign_in', {
title: "Codeial | Sign In"
})
}
// get the sign up data
module.exports.create = function(req, res){
if(req.body.password != req.body.confirm_password){
return res.redirect('back')
}
User.findOne({email:req.body.email}, function(err, user){
if(err){console.log('error in finding user in signing up'); return;}
if(!user){
User.create(req.body, function(err, user){
if(err){console.log('error in finding user in signing up'); return;}
return res.redirect('/users/sign-in')
})
}
else{
return res.redirect('back')
}
})
}
module.exports.createSession = function(req, res){
return res.redirect('/');
}
users.js
const express = require('express')
const router = express.Router();
const passport = require('passport');
const usersController = require('../controllers/users_controller');
router.get('/profile',passport.checkAuthenticated,usersController.profile)
router.get('/sign-up', usersController.signUp);
router.get('/sign-in', usersController.signIn);
// in above all codes after get('/sign-up') means when we type the keyword sign-up in the browser we need to render the folllowing page which is userController.signUp
// we are using users_controller.js file by importing
router.post('/create', usersController.create);
router.post('/create-session',passport.authenticate(
'local',
{failureRedirect: '/users/sign-in'},
),usersController.createSession);
// above line post create-session is forms action in user_sign_in.ejs file - when we submit the data of the form the post method is invoked
module.exports = router;
mongoose.js
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/codeial_development')
const db = mongoose.connection;
db.on('error', console.error.bind(console, "Error connecting to MongoDb"));
db.once('open', function(){
console.log('connected to the database :: MongoDB ')
})
module.exports = db;
index.js
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const port = 8000;
const expressLayouts = require('express-ejs-layouts');
const db = require('./config/mongoose')
const session = require('express-session');
const passport = require('passport');
const passportLocal = require('./config/passport-local-strategy')
const MongoStore = require('connect-mongodb-session')(session)
app.use(express.urlencoded());
/* is a method inbuilt in express to recognize the incoming
Request Object as strings or arrays. This method is called as a
middleware in your application using the code*/
app.use(cookieParser());
app.use(express.static('./assets'));
app.use(expressLayouts);
// extact style and scripts from subpages into the layout
app.set('layout extractStyles', true)
app.set('layout extractScripts', true)
app.set('view engine', 'ejs');
app.set('views','./views')
app.use(session({
name: 'codeial',
secret:'blahsomeone',
saveUninitialized:false,
resave:false,
cookie:{
maxAge: (1000 * 60 * 100)
},
store: new MongoStore({
// mongooseConnection:db
mongoUrl: db._connectionString,
autoRemove: 'disabled'
}, function(err){
console.log(err || 'connect-mongo setup ok')
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.setAuthenticatedUser);
// use express router
app.use('/', require('./routes'));
app.listen(port, function(err){
if(err){console.log(`Error running the server: ${err}`)};
console.log(`Server is running on port: ${port}`);
})
I'm not able to view profile page, its redirecting or getting this error
This page isn’t workinglocalhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS

how to make a page only accessible when logged in with express & ejs

Currently I'm working on a little project for a dummy login/register page and now I want to add a page that is only accessible when you're logged in. So the question is how do I make a session or cookie and retrieve them? And how do I block not logged in users.
I'm currently using this code for the app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var expressSession = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var AuthTokenStrategy = require('passport-auth-token').Strategy;
require('./models');
var User = mongoose.model('User')
mongoose.connect('mongodb://localhost:27017/my-data', { useNewUrlParser: true, useUnifiedTopology: true })
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
passport.use(new LocalStrategy({
usernameField: "key"
}, function(key, next) {
User.findOne({
key: key
}, function(err, user) {
if (err) return next(err);
if (!user) {
return next({message: 'Key incorrect'})
}
next(null, user);
})
}));
passport.serializeUser(function (user, next) {
next(null, user._id)
})
passport.deserializeUser(function (id, next){
User.findById(id, function (err, user) {
next(err, user);
});
});
app.use(passport.initialize());
app.use(passport.session());
app.use(expressSession({
secret: 'aksndklajsdjicpwoemcklnaiohdandascopkqpowdmklasmdiojqwndjkasndosiqjwdklnasaksndklajsdjicpwoemcklnaiohdandascopkqpowdmklasmdiojqwndjkasndosiqjwdklnas'
}))
app.get('/', function(req, res, next){
res.render('index', {title: 'MySite'})
});
app.get('/main', function(req, res, next){
res.render('main')
});
app.get('/login', function(req, res, next){
res.render('login')
});
app.post('/signup', function(req, res, next){
User.findOne({
key: req.body.key
}, function (err, user) {
if (err) return next(err)
if (user) return next({message: 'This client exists'})
let newUser = new User({
key: req.body.key
});
newUser.save(function(err) {
if (err) return next(err);
res.redirect('/main');
});
console.log(req.body)
});
});
app.post('/login', async (req, res, next) => {
const key = req.body.key;
//const ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
//console.log(ip);
if (!key) return res.status(401).json({ err: 'Key not provided' });
const User = mongoose.model('User');
const user = await User.findOne({ key }).exec();
if (!user) return res.status(401).json({ err: 'Invalid Key' });
res.redirect('/main');
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Try do add this middleware to protected route:
function isAuthenticated(req,res,next){
if(req.isAuthenticated()){ // will return true if user is logged in
next();
} else{
res.redirect("/login");
}
}
app.get('/protectedPath',isAuthenticated, function(req,res) {
//protected content
);

Cannot read property 'totalQty' of undefined

I've created a cart object, which can store the products in a cart. The problem is before an item is put into the cart it is undefined. How do I make the cart defined even when nothing is in it during the session? I'm using ejs.
Here is my Error
/home/ubuntu/workspace/views/partials/header.ejs:37
35| </li>
36| <li>
>> 37| <a href="cart" class="navport"><span
class="badge"><%= session.cart.totalQty || 0%></span></a>
38| </li>
39| </ul>
40|
Cannot read property 'totalQty' of undefined
App.js
var express = require("express");
var app = express();
var mongoose = require("mongoose"),
User = require("./models/user"),
bodyParser = require("body-parser"),
ejs = require("ejs"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
localMongoose = require("passport-local-mongoose"),
session = require("express-session"),
MongoStore = require("connect-mongo")(session),
Cart = require("./models/cart"),
Clothes = require("./models/clothes");
mongoose.connect("mongodb://localhost/bitchinvintage");
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
secret: "random dogga",
resave: false,
saveUninitialized: false,
store: new MongoStore({mongooseConnection: mongoose.connection}),
cookie: {maxAge: 180 * 60 * 1000}
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function (req, res, next) {
res.locals.login = req.isAuthenticated();
res.locals.session = req.session;
next();
});
app.get("/", function(req, res){
res.render("landing");
});
// Clothes Routes
app.get("/clothes", function(req, res){
// Get all campgrounds from DB
Clothes.find({}, function(err, clothes){
if(err){
console.log(err);
} else {
res.render("clothes",{clothes:clothes});
}
});
});
app.get("/clothes/new", function(req, res){
res.render("new");
});
app.post("/clothes", function(req, res){
var name = req.body.name;
var overlay = req.body.overlay;
var price = req.body.price;
var image = req.body.image;
var newClothes = {name: name, image: image, price: price, overlay: overlay}
Clothes.create(newClothes, function(err, newlyCreated){
if(err){
console.log(err);
} else{
res.redirect("/clothes");
}
});
});
// ------------------
// Register Routes
app.get("/register", function(req, res){
res.render("register");
});
app.post("/register", function(req, res){
var newUser = new User({username: req.body.username});
User.register(newUser, req.body.password, function(err, user){
if (err){
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function(){
res.redirect("/");
})
})
});
// -----------
// Login Routes
app.post("/login", passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/register"
}), function(req, req){
});
// Cart Routes
app.get("/add-to-cart/:id", function(req, res, next){
var productId = req.params.id;
var cart = new Cart(req.session.cart ? req.session.cart : {});
console.log("works");
Clothes.findById(productId, function(err, clothes){
if(err){
return res.redirect("/");
}
cart.add(clothes, productId);
req.session.cart = cart;
console.log(req.session.cart);
res.redirect("/clothes");
});
});
// ------------
app.get("/account", isLoggedIn, function(req, res){
});
app.get("/*", function(req, res){
res.render("error");
});
app.listen(process.env.PORT, process.env.IP, function(){
console.log("Vintage server Starting...")
});
function isLoggedIn(req, res, next) {
if (req.user) {
next();
} else {
res.redirect("/account");
}
}
models/cart.js
This is the cart Object
module.exports = function Cart(oldCart) {
this.items = oldCart.items || {};
this.totalQty = oldCart.totalQty || 0;
this.totalPrice = oldCart.totalPrice || 0;
this.add = function(item, id) {
var storedItem = this.items[id];
if (!storedItem){
storedItem = this.items[id] = {item: item, qty: 0, price: 0}
}
storedItem.qty++;
storedItem.price = storedItem.item.price * storedItem.qty;
this.totalQty++;
this.totalPrice += storedItem.price;
}
this.generateArray = function() {
var arr = [];
for (var id in this.items) {
arr.push(this.items[id]);
}
return arr;
}
};
header.ejs
This is the HTML where I'm trying to list the total amount in the cart on the navbar
<li>
<a href="cart" class="navport"><span class="badge"><%=
session.cart.totalQty || 0%></span></a>
</li>
</ul>
var Cart = require('../models/cart');
(path for cart model)
did you include this line in your route ? because of that you are getting cart it is undefined error. please make sure that you have included above line in your route file. when you create a cart object this line will help you refer the cart model.
I've faced the same issue while loading the index template. Can you check if session.cart is available before rendering shopping-cart quantity? I added simple if condition like below and it worked for me.
<% if(session.cart) { %>
<span class="badge"><%= session.cart.totalQty %></span>
<% } %>

Node Route not working when issuing a GET request

Guys I'm going through a udemy class on Node and Express and I've gotten stuck. I'm implementing a route using a GET method ruest. The route has the form of "campgrounds/:id" however, there's a route above that has the name of "/campgrounds/new" which is submission form. here's the link to working web app.
and the webpage of working app
http://webdevcamp-miatech.c9users.io/campgrounds
when you click on any of the buttons "more info" it will redirect to "campgrounds/:id" for now I"m just testing the route and I'm printing some text.
app.js file
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose");
//connect mongoose db
mongoose.connect("mongodb://localhost/yelp_camp");
app.use(bodyParser.urlencoded({extended: true})); //parsing html request
app.set("view engine", "ejs"); //handling vies through ejs pages
//schema/model for data to be inserted in db
var campgroundSchema = new mongoose.Schema({
name: String,
image: String,
description: String
})
var Campground = mongoose.model("Campground", campgroundSchema);
Campground.create({
name: "Salmon Creek",
image: "https://farm6.staticflickr.com/5786/20607281024_5c7b3635cc.jpg",
description: "This is a huge granite hill, no bathroom campground"
}, function(err, campground) {
if(err) {
console.log(err);
}
else {
console.log("Created Campground");
console.log(campground);
}
})
//default route
app.get("/", function(req, res) {
res.render("landing");
})
app.get("/campgrounds", function(req, res) {
Campground.find({}, function(err, allCampgrounds) {
if(err) {
console.log(err);
}
else {
res.render("campgrounds", {campgrounds: allCampgrounds});
}
})
});
//method to add to database and redirect to campgrounds
app.post("/campgrounds", function(req, res) {
// res.send("you hit post route");
//get data from form and add to campgrounds array
var name = req.body.name;
var imgUrl = req.body.image;
var newCampGround = {name: name, image: imgUrl};
//adding to database table
Campground.create(newCampGround, function(err, newlyCreated) {
if(err) {
console.log(err);
}
else {
res.redirect("/campgrounds");
console.log(newlyCreated);
}
});
});
app.get("/campgrounds/new", function(req, res) {
res.render("new.ejs");
})
//displaying especific campground
app.get("campgrounds/:id", function(req, res) {
//find campground with id
// Campground.FindById(req.param)
// res.render("single.ejs");
res.send("This will be the single page!");
})
//starting server
app.listen(process.env.PORT, process.env.IP, function() {
console.log("server started!..");
});
Here's my project on c9.io
https://ide.c9.io/miatech/webdevcamp
missing slash before campgrounds
app.get("/campgrounds/:id", function(req, res) {
//find campground with id
// Campground.FindById(req.param)
// res.render("single.ejs");
res.send("This will be the single page!");
})

Login system using Passport.js is always executing “failureRedirect” (nodejs)

I'm doing a tutorial and I'm stuck in the login area. When I'm login in with Passport.js it always executing "failureRedirect" in authenticate.
After trying to debug replacing the router.post('login') route I received the following message:
Error: null User: false Info: {"message":"Missing credentials"}
After Reading on some forums I think that the problem could be related to body-parser. I've been trying to solve the problem but I haven't been able yet. I'd appreciate the help of a most experienced node.js programmer.
The structure of the project is:
app.js
routes:
users.js
models:
user.js
user.js
var express = require('express');
var router = express.Router();
var multer = require('multer');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var User = require('../models/user');
var upload = multer({ dest: './uploads' });
// create application/json parser
var jsonParser = bodyParser.json();
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/register', function(req, res, next) {
res.render('register', {
title: 'Register'
});
});
router.get('/login', function(req, res, next) {
res.render('login', {
'title': 'Login'
});
});
router.post('/register', upload.single('profileimage'), function (req, res, next) {
//Get Form Values
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
// Check for Image Field
if(req.files && req.files.profileimage){
console.log('Uploading File...');
// File Info
var profileImageOriginalName = req.files.profileimage.originalname;
var profileImageName = req.files.profileimage.name;
var profileImageMime = req.files.profileimage.mimetype;
var profileImagePath = req.files.profileimage.path;
var profileImageExt = req.files.profileimage.extension;
var profileImageSize = req.files.profileimage.size;
} else {
// Set a Default Image
var profileImageName = 'noimage.png';
}
// Form Validation
req.checkBody('name', 'Name field is required').notEmpty();
req.checkBody('email', 'Email field is required').notEmpty();
req.checkBody('email', 'Email not valid').isEmail();
req.checkBody('username', 'Username field is required').notEmpty();
req.checkBody('password', 'Password field is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);
// Check for errors
var errors = req.validationErrors();
if(errors){
res.render('register', {
errors: errors,
name: name,
email: email,
username: username,
password: password,
password2: password2
});
} else {
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileImage: profileImageName
});
// Create User
User.createUser(newUser, function (err, user) {
if(err) throw err;
console.log(user);
});
//Success Message
req.flash('success', 'You are now registered and may log in');
res.location('/');
res.redirect('/');
}
});
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy(
function (username, password, done) {
User.getUserByUsername(username, function (err, user) {
if(err) throw err;
if(!user){
console.log('Unknown User');
return done(null, false, {message: 'Unknown User'});
}
User.comparePassword(password, user.password, function (err, isMatch) {
if(err) throw err;
if(isMatch){
return done(null, user);
} else {
console.log('Invalid Password');
return done(null, false, {message:'Invalid Password'});
}
});
});
}
));
router.post('/login', jsonParser, passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/users/login',
failureFlash: true //'Invalid username or password'
}), function (req, res) {
console.log('Authentication Successful');
req.flash('success', 'You are logged in');
res.redirect('/');
});
router.post('/login', passport.authenticate('local', function(err, user, info) {
console.log("authenticate");
console.log(err);
console.log(user);
console.log(info);
}), function (req, res) {
console.log('Authentication Successful');
req.flash('success', 'You are logged in');
res.redirect('/');
});
module.exports = router;
user.js
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
mongoose.connect('mongodb://localhost/nodeauth');
var db = mongoose.connection;
// User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String,
required: true,
bcrypt: true
},
email: {
type: String
},
name:{
type: String
},
profileimage:{
type: String
}
});
var User = module.exports = mongoose.model('User', UserSchema);
module.exports.comparePassword = function(candidatePassowrd, hash, callback) {
bcrypt.compare(candidatePassowrd, hash, function (err, isMatch) {
if(err) return callback(err);
callback(null, isMatch);
});
}
module.exports.getUserById = function (id, callback) {
User.findById(id, callback);
}
module.exports.getUserByUsername = function (username, callback) {
var query = {username: username};
User.findOne(query, callback);
}
module.exports.createUser = function (newUser, callback) {
bcrypt.hash(newUser.password, 10, function (err, hash) {
if(err) throw err;
// Set hashed pw
newUser.password = hash;
// Create User
newUser.save(callback);
});
}
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Handle File Uploads
// app.use(multer({dest:'./uploads'}));
var upload = multer({ dest: './uploads' });
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Handle Express Sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport
app.use(passport.initialize());
app.use(passport.session());
// Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// app.use(expressValidator({
// errorFormatter
// }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Files on Dropbox:
https://www.dropbox.com/sh/ex26xxo85lfo0my/AADET-j6Ift0q-y-ecWCRUEba?dl=0
Thanks for your help :)
Please check the code here on https://github.com/rupalipemare/Mongoose-Demo, wherein there is complete example demonstrating passport authentication.
First.. Please try to modularize code. Putting a functionalities in different files can help you track bugs faster. Second why are there two POST calls to login route? Remove the first one and no need to send jsonParser. Yo have declared to serialize and deserialize user. So passport will handle rest.

Categories

Resources