PassportJS本地策略无法使用Withh MongoDB

时间:2017-06-25 00:16:45

标签: node.js mongodb express passport.js

我正在尝试使用PassportJS来处理用户身份验证,我无法让它运行我的数据库设置。

我正在使用没有 Mongoose的MongoDB ,我无法使LocalStrategy模块工作。

希望我的数据库查询不会太麻烦。

本地策略:

passport.use(new LocalStrategy(
function(username, password, done) {
//Fire up database
mongo.connect("mongodb://localhost:27017/formulas", function(e, db) {
  if (e) {return next(e);}
  var col = db.collection("users");
  //Do a database query to find a record by username
      col.findOne({"username": username}, function(err, user){
        if (err) { return done(err);}
        if(!user) {
          return done(null, false, { message: "Please check your log in credentials." });
        }
        //if it exists call done() object with user information
        bcrypt.compare(password, user.password, function(err, res){
          if (err) throw err;
          if (res == true) {
            return done(null, {username: username, password: password});
          } else {
            return done(null, false, { message: "Invalid password."});
          }
        });
      });
    });
  }));

我这样打电话给passport.authenticate()

router.post('/login',
passport.authenticate('local', {successRedirect:'/', failureRedirect:'/about',failureFlash: false}),
function(req, res){
  console.log(req.body);
  console.log(req.user);
  console.log("The user was logged");
});

SerializeUserdeserializeUser如下所示:

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

passport.deserializeUser(function(id, done) {
  mongo.connect("mongodb://localhost:27017/formulas", function(e, db){
  if (e) {return next(e);}
  var col = db.collection("users");
  col.findOne({"username": id}, function(err, user){
    done(err, {"username": id});
  });
});
});

当我打电话给app.post(/login)时,我直接被/about取消,并且没有任何内容记录到控制台,所以我不确定出了什么问题。

非常感谢有关修复内容或如何排除故障的建议。

1 个答案:

答案 0 :(得分:1)

首先,当你序列化用户对象时,在反序列化时也必须传递整个用户对象。 考虑下面的例子。

对于路线:

router.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
        if (err) { return next(err); }
        req.session.user = req.user;
        return res.redirect('/home');
    });
  })(req, res, next);
});

对于passport.js,将localstrategy和passport放在同一个文件夹中

var passport = require('passport'),
session = require('express-session');
var local = require('./localstrategy.js');
module.exports = function (app) {
  app.use(session({
    secret: 'Site visit',
    resave: true,
    saveUninitialized: true,
    cookie: { secure: false }
  }));
  app.use(passport.initialize());
  app.use(passport.session());
  passport.serializeUser(function(user, done){
    done(null, user);
 });
 passport.deserializeUser(function(user, done){
    done(null, user);
 });
 local();
};

对于本地策略:

'use strict';
var  passport = require('passport'),
local = require('passport-local').Strategy;
var user;
// path where the db.js is placed
var db = require('./../db.js');
var ObjectId = db.getObjectID();
var bcrypt = require('bcrypt');

module.exports = function(){
   passport.use(new local({
    usernameField : 'username',
    passwordField : 'password'
   }, function(username, password, done){
     var collection = db.getDb().collection('users');
     collection.findOne({
        username: username,
     }, function (err, result) {
        if(result == null){
            cb(null, false);
        }else {
          bcrypt.compare(password, result.password, function (err, passRes) {
              if (passRes == true) {
                user = user;
                done(err, user);
               }else{
                  done(null, false, { message : 'Invalid Password'});
               }    
            });
        }
    });
  }));
};