Coverage for api/handlers/authorization/check_role.py: 40%

11 statements  

« prev     ^ index     » next       coverage.py v7.6.2, created at 2024-10-10 03:02 +0300

1from fastapi import HTTPException 

2from keycloak import idp 

3from sotrans_models.models.users import SotransOIDCUserModel 

4 

5 

6def has_role(user: SotransOIDCUserModel, role: str): 

7 return idp.check_roles(user.roles, [role]) 

8 

9 

10def assert_single_role_access( 

11 user: SotransOIDCUserModel, role: str, access_object: str = "этот метод" 

12): 

13 if not has_role(user, role): 

14 raise HTTPException( 

15 403, 

16 detail=f"Нет доступа. Только пользователям с ролью {role} доступен {access_object}.", 

17 ) 

18 

19 

20def assert_any_roles_access( 

21 user: SotransOIDCUserModel, 

22 roles: list, 

23 access_object: str = "this endpoint", 

24): 

25 if not any([idp.check_roles(user.roles, [role]) for role in roles]): 

26 raise HTTPException( 

27 403, 

28 detail=f"No permissions. Only users with any of this roles: {roles}, can access {access_object}.", 

29 )