所以我正在做一个基于角色的访问应用程序,并将用户的角色嵌入到 JWT 中。当我解码令牌时,我得到了id, role.... 现在我有一个函数可以检查标头中的令牌x-auth-token。这就是函数的样子。
export const decodeToken = (controller) => {
return wrapAsync(async (httpRequest) => {
const token = httpRequest.headers['x-auth-token']
if (!token) {
throw new UnauthorizedError('No token, authorization denied.')
}
const decoded = jwt.verify(token, process.env.JWT_SECRET)
httpRequest.user = decoded
return controller(httpRequest)
})
}
我还有一个检查角色的函数,它与函数类似decodeToken,这就是roleCheck函数的样子。
export function roleCheck(controller) {
return wrapAsync(async (httpRequest) => {
const token = httpRequest.headers['x-auth-token']
const decoded = jwt.verify(token, process.env.JWT_SECRET)
if (decoded.role !== 'admin') {
throw new UnauthorizedError(
'You do not have the authorization to perform this action'
)
}
return controller(httpRequest)
})
}
现在,这里有相当多的代码重复。我可以解决此问题的一种方法是还检查函数中的角色decodeToken,但该方法将导致没有将角色admin附加到传入负载的用户无法访问所有路由。现在我的问题是我该如何通过这个
const token = httpRequest.headers['x-auth-token']
const decoded = jwt.verify(token, process.env.JWT_SECRET)
从decodeToken功能到roleCheck功能。另外,这是函数组合的用例吗?我觉得代码可以比这干净得多,但我只是不知道如何实现这一点。
通常,路线如下所示
export function config(router) {
router
.post('/', expressCallback(decodeToken(roleCheck(postProduct))))
.get('/', expressCallback(decodeToken(getProducts)))
...
return router
}
因此,decodeToken首先调用 ,然后在roleCheck请求到达postProduct控制器之前调用 。通过这种方式,从标头获取令牌并进行解码,然后控制器可以根据角色采取行动。
任何帮助将不胜感激,谢谢。
慕工程0101907
相关分类