创建一个中间件功能来检查用户角色是否等于“管理员" [英] Creating a middleware function to check if user role is equal to 'Admin'

查看:99
本文介绍了创建一个中间件功能来检查用户角色是否等于“管理员"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用最新的MEAN Stack技术创建博客.登录的用户可以创建一个具有管理员"和主持人"角色的新用户.

I'm creating a blog using the latest MEAN Stack technologies. A logged in user can create a new user with the roles 'admin' and 'moderator.

创建具有管理员角色或主持人角色的新用户

该路由受保护,目前只有登录用户可以访问.这是用于检查用户是否通过身份验证的中间件.

This route is protected and currently, only a logged in user can access it. Here is the middleware for checking if the user is authenticated or not.

//check_auth.js

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(' ')[1];
    jwt.verify(token,  'my_jwt_secret');
    next();
  } catch (error) {
    res.status(401).json({ message: 'Auth failed!'});
  }


};

我使用此中间件来保护对某些路线的未经授权的访问.我想创建一个类似的中间件,在其中检查用户是否是管理员.因此,我可以在创建用户的路径上应用此中间件,因此只有授权用户和具有"admin"角色的用户才能创建新用户.

I apply this middleware to protect unauthorized access to some of my routes. I want to create a similar middleware in which I check if the user is an administrator or not. So I can apply this middleware on the route for creating users, so only an authorized user and a user who has the role of 'admin' can create a new user.

我认为这可以帮助创建中间件.当用户登录ID时,电子邮件和角色将存储在jwt中.

I think this can help in creating the middleware. When a user logs in the id, email, and role is stored in the jwt.

router.post("/login", (req, res, next) => {
  let fetchedUser;
  User.findOne({ email: req.body.email })
    .then(user => {
      if (!user) {
        return res.status(401).json({
          message: "Auth failed"
        });
      }
      fetchedUser = user;
      return bcrypt.compare(req.body.password, user.password);
    })
    .then(result => {
      if (!result) {
        return res.status(401).json({
          message: "Auth failed"
        });
      }
      const token = jwt.sign(
        { email: fetchedUser.email, userId: fetchedUser._id, role: fetchedUser.role },
        "my_jwt_secret",
        { expiresIn: "1h" }
      );
      res.status(200).json({
        token: token,
        expiresIn: 3600
      });
    })
    .catch(err => {
      return res.status(401).json({
        message: "Auth failed"
      });
    });
});

可以在我的GitHub存储库中找到整个代码: https://github.com/rajotam/Eleven

The whole code can be found in my GitHub repository: https://github.com/rajotam/Eleven

推荐答案

向所有需​​要验证的端点添加路由处理程序,并在需要时将其导入. https://expressjs.com/en/guide/routing.html

Add a Route Handler to all endpoints that need verification and import it wherever needed. https://expressjs.com/en/guide/routing.html

例如.

router.post('/login', verify.isAdmin, (req, res, next) => {
    //do something
})

//验证功能在单独的文件中

//verify function in separate file

module.exports = {
    isAdmin: (req, res, next) =>{
        if(req.user.admin){
            next();
        }else{
            res.status(403).send();
        }
    }
}

完整代码示例:

https://medium .freecodecamp.org/securing-node-js-restful-apis-with-json-web-tokens-9f811a92bb52

这篇关于创建一个中间件功能来检查用户角色是否等于“管理员"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆