如何使用nodejs实现基于角色的身份验证?

时间:2019-09-23 17:48:17

标签: node.js ajax mongodb express

基本上,我想让nodeJS检查通过登录页面登录的用户是否是管理员,如果不是,则应将其发送给管理员页面;如果不是,则应将其发送给其他页面。

我目前只有一个登录页面是静态的,我有两个HTML页面,每个页面都有大量的jquery控制器,因此当我考虑重写所有这些视图或做出反应时,我意识到这将花费我很多有时间完成它,我尝试了许多解决方案,但是要么我只能让身份验证部分起作用,而没有授权,要么反之。

我有一个简单的登录表单,我想要实现的功能类似于获取表单数据并通过ajax发送,然后控制器将首先对用户进行身份验证,然后检查用户的角色(如果是) admin应该sendfile('index.html')如果fm应该sendfile('req.html')我已经写了每个页面以便能够执行某些功能,并且每个页面都与六个不同的对象通信API,因此我至少现在不需要任何新角色和特权定义

2 个答案:

答案 0 :(得分:1)

好吧,因为没有人愿意回答,所以我为有兴趣学习基于会话的身份验证并且不想被成千上万的框架和库所淹没的初学者写了一篇文章。 https://medium.com/@ahmedcheikhsidahmed/authentication-with-nodejs-expressjs-the-simple-way-945939878e16

答案 1 :(得分:1)

我所做的只是向我的用户架构输入了一个角色,该角色从1到4运行,我将默认设置设置为4(代表一个普通用户)和1-3(针对不同的管理员级别),这是代码,它可能会帮助某人有一天

用户架构:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const UserSchema = new Schema({
  email: {
    type: String,
    required: true
  },

  password: {
    type: String,
    required: true
  },
  role:{
    type: Number,
    default : 4,
  },

  date: {
    type: Date,
    default: Date.now
  },
});

module.exports = User = mongoose.model('users', UserSchema);

这是用户注册路线

// @route   POST api/users/register
// @desc    Register user
// @access  Public
router.post('/register', (req, res) => {
  const { errors, isValid } = validateRegisterInput(req.body);

  // Check Validation 
  if (!isValid) {
    return res.status(400).json(errors);
  }

  User.find().sort({unitNo : -1}).then(user => {
        const newUser = new User(
      {
        email: req.body.email,
        password: req.body.password,
        });
     bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;

            newUser 
             .save()
              .then(user => res.json(user))
              .catch(err => console.log(err));
        });
      });

  });
});

这是用户登录名

// @route   GET api/users/login
// @desc    Login User / Returning JWT Token
// @access  Public
router.post('/login', (req, res) => {
  const { errors, isValid } = validateLoginInput(req.body);

  // Check Validation
  if (!isValid) {
    return res.status(400).json(errors);
  }

  const email = req.body.email;
  const password = req.body.password;

  // Find user by email
  User.findOne({ email }).then(user => {
    // Check Password
    bcrypt.compare(password, user.password).then(isMatch => {
      if (isMatch) {
        // User Matched
        const payload = { id: user.id, name: user.name  }; // Create JWT Payload

        // Sign Token
        jwt.sign(
          payload,
          keys.secretOrKey,
          { expiresIn: 20000600 },
          (err, token) => {
            res.json({
              success: true,
              token: 'Bearer ' + token
            });
          }
        );
      } else {
        errors.password = 'Password incorrect';
        return res.status(400).json(errors);
      }
    });
  });
});

但是对于管理员来说,角色的范围是1-3,这是登录的样子

// @route   Post api/admins/login
// @desc    Login User / Returning JWT Token
// @access  Public
router.post('/login', (req, res) => {
  const { errors, isValid } = validateLoginInput(req.body);

  // Check Validation
  if (!isValid) {
    return res.status(400).json(errors);
  }

  const email = req.body.email;
  const password = req.body.password;

  // Find user by email
  User.findOne({ email }).then(user => {
    // Check for Admin
    if (!user) {
      errors.email = 'User not found';
      return res.status(404).json(errors);
    }
    // Check to see if level meet admin role(Her is where i check if it is the admin or the user)
    if(user.role == 4){
      errors.role = 'You are not allowed to view this page'
      return res.status(404).json(errors);
    }

    // Check Password
    bcrypt.compare(password, user.password).then(isMatch => {
      if (isMatch) {
        // User Matched
        const payload = { id: user.id, name: user.name }; // Create JWT Payload

        // Sign Token
        jwt.sign(
          payload,
          keys.secretOrKey,
          { expiresIn: "7h" },
          (err, token) => {
            res.json({
              success: true,
              token: 'Bearer ' + token
            });
          }
        );
      } else {
        errors.password = 'Password incorrect';
        return res.status(400).json(errors);
      }
    });
  });
});

我希望这有一天能解决某人的问题...