Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I am trying to use passport-local-mongoose to authenticate a user after submitting a POST on the /register form. I can't figure out why i always get "unauthorized" & oddly no data is submitted on the database (it works if i remove "passport.authenticate('local') from app.post("/register") )

any ideas?

app.js :

// ====== Dependencies 

var express = require('express'); 

 bodyParser = require('body-parser'); 

 validator = require('express-validator'); 

 cookieParser = require('cookie-parser'); 

 expressSession = require('express-session'); 

 passport = require('passport'); 

 LocalStrategy = require('passport-local').Strategy; 

 auth = require('./controllers/auth'); 

 registration = require('./controllers/register'); 

 User = require('./models/user'); 

// ====== Options 

 var app = express() 

 .use(bodyParser.urlencoded({ extended: false }))

 .use(bodyParser.json()) 

 .use(validator()) 

 .set('view engine','ejs')  

 .use(express.static("views")) 

 .use(cookieParser())  

 .use(expressSession({

 secret : 'soooosecret', 

 resave : true, saveUninitialized : false 

})) 

.use(passport.initialize()) 

.use(passport.session()); 

passport.use(new LocalStrategy(User.authenticate())); passport.serializeUser(User.serializeUser()); passport.deserializeUser(User.deserializeUser()); app.post('/register', passport.authenticate('local'), registration.reg ); 

app.listen(8080); 

console.log('Server running at 8080');

register.js :

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

var reg = function (req, res) { 

/* some form validation... */ 

var errors = req.validationErrors(); 

if (errors) { 

res.render("register" , { errors : errors } ); 

} else { 

var newUser = new User({ 

username : username, 

password : password, 

email : email, 

tel : tel, 

country : country 

}); 

User.createUser(newUser); 

module.exports = { reg : reg }

user.js :

var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/mvpem'); 

var passportLocalMongoose = require('passport-local-mongoose'); var db = mongoose.connection; 

var Schema = mongoose.Schema; 

var UserSchema = new Schema({ 

username : String, 

password : String, 

email : String, 

tel : Number, 

country : String 

}); 

UserSchema.plugin(passportLocalMongoose); 

module.exports = mongoose.model('User', UserSchema); module.exports.createUser = function(newUser) { 

newUser.save(); 

}

2 Answers

0 votes
by (106k points)

Authenticate user right after registration in mongoose your register.js should look like as follows:-

if (errors) { 

res.render("register" , { errors : errors } ); 

else { 

var newUser = new User({ 

username : username, 

email : email, 

tel : tel, 

country : country 

}); 

User.register(newUser, password, function(err, user) { 

if (errors) { 

// handle the error 

passport.authenticate("local")(req, res, function() { 

// redirect user or do whatever you want 

}); 

}); 

}

and don't forget to require passport in register.js

0 votes
by (107k points)

It looks like your passport config is not setup correctly.

You have to tell a passport how to handle success and failure in order to get it to log you in. Just you have to create a config.js file you will import in your main file:

var passport = require('passport')

  , LocalStrategy = require('passport-local').Strategy,

  , User = require('../models/user');

passport.use(new LocalStrategy(

  function(username, password, done) {

    User.findOne({ username: username }, function(err, user) {

      if (err) { return done(err); }

      if (!user) {

        return done(null, false, { message: 'Incorrect username.' });

      }

      if (!user.validPassword(password)) {

        return done(null, false, { message: 'Incorrect password.' });

      }

      return done(null, user);

    });

  }

));

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...