I am trying to use casl-mongoose for role based authentication
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);
I got ForbiddenError even I used role correctly.I want to know how to use "create" in casl.
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 object
req.user : admin
{
"name": "aaa",
"email": "[email protected]",
"password": "password",
"role": "user"
}
I've just tested your code and if you pass "user"
instead of req.user.userRole
, you won't be able to create a user because your permissions says that user with role "user" can only read users with role "user".
If you pass "admin"
, then everything is ok and error is not thrown.
The link to repl - https://repl.it/@stalniy/so-63132256