diff --git a/app/dependencies/permissions_checker.py b/app/dependencies/permissions_checker.py new file mode 100644 index 0000000..896679f --- /dev/null +++ b/app/dependencies/permissions_checker.py @@ -0,0 +1,18 @@ +from ..dependencies import users_active +from fastapi import Depends, HTTPException, status +from ..models import users + + +class PermissionChecker: + + def __init__(self, roles: list[str]) -> None: + self.roles = roles + + def __call__(self, user: users.User = Depends(users_active.get_current_active_user)) -> bool: + for role in self.roles: + if role == user.roles: + return True + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail='Roles unauthorized' + ) diff --git a/app/routers/users.py b/app/routers/users.py index 250013b..0ec1ccf 100644 --- a/app/routers/users.py +++ b/app/routers/users.py @@ -1,5 +1,5 @@ from fastapi import APIRouter, Depends -from ..dependencies import users_active +from ..dependencies import users_active, permissions_checker from ..models import users from typing import Annotated @@ -7,9 +7,9 @@ from typing import Annotated router = APIRouter() @router.get("/users/", tags=["users"], response_model=list[users.User]) -async def read_users(current_user: Annotated[users.User, Depends(users_active.get_current_active_user)]): +async def read_users(current_user: Annotated[users.User, Depends(users_active.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))]): return users_active.fake_users @router.get("/users/me",tags=["users"], response_model=users.User) -async def read_users_me(current_user: Annotated[users.User, Depends(users_active.get_current_active_user)]): +async def read_users_me(current_user: Annotated[users.User, Depends(users_active.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))]): return current_user \ No newline at end of file