Passport Local Strategy不会被称为NodeJS

时间:2016-05-11 19:55:32

标签: javascript node.js passport-local

我在NodeJS应用程序上实现本地护照时遇到了一些麻烦。我不明白我在这里做错了什么。我会在这里列出这个问题的重要代码

app.js

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());

users.js

var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user.js');

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) {
        console.log('Entered passport'); // This doesn't even happen
        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);
                }
                console.log('Invalid Password');
                return done(null, false, {
                    message: 'Invalid Password'
                });
            });
            return done(null, user);
        });
    }
));

router.post('/login', passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect: '/users/login',
    failureFlash: 'Invalid username or password'
}), function(req, res) {
    console.log("Authentication Successfull!");
    req.flash('success', 'You are logged in');
    res.redirect('/');
});

user.js (型号):

module.exports.getUserByUsername = function(username, callback) {
    var query = { username: username };
    User.findOne(query, callback);
}

module.exports.getUserById = function(id, callback) {
    User.findById(id, callback);
}

module.exports.comparePassword = function(candidatePassword, hash, callback) {
    bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
        if(err) return callback(err);
        callback(null, isMatch);
    });
}

我没有收到任何语法错误。在users.js中我想将消息记录到控制台,但它甚至没有到达那里。当我在那里输入一个带有console.log的函数时,登录时的post函数会被触发,但现在它似乎没有。它只是重新加载页面(看起来像它)。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

尝试在护照启动前挂载session中间件:

var session = require('express-session')

app.use(session({ secret: 'xxxxxxx' }));
app.use(passport.initialize());
app.use(passport.session());