我需要检查用户是否是管理员,或者用户是否与请求的用户相同。我试过了,但在一种情况下不起作用。
router.get('/:id', isSigned, isSameUser || isAdmin, getUser)有没有办法在不创建专用函数的情况下做我想做的事?
发布于 2022-10-20 13:43:47
您可以编写不同的中间件,以避免不必要的中间件链接,您可以将其称为Auth或AuthMiddleware,您想要的名称取决于您。在这个中间件中,您可以执行检查用户身份验证状态的逻辑,类似于以下内容:
function AuthMiddleware(request, response, next) {
if(isSigned) {
// User is signed in, so we can proceed doing the next check
if(isSameUser || isAdmin || getUser) {
// Validation checks out, go to next middleware without warnings.
return next();
} else {
// User failed to show some ID and cannot access the page.
return next(new Error("Unauthorized."));
}
} else {
// The user has not signed in to your application
return next(new Error("Unauthenticated"));
}
}
router.get('/:id', AuthMiddleWare, (request, response) => {
// DO LOGIC
});将这个中间件放入一个新文件中,每次需要它时,您都可以导入它,而不是一遍又一遍地复制和粘贴相同的代码。
!注意,这是一个粗略的草图代码,只是为了让您走上正确的轨道,所以您很可能不得不根据自己的需要和逻辑调整这个片段。
拥有单个身份验证中间件的好处在于,您可以在每个路由上使用它,因此您不必在请求中使用这么多的链接。
https://stackoverflow.com/questions/74140808
复制相似问题