在 Express 中间件调用中访问路由参数

问题描述 投票:0回答:1

我有一个使用 Discord 来验证用户身份的应用程序。在后端,在某些端点上,我需要检查发出请求的用户是否是给定公会中的管理员。

例如:

PATCH "/set-bot-config-for-guild/:guildId"
、<- I would like to allow only server admins to call this

我创建了一个身份验证中间件。它是一个返回 RequestHandler 函数的函数,如下所示:

export function authenticateAdmin(guildId: string) {
   return async (req: Request; res: Response; next: NextFunction) => {
      // get user auth token from req.cookies.token
      ...
      // verify token with Discord auth api, get user id
      ...
      // get user roles in given guild, from Discord api
      ...
      // get admin role id of given guild from Discord api using guildId
      ...
      // check if user has admin role in given guild
      ...
      if (userIsAdminInGuild) {
         next()
      }
      else {
          return res.status(401).send("Unauthorized");
      }
   }
}

本来我想这样称呼这个中间件:

router.patch(
   "/set-bot-config-for-guild/:guildId",
   authenticateAdmin(guildId),
   async (req: Request, res: Response) => {
       ...
   }
);

问题是,

guildId
来自路由参数
:guildId
,在调用中间件时我还没有访问权限。

  • 有什么办法获取并传递给中间件吗?
  • 或者我需要在中间件函数本身中获取 guildId 吗?因为也许 guildId 不会总是在路由中,而是来自其他地方,而且我仍然希望能够使用这个中间件。

编辑:经过更多调查,结果发现我也无法在中间件中访问

req.params.guildId
。因此,我只需编写一个函数来检查用户是否是给定公会中的管理员,并在任何相关的路由处理程序中调用它。

它有效,但如果有人有更“优雅”的解决方案,请帮助我。

express middleware
1个回答
0
投票

您可以访问中间件本身中的

guildId

像这样定义路线

router.patch(
   "/set-bot-config-for-guild/:guildId",
   authenticateAdmin,
   async (req: Request, res: Response) => {
       ...
   }
);

在中间件中,如果将其定义为函数,您将拥有

request
属性。

export const authenticateAdmin=async (req: Request; res: Response; next: NextFunction) => {
       const guildId=req.params?.guildId;   
       // get user auth token from req.cookies.token
       ...
       // verify token with Discord auth api, get user id
       ...
       // get user roles in given guild, from Discord api
       ...
       // get admin role id of given guild from Discord api using guildId
       ...
       // check if user has admin role in given guild
       ...
       if (userIsAdminInGuild) {
          next()
       }
       else {
           return res.status(401).send("Unauthorized");
       }
    }
© www.soinside.com 2019 - 2024. All rights reserved.