fix: improve authorization logic in RBAC by refining action checks and simplifying role permission validation

This commit is contained in:
swve 2025-05-05 22:38:44 +02:00
parent 8c2b1e5b99
commit dcfcb06b2e

View file

@ -60,7 +60,11 @@ async def authorization_verify_if_user_is_author(
element_uuid: str, element_uuid: str,
db_session: Session, db_session: Session,
): ):
if action == "update" or "delete" or "read": # For create action, we don't need to check existing resource
if action == "create":
return True # Allow creation if user is authenticated
if action in ["update", "delete", "read"]:
statement = select(ResourceAuthor).where( statement = select(ResourceAuthor).where(
ResourceAuthor.resource_uuid == element_uuid ResourceAuthor.resource_uuid == element_uuid
) )
@ -79,6 +83,7 @@ async def authorization_verify_if_user_is_author(
return False return False
else: else:
return False return False
return False
# Tested and working # Tested and working
@ -101,17 +106,17 @@ async def authorization_verify_based_on_roles(
user_roles_in_organization_and_standard_roles = db_session.exec(statement).all() user_roles_in_organization_and_standard_roles = db_session.exec(statement).all()
# Find in roles list if there is a role that matches users action for this type of element # Check all roles until we find one that grants the permission
for role in user_roles_in_organization_and_standard_roles: for role in user_roles_in_organization_and_standard_roles:
role = Role.model_validate(role) role = Role.model_validate(role)
if role.rights: if role.rights:
rights = role.rights rights = role.rights
if rights[element_type][f"action_{action}"] is True: element_rights = getattr(rights, element_type, None)
if element_rights and getattr(element_rights, f"action_{action}", False):
return True return True
else:
return False # If we get here, no role granted the permission
else: return False
return False
async def authorization_verify_based_on_org_admin_status( async def authorization_verify_based_on_org_admin_status(
@ -133,13 +138,13 @@ async def authorization_verify_based_on_org_admin_status(
user_roles_in_organization_and_standard_roles = db_session.exec(statement).all() user_roles_in_organization_and_standard_roles = db_session.exec(statement).all()
# Find in roles list if there is a role that matches users action for this type of element # Check if user has admin role (role_id 1 or 2) in any organization
for role in user_roles_in_organization_and_standard_roles: for role in user_roles_in_organization_and_standard_roles:
role = Role.model_validate(role) role = Role.model_validate(role)
if role.id == 1 or role.id == 2: if role.id in [1, 2]: # Assuming 1 and 2 are admin role IDs
return True return True
else:
return False return False
# Tested and working # Tested and working