创建一个中间件函数来检查用户角色是否等于 'Admin' [英] Creating a middleware function to check if user role is equal to 'Admin'
问题描述
我正在使用最新的 MEAN Stack 技术创建博客.已登录的用户可以创建一个具有管理员"和版主"角色的新用户.
I'm creating a blog using the latest MEAN Stack technologies. A logged in user can create a new user with the roles 'admin' and 'moderator.
此路由受到保护,目前只有登录用户才能访问.这是检查用户是否通过身份验证的中间件.
This route is protected and currently, only a logged in user can access it. Here is the middleware for checking if the user is authenticated or not.
//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!'});
}
};
我应用这个中间件来保护对我的一些路由的未经授权的访问.我想创建一个类似的中间件,在其中检查用户是否是管理员.所以我可以在创建用户的路由上应用这个中间件,这样只有授权用户和具有admin"角色的用户才能创建新用户.
I apply this middleware to protect unauthorized access to some of my routes. I want to create a similar middleware in which I check if the user is an administrator or not. So I can apply this middleware on the route for creating users, so only an authorized user and a user who has the role of 'admin' can create a new user.
我认为这有助于创建中间件.当用户登录时,id、email 和角色存储在 jwt.conf 文件中.
I think this can help in creating the middleware. When a user logs in the id, email, and role is stored in the 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"
});
});
});
完整代码可以在我的 GitHub 仓库中找到:https://github.com/rajotam/Eleven
The whole code can be found in my GitHub repository: https://github.com/rajotam/Eleven
推荐答案
向所有需要验证的端点添加一个路由处理程序,并在需要的地方导入它.https://expressjs.com/en/guide/routing.html
Add a Route Handler to all endpoints that need verification and import it wherever needed. https://expressjs.com/en/guide/routing.html
例如
router.post('/login', verify.isAdmin, (req, res, next) => {
//do something
})
//在单独的文件中验证函数
//verify function in separate file
module.exports = {
isAdmin: (req, res, next) =>{
if(req.user.admin){
next();
}else{
res.status(403).send();
}
}
}
完整代码示例:
https://medium.freecodecamp.org/securing-node-js-restful-apis-with-json-web-tokens-9f811a92bb52
这篇关于创建一个中间件函数来检查用户角色是否等于 'Admin'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!