如何在Express.JS中使用Passport.js实现基于角色的用户身份验证?

时间:2020-07-10 18:05:20

标签: express authentication passport-local

我正在使用Express.js构建一个项目,并使用Passport.JS进行身份验证。我可以为Passport.JS中的单一类型的用户执行用户身份验证。但是,我无法对两种类型的用户(普通用户和admin)进行此身份验证。在调用自定义路由之前,我尝试使用要映射的角色对象,但没有正确理解如何实现此目的(而且它不起作用)。希望能为您解决此问题提供帮助。这是我的auth.js文件:

我的auth.js文件:

module.exports = {
  ensureAuthenticated: function(req, res, next) {
    if (req.isAuthenticated()) {
      return next();
    }
    req.flash('error_msg', 'Please log in to view that resource');
    res.redirect('/users/login');
  },
  forwardAuthenticated: function(req, res, next) {
    if (!req.isAuthenticated()) {
      return next();
    }
     
    res.redirect('/dashboard');      
  }
};

我的Passport.JS文件:

const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcryptjs');

// Load User model
const User = require('../models/User');



module.exports = function(passport) {
  passport.use(
    new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
      // Match user
      User.findOne({
        email: email
      }).then(user => {
        if (!user) {
          return done(null, false, { message: 'That email is not registered' });
        }

        // Match password
        bcrypt.compare(password, user.password, (err, isMatch) => {
          if (err) throw err;
          if (isMatch) {
            return done(null, user);
          } else {
            return done(null, false, { message: 'Password incorrect' });
          }
        });
      });
    })
  );
  passport.serializeUser(function(user, done) {
    done(null, user.id);
  });
  passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
      done(err, user);
    });
  });
};

完整代码的链接位于:https://github.com/Temybroder/sealedapp

0 个答案:

没有答案