NodeJS: Passport authentication not working

user5499130 Source

I am using passport local for authentication and the login credentials don't get authenticated. I just get redirected to the failureRedirect. I don't even get the flash error.

Here is my login route:

var express = require('express');
var router = express.Router();
var passport = require('passport');
var flash = require('connect-flash');

router.get('/', function(req, res, next) {
  if(req.user){
    return res.redirect('/profile');
  }
  var vm = {
    title: 'Login',
    error: req.flash('error')
  };

  res.render('login', { title: 'Place an order' });
});

router.post('/', 
  passport.authenticate('local', {
    failureRedirect: '/login', 
    successRedirect: '/profile',
    failureFlash: 'Invalid credentials'
  }));

module.exports = router;

This is app.js:

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var expressSession = require('express-session');
var flash = require('connect-flash');

var config = require('./config');

var routes = require('./routes/index');
var signup = require('./routes/signup');
var login = require('./routes/login');
var profile = require('./routes/profile');

var restrict = require('./auth/restrict');
var passportConfig = require('./auth/passport-config');
passportConfig();

mongoose.connect(config.mongoUri);

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(expressSession({
    secret: 'themsec',
    saveUninitialized: false,
    resave: false
}));

app.use(flash());
app.use(passport.initialize());
app.use(passport.session());

app.use('/', routes);
app.use('/signup', signup);
app.use('/login', login);
//app.use(restrict);
app.use('/profile', profile);

// 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 handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

Passport-config:

module.exports = function(){
    var passport = require('passport');
    var passportLocal = require('passport-local');
    var userService = require('../services/user-service');

    passport.use(new passportLocal.Strategy({username: 'email'},function(email, password, next){
        userService.findUser(email, function(err, user){
            if(err){
                return next(err);
            }
            if(!user || user.password!= password){
                return next(null, null);
            }
            next(null, user);
        });
    }));

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

    passport.deserializeUser(function(email, next){
        userService.findUser(email, function(err, user){
            next(err, user);
        });
    });
};

User services:

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

exports.addUser = function(user, next){
    var newUser = new User({
        firstName: user.firstName,
        lastName: user.lastName,
        email:user.email.toLowerCase(),
        password: user.password,
    });
    newUser.save(function(err){
        if(err)
            return next(err)
        next(null);
    });
};

exports.findUser = function(email, next){
    User.findOne({email:email.toLowerCase()}, function(err, user){
        next(err, user)
    });
};

User model:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userService = require('../services/user-service');

var userSchema = new Schema({
    firstName: {type: String, required: true},
    lastName: String,
    email: {type: String, required: true},
    password: {type: String, required: true},
    created: {type: Date, default: Date.now}
});

userSchema.path('email').validate(function(value, next){
    userService.findUser(value, function(err, user){
        if(err){
            console.log(err);
            return false;
        }
        next(!user) 
    });
}, 'That email is already in use');

var User = mongoose.model('User', userSchema);

module.exports = {
    User:User
};

Someone please help me, I am turning mad with frustration. I am new to Node.

Edit: I have removed the code that would lead to an infinite loop if the user logged-in, however, I still cannot login.

node.jsexpresspassport.jspassport-local

Answers

comments powered by Disqus