创建一个中间件函数来检查用户角色是否等于“Admin”

Ald*_*vic 3 middleware mongodb node.js express

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

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

该路由受到保护,目前只有登录用户才能访问它。这是用于检查用户是否经过身份验证的中间件。

//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!'});
  }


};
Run Code Online (Sandbox Code Playgroud)

我应用这个中间件来保护对我的某些路由的未经授权的访问。我想创建一个类似的中间件,在其中检查用户是否是管理员。所以我可以在创建用户的路由上应用这个中间件,这样只有授权用户和具有“admin”角色的用户才能创建新用户。

我认为这有助于创建中间件。当用户登录时,id、电子邮件和角色存储在 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"
      });
    });
});
Run Code Online (Sandbox Code Playgroud)

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

gbr*_*ide 5

将路由处理程序添加到需要验证的所有端点,并在需要的地方导入它。 https://expressjs.com/en/guide/routing.html

前任。

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

//验证单独文件中的函数

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

完整代码示例:

https://medium.com/@maison.moa/using-jwt-json-web-tokens-to-authorize-users-and-protect-api-routes-3e04a1453c3e

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