在MEAN Stack环境中使用passport.js验证路由

时间:2016-05-26 17:35:24

标签: javascript node.js session express passport.js

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

控制器/ 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

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

  }));
};

1 个答案:

答案 0 :(得分:0)

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

})

你的回叫将在这里收到(错误,用户,信息) 发送最终请求为 return done(null,false,user) 现在检查req.isAuthenticated