gpt4 book ai didi

node.js - 模型操作的 Sails.js 身份验证

转载 作者:IT老高 更新时间:2023-10-28 13:25:04 26 4
gpt4 key购买 nike

我正在制作一个具有不同访问级别的 API,“客户端”可能只能读取。但“管理员”必须具有写入权限。每次检查不同的角色作为 Sails.js 中的策略,并在 req.session 中设置权限。

我只需要让“客户端”无法访问创建、更新和删除操作,因此我创建了一个具有这些 CRUD 操作的 Controller 并检查用户是否具有正确的角色。所有访问受限的操作都通过 routes.js 重定向到此 Controller 。

现在我的问题是,当我删除如下条目时:Category.destroy(req.param('id'));给我 undefined 并且没有 done 方法。与文档中提到的不同,我设法通过创建这个来解决问题:

   var deleted = Category.destroy(req.param('id'), function(err, status) { 
if (status == 1){
res.json({message: 'Category is deleted'});
} else {
res.json({message: 'Oops, something went wrong'});
}
});

但是必须有另一种方法来对这些基本操作应用身份验证。因为现在我要编写所有 Action 。

我写的删除函数的代码有问题吗?是否可以应用策略并重定向到默认模型操作,就好像根本没有身份验证一样?

最佳答案

您可以在 ModelsControllers 级别定义策略。这是 /config/policies.js 中的一个示例。

module.exports.policies = {
// Default policy (allow public access)
'*': true,
'events': 'eventsPolicy', // Policy for a Model

someController: { // Policy for a Controller
// Apply the "authenticated" policy to all actions
'*': 'authenticated',

// For someAction, apply 'somePolicy' instead
someAction: 'somePolicy'
}
};

api/policies 下是您可以定义访问级别的地方。

module.exports = function (req, res, next) {
if (req.session.user) {
var action = req.param('action');
if (action == "create") {
req.body.userId = req.session.user.id;
req.body.username = req.session.user.username;
}
next();
} else {
res.send("You're not authenticated.", 403);
}
};

希望这会有所帮助。

关于node.js - 模型操作的 Sails.js 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16061678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com