如何使用PassportJS根据用户角色进行重定向?

时间:2019-11-20 14:13:43

标签: node.js reactjs mongodb passport.js

我需要重定向3种类型的用户(基于单个用户模型架构)。如何在用户路由中的router.post()调用中做到这一点?我知道passport.authenticate接受某些参数,但是我想知道是否有任何办法可以根据用户类型(模式中的角色)进行多次重定向?非常感谢! 这是我为一种类型的用户执行的操作:

//////this is my passport.js file//////

const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
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);
    });
  });
};



/////////auth.js file/////////
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();
    }      
  }
};


//////users.js route bellow/////////
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const passport = require('passport');
// Load User model
const User = require('../models/User');
const { forwardAuthenticated } = require('../config/auth');
const mongoose = require('mongoose');
// Login Page
router.get('/login', forwardAuthenticated, (req, res) => res.render('login'));

// Register Page
router.get('/register', forwardAuthenticated, (req, res) => res.render('register'));

// Register
router.post('/register', (req, res) => {
  const { role, name, email, password, password2 } = req.body;
  let errors = [];

  if (!role || !name || !email || !password || !password2) {
    errors.push({ msg: 'Please enter all fields' });
  }

  if (password != password2) {
    errors.push({ msg: 'Passwords do not match' });
  }

  if (password.length < 6) {
    errors.push({ msg: 'Password must be at least 6 characters' });
  }

  if (errors.length > 0) {
    res.render('register', {
      errors,
      role,
      name,
      email,
      password,
      password2
    });
  } else {
    User.findOne({ email: email }).then(user => {
      if (user) {
        errors.push({ msg: 'Email already exists' });
        res.render('register', {
          errors,
          role: role,
          name,
          email,
          password,
          password2
        });
      } else {
        const newUser = new User({
          role,
          name,
          email,
          password
        });

        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err;
            newUser.password = hash;
            newUser
              .save()
              .then(user => {
                req.flash(
                  'success_msg',
                  'You are now registered and can log in'
                );
                res.redirect('/users/login');
              })
              .catch(err => console.log(err));
          });
        });
      }
    });
  }
});




 // Login
   router.post('/login', (req, res, next) => {
       passport.authenticate('local', {
        successRedirect: '/aboutus',
        failureRedirect: '/users/login',
        failureFlash: true
      })(req, res, next);
});



// Logout
router.get('/logout', (req, res) => {
  req.logout();
  req.flash('success_msg', 'You are logged out');
  res.redirect('/users/login');
});

module.exports = router;

1 个答案:

答案 0 :(得分:0)

我很确定你可以在发布后做这样的事情:

app.post('/login', (req, res) => {
    if (req.body.role === 'normalUser') {
        res.redirect('/normalUserPage')
    } else if (req.body.role === 'administrator') {
        res.redirect('/administratorPage');
    } else if (req.body.role === 'receptionist') {
        res.redirect('/receptionistPage');
    }
});

我很确定应该这样做,请确保在尝试之后出现这些条件 使用提供的电子邮件和密码登录。

您几乎需要为这三个用户设置一个条件,并根据用户类型将他们重定向到他们的特定页面。

另一种解决方案是使用提供的信息登录并显示相同的页面。但是,您可以根据用户的角色指定他们正在查看的内容。

示例:

如果用户类型是 admin,则公开一个 div,允许他们查看所有数据并具有编辑或删除的能力。

如果用户是正常的,暴露一个 div 允许他们只查看为他们指定的内容。例如只有姓名,没有任何其他信息。

如果用户是接待员,则公开一个 div,允许他们查看所有内容,但不能编辑任何信息。

我真的希望这对你有帮助。如果这对您有帮助,请告诉我。 如果它对您没有帮助,我可以尝试找出其他解决方案。

相关问题