我正在尝试使用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,并且控制台上没有任何记录,因此我不太确定出了什么问题。

非常感谢您提供有关修复问题或如何进行故障排除的建议。

最佳答案

首先,当您序列化用户对象时,然后在反序列化中,还必须传递整个用户对象。
考虑下面的示例。

路线:

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'});
               }
            });
        }
    });
  }));
};

关于node.js - PassportJS本地策略不适用于MongoDB,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44742061/

10-11 04:23