Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在平均堆栈环境中使用passport.js验证路由_Javascript_Node.js_Session_Express_Passport.js - Fatal编程技术网

Javascript 在平均堆栈环境中使用passport.js验证路由

Javascript 在平均堆栈环境中使用passport.js验证路由,javascript,node.js,session,express,passport.js,Javascript,Node.js,Session,Express,Passport.js,我无法使用passport.js保护adminpanel的各个路由 用户注册正在运行。即使我登录到面板,它也会成功重定向。但是req.isAuthenticate总是返回假值。因此,我无法访问管理面板内的路由 代码 controller/admin.js var express = require('express'), router = express.Router(), session=require('express-session'); module.exports = functio

我无法使用passport.js保护adminpanel的各个路由 用户注册正在运行。即使我登录到面板,它也会成功重定向。但是req.isAuthenticate总是返回假值。因此,我无法访问管理面板内的路由

代码 controller/admin.js

var express = require('express'),
router = express.Router(),
session=require('express-session');

module.exports = function (app) {
app.use('/', router);
};

var passport = require('passport');
var flash    = require('connect-flash'),

session = require('express-session');
router.use(session({ secret: 'ilovescotchscotchyscotchscotch' ,saveUninitialized: true, resave: true})); // session secret
router.use(passport.initialize());
router.use(passport.session()); // persistent login sessions
router.use(flash());

router.get('/expoadmin/', function(req, res) {
  // render the page and pass in any flash data if it exists
  res.render('expoadmin/login', { message: req.flash('loginMessage')});
});
// process the login form
router.post('/expoadmin/login', passport.authenticate('admin-login', {
  successRedirect : '/expoadmin/dashboard', // redirect to the secure profile section
  failureRedirect : '/expoadmin/', // redirect back to the signup page if there is an error
  failureFlash : true // allow flash messages
}));
router.get('/expoadmin/logout', function(req, res){
  console.log('logging out');
  req.logout();
  res.redirect('/expoadmin');
});
router.get('/expoadmin/addadmin', function(req, res) {

  // render the page and pass in any flash data if it exists
  res.render('expoadmin/signup', { message: req.flash('signupMessage') });
});

// process the signup form
router.post('/expoadmin/signup', passport.authenticate('admin-signup', {
  successRedirect : '/expoadmin/admins', // redirect to the secure profile section
  failureRedirect : '/expoadmin/addadmin', // redirect back to the signup page if there is an error
  failureFlash : true // allow flash messages
}));


var fetch =require('../adminroutes/eventsfetch.js');

router.get('/expoadmin/dashboard', isLoggedIn, 
function (req, res, next) {        res.render('expoadmin/index',{ layout : 'dashboard'}); });
router.get('/expoadmin/eventsfetch', isLoggedIn, fetch.view );

// route middleware to make sure
function isLoggedIn(req, res, next) {
var ses=req.session;
console.log(req.user);
console.log(session.user);
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
  return next();

// if they aren't redirect them to the home page
res.redirect('/expoadmin');
}
passport.js


})

您的回调将在此处接收(错误、用户、信息) 将最终请求发送为 返回完成(空、假、用户) 现在检查req.isAuthenticated

})

您的回调将在此处接收(错误、用户、信息) 将最终请求发送为 返回完成(空、假、用户)
现在检查请求是否已验证

我尝试了这个。但问题还是一样的。找不到用户。请提及您的返回回调语句……它必须是三个参数函数(req、电子邮件、密码、完成){Admin.findOne({'local.email':email},函数(err、User){console.log(User);if(err)返回完成(err);if(!User)返回完成(null,false,req.flash('loginMessage','No admin found.');if(!bcrypt.compareSync(password,user.local.password))返回完成(null,false,req.flash('loginMessage','Oops!error password.');返回完成(null,true,user);})我试过了。但还是同样的问题。找不到用户。请您提及您的返回回调语句……它必须是三个参数函数(req,email,password,done){Admin.findOne({'local.email':email},函数(err,User){console.log(User);if(err)return done(err);if(!user)返回完成(null,false,req.flash('loginMessage','No admin found');if(!bcrypt.compareSync(password,user.local.password))返回完成(null,false,req.flash('loginMessage','Oops!error password');返回完成(null,true,user);};}
// config/passport.js

// load all the things we need
var LocalStrategy   = require('passport-local').Strategy;

var bcrypt   = require('bcrypt-nodejs');

// load up the user model
var Admin            = require('../app/models/admin');

// expose this function to our app using module.exports
module.exports = function(passport) {

// =========================================================================
  // passport session setup ==================================================
  // =========================================================================
  // required for persistent login sessions
  // passport needs ability to serialize and unserialize users out of session

  // used to serialize the user for the session
  passport.serializeUser(function(user, done) {
      done(null, user._id);

  });

  // used to deserialize the user
  passport.deserializeUser(function(id, done) {
      User.findById(id, function(err, user) {
          done(err, user);
      });
  });
  // =========================================================================
  // Admin LOGIN =============================================================
  // =========================================================================
  // we are using named strategies since we have one for login and one for signup
  // by default, if there was no name, it would just be called 'local'

  passport.use('admin-login', new LocalStrategy({
      // by default, local strategy uses username and password, we will override with email
      usernameField : 'email',
      passwordField : 'password',
      passReqToCallback : true // allows us to pass back the entire request to the callback
  },
  function(req, email, password, done) { // callback with email and password from our form

      // find a user whose email is the same as the forms email
      // we are checking to see if the user trying to login already exists

      Admin.findOne({ 'local.email' :  email }, function(err, user) {
          // if there are any errors, return the error before anything else
          console.log(user);
          if (err)
              return done(err);
          // if no user is found, return the message
          if (!user)
              return done(null, false, req.flash('loginMessage', 'No admin found.')); // req.flash is the way to set flashdata using connect-flash

          // if the user is found but the password is wrong
          console.log(bcrypt.compareSync(password, user.local.password));
          if (!bcrypt.compareSync(password, user.local.password))
              return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
          console.log(user);
          // all is well, return successful user
          return done(null, user);
      });

  }));
};
router.post('/expoadmin/login',function(req,res,next){
passport.authenticate('admin-login', function (err, user, info) {

        if (err) {
     //send error message here
        }
        // Generate a JSON response reflecting authentication status
        if (!user) {
            //send if user not found
        }
        else{


        req.logIn(user, function (err,data) {
            if (err) {
            //some error with serialization
            }
            //do your stuff with info here
            res.redirect('/expoadmin/dashboard')
            });
        });
      }  
    })(req, res, next);