![](/img/trans.png)
[英]How can I disable NodeJS Express for specific paths in my app and allow access to a specific regex in one of them?
[英]How can i allow specific user categories to access specific routes of application?
我的應用程序由兩種類型的用戶組成。 假設 A 和 B。他們都首先需要進行身份驗證。 認證完成。 但是現在我希望 A 訪問特定的路由,如果它嘗試訪問 B 路由,我想給 A 錯誤,例如拒絕訪問此路由,對於 B 也是如此。A 是 type=0,B 是 type=1。
對於身份驗證,我正在使用這個使用令牌的中間件:
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);
})
};
我應該如何着手實現這一目標?
這是您的解決方案,其中roles
是一個字符串數組,其中包含該特定路線的允許角色。 這也意味着用戶(在您的 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.