使用 casl 创建用户以获得基于角色的权限
create user using casl for role based permission
我正在尝试使用 casl-mongoose 进行基于角色的身份验证
role.js
module.exports = function (user) {
const ability = defineAbility((can) => {
switch (user) {
case "admin":
can(["create", "read", "update", "delete"], "User");
break;
case "user":
can("read", "User", { role: "user" });
break;
}
});
return ability;
};
user.js
const defineAbilitiesForUser = require("../middleware/roles");
user = new User(_.pick(req.body, ["name", "email", "password", "role"]));
const ability = defineAbilitiesForUser(req.user.userRole);
// req.ability.throwUnlessCan("create", user);
ForbiddenError.from(ability).throwUnlessCan("create", user);
即使我使用了角色,我也遇到了 ForbiddenError correctly.I 想知道如何在 casl 中使用“create”。
ForbiddenError: Cannot execute "create" on "User"
at Function.i.from (/home/madhu/Madhu/JavaScript/codedigital/casl_final/node_modules/@casl/ability/dist/umd/index.js:1:7009)
at /home/madhu/Madhu/JavaScript/codedigital/casl_final/routes/users.js:52:18
at processTicksAndRejections (internal/process/task_queues.js:97:5)
json 对象
req.user : admin
{
"name": "aaa",
"email": "aaa@email.com",
"password": "password",
"role": "user"
}
我刚刚测试了你的代码,如果你传递 "user"
而不是 req.user.userRole
,你将无法创建用户,因为你的权限表明该用户具有角色“user”只能读取角色为“user”的用户。
如果你通过 "admin"
,那么一切正常,不会抛出错误。
我正在尝试使用 casl-mongoose 进行基于角色的身份验证
role.js
module.exports = function (user) {
const ability = defineAbility((can) => {
switch (user) {
case "admin":
can(["create", "read", "update", "delete"], "User");
break;
case "user":
can("read", "User", { role: "user" });
break;
}
});
return ability;
};
user.js
const defineAbilitiesForUser = require("../middleware/roles");
user = new User(_.pick(req.body, ["name", "email", "password", "role"]));
const ability = defineAbilitiesForUser(req.user.userRole);
// req.ability.throwUnlessCan("create", user);
ForbiddenError.from(ability).throwUnlessCan("create", user);
即使我使用了角色,我也遇到了 ForbiddenError correctly.I 想知道如何在 casl 中使用“create”。
ForbiddenError: Cannot execute "create" on "User"
at Function.i.from (/home/madhu/Madhu/JavaScript/codedigital/casl_final/node_modules/@casl/ability/dist/umd/index.js:1:7009)
at /home/madhu/Madhu/JavaScript/codedigital/casl_final/routes/users.js:52:18
at processTicksAndRejections (internal/process/task_queues.js:97:5)
json 对象
req.user : admin
{
"name": "aaa",
"email": "aaa@email.com",
"password": "password",
"role": "user"
}
我刚刚测试了你的代码,如果你传递 "user"
而不是 req.user.userRole
,你将无法创建用户,因为你的权限表明该用户具有角色“user”只能读取角色为“user”的用户。
如果你通过 "admin"
,那么一切正常,不会抛出错误。