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

2023-12-07

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

Codes

控制器/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');
}

护照.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);
      });

  }));
};

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

})

您的回调将在 (err,user,info) 中收到 将最终请求发送为 返回完成(空,假,用户) 现在检查 req.isAuthenticated

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 MEAN Stack 环境中使用 Passport.js 验证路由 的相关文章

随机推荐