[英]How can i allow specific user categories to access specific routes of application?
My application consists of two type of users.我的应用程序由两种类型的用户组成。 Let's say A and B. Both of them first needs to authenticated.假设 A 和 B。他们都首先需要进行身份验证。 Authentication is done.认证完成。 But now i want A to access specific routes and if it tries to access B routes i want to give A error like access denied to this route and same for B. A is type=0 and B is type=1.但是现在我希望 A 访问特定的路由,如果它尝试访问 B 路由,我想给 A 错误,例如拒绝访问此路由,对于 B 也是如此。A 是 type=0,B 是 type=1。
For authetication i am using this middleware which uses token:对于身份验证,我正在使用这个使用令牌的中间件:
auth.js: auth.js:
const authenticate = (req, res, next) => {
var token = req.cookies['x-auth'];
User.findByToken(token).then(user => {
if(!user){
return Promise.reject();
}
req.user = user;
next();
}).catch(err => {
console.log(err);
var response = {
status:'failure',
message: err.message
};
res.status(401).send(response);
})
};
How should i proceed to achieve this?我应该如何着手实现这一目标?
Here's your solution, where roles
is an array of strings containing the allowed roles for that specific route.这是您的解决方案,其中roles
是一个字符串数组,其中包含该特定路线的允许角色。 This also implies that the users (in your MongoDB model) have a role
field.这也意味着用户(在您的 MongoDB 模型中)具有role
字段。
const authenticateWithRole = (roles = []) => {
return async (req, res next) => {
const token = req.cookies['x-auth'];
try {
const user = await User.findByToken(token);
if (roles.includes(user.role)) {
// Store the informations for the middleware
req.user = user;
next();
} else {
res.status(403).send({
// Your error-response here...
});
}
}
catch (e) {
res.status(401).send({
// Your error-response here...
});
}
}
}
// Later in your APIs
app.use('/limited-route', authenticateWithRole([
'admin',
'student'
]), (req, res) => {
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.