From 88c500ed8db61773c7a138c504926b491fc48b5d Mon Sep 17 00:00:00 2001 From: Sanu Date: Thu, 7 Nov 2024 23:25:32 +0530 Subject: [PATCH] casbin rbac sample enforcer --- backend/api/UsersView.py | 8 +++++++- backend/rbac_model.conf | 5 ++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/backend/api/UsersView.py b/backend/api/UsersView.py index f2cbd803..37273234 100644 --- a/backend/api/UsersView.py +++ b/backend/api/UsersView.py @@ -1,6 +1,7 @@ from starlette.responses import JSONResponse, Response from common.paths import api_base_url from backend.managers.UsersManager import UsersManager +from backend.managers.CasbinRoleManager import CasbinRoleManager from backend.pagination import parse_pagination_params from aiosqlite import IntegrityError from backend.schemas import UserSchema @@ -8,6 +9,7 @@ class UsersView: def __init__(self): self.um = UsersManager() + self.cb = CasbinRoleManager() async def get(self, id: str): user = await self.um.retrieve_user(id) @@ -15,7 +17,11 @@ async def get(self, id: str): return JSONResponse(status_code=404, headers={"error": "User not found"}) return JSONResponse(user.model_dump(), status_code=200) - async def post(self, body: dict): + async def post(self,token_info, body: dict): + enforcer = self.cb.get_enforcer() + if not enforcer.enforce(token_info["role"], 'user', 'POST'): + return JSONResponse({"message": "Permission denied"}, status_code=403) + try: id = await self.um.create_user(body['name'], body['email']) return JSONResponse({"id": id}, status_code=201, headers={'Location': f'{api_base_url}/users/{id}'}) diff --git a/backend/rbac_model.conf b/backend/rbac_model.conf index a1f4c8e5..7635cc09 100644 --- a/backend/rbac_model.conf +++ b/backend/rbac_model.conf @@ -2,14 +2,13 @@ r = role, res_id, act [policy_definition] -p = role, res_id, act, eft +p = role, res_id, act [policy_effect] e = some(where (p.eft == allow)) [matchers] -m = (r.res_id == p.res_id && r.act == p.act && r.role == p.role) || - (r.res_id != p.res_id && p.res_id == "DEFAULT" && r.act == p.act && r.role == p.role) +m = (r.res_id == p.res_id && r.act == p.act && r.role == p.role) || (p.res_id == "DEFAULT" && r.act == p.act && r.role == p.role) [role_definition] g = _, _ \ No newline at end of file