简体   繁体   English

创建可由 2 个角色 NodeJs 访问的路由的最佳实践是什么

[英]What is the best practice for creating a route that can be accessed by 2 roles NodeJs

Regarding best practice in creating routes in Node.Js Express.Js.关于在 Node.Js Express.Js 中创建路由的最佳实践。 For example, if I have 4 roles, namely headmaster, student and teacher, then I have a route called /sliders , which in the application these sliders can be seen by both teacher, student, and administrator only.例如,如果我有 4 个角色,即校长、学生和教师,那么我有一个名为/sliders的路由,在应用程序中,这些滑块只能由教师、学生和管理员看到。

When creating routes and middleware for checking roles, what are the best practices?在创建用于检查角色的路由和中间件时,最佳实践是什么?

I. Should I create 1 endpoints and 1 middleware that can be access by student and teacher only? I. 我应该创建 1 个端点和 1 个只能由学生和教师访问的中间件吗?

For example:例如:

v1.get('/sliders', isUserOrTeacher, controller.findAll)

and my middleware code:和我的中间件代码:

const isUserOrTeacher = (req, res, next) => {
  User.findById(req.payload.aud).exec((err, user) => {
    if (err) {
      res.status(500).send({ message: err })
      return
    }

    Role.find(
      {
        _id: { $in: user.roles }
      },
      (err, roles) => {
        if (err) {
          res.status(500).send({ message: err })
          return
        }

        for (let i = 0; i < roles.length; i++) {
          if (roles[i].name === 'student' || roles[i].name === 'teacher' || roles[i].name === 'admin') {
            next()
            return
          }
        }

        logger.error(req.method, req.originalUrl, '. Error isUserOrTeacher: ' + req.payload)
        return sendUnauthorized(res)
      }
    )
  })
}

II.二。 or i should make 2 different endpoint and 2 middleware或者我应该制作 2 个不同的端点和 2 个中间件

for example:例如:

v1.get('/user/sliders', isUser, controller.findAll)
v1.get('/teacher/sliders', isTeacher, controller.findAll)

III.三、 or can i make route like this??或者我可以做这样的路线吗?? And how the coding?以及如何编码? for middleware:对于中间件:

v1.get('/sliders', isUser, isTeacher, isAdmin, controller.findAll)

Which one is the best practice?哪一个是最佳实践?

There are three concerns that you should separate and not mix up:您应该分开而不是混淆三个问题:

  • which resource is accessed (the route)访问了哪个资源(路由)
  • which user is accessing the resource (authentication)哪个用户正在访问资源(身份验证)
  • which role does the user need to access the resource (authorisation)用户需要哪个角色才能访问资源(授权)

Consequently, you'd use different middlewares for this:因此,您将为此使用不同的中间件:

v1.get('/sliders', isAuthenticated, hasRole(['teacher', 'admin']), controller.findAll)

The isAuthenticated middleware would load the user object from the database or session store and store it on the request object (or throw if the client is not logged in). isAuthenticated中间件将从数据库或 session 存储加载用户 object 并将其存储在请求 object 上(如果客户端未登录,则抛出)。 The middleware created by hasRole would then check whether the user object has one of the given roles, or throw a "missing permission" error.然后,由hasRole创建的中间件将检查用户 object 是否具有给定角色之一,或者抛出“缺少权限”错误。 The controller would finally load and return the resource. controller 最终将加载并返回资源。
You can also make the role check part of the data provider (eg a database service) that the controller uses, so that it is done consistently for all accesses, no matter from where.您还可以将角色检查作为 controller 使用的数据提供者(例如数据库服务)的一部分,以便无论来自何处,所有访问都可以一致地完成。

I will do a middleware named canGet<Controller name> and the code in it will be我将做一个名为canGet<Controller name>的中间件,其中的代码将是

 switch(userRole): 
  case 'teacher':
    next();
    break;
  case 'user':
    next();
    break;
  default:
   res.statut(403);

And then you can add any role in it, and without changing the name of the function in your route然后你可以在其中添加任何角色,而无需更改路由中 function 的名称

I am agreeable with option No.1.我同意选项 1。 I have one project which has to handle 7 roles.我有一个项目必须处理 7 个角色。 It has been running for 2 months now.它已经运行了 2 个月了。 I declare the roles as below:我声明的角色如下:

  const express = require("express");
  const router = express.Router();
  const role = require("../authentication/authRole");
  const auth = require("../authentication/authentication");

  router.get('/sliders', auth.isAuthenticated, role.isUserOrTeacher("admin", "teacher", "student"), controller.findAll)

  // You can add more routes and define which role is allowed to access

  module.exports = router;

authRole.js authRole.js

  const isUserOrTeacher = (roleOne, roleTwo, roleThree) => {
    return (req, res, next) => {
      // codes
      for (let i = 0; i < roles.length; i++) {
        if (roles[i].name === roleOne || roles[i].name === roleTwo || roles[i].name === roleThree) {
          // codes
      }
      // codes
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM