我正在尝试使用 casl-mongoose 进行基于角色的身份验证
角色.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;
};
用户.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。我想知道如何在 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"
}