permission checker

This commit is contained in:
Valentin CZERYBA 2023-10-12 23:54:50 +02:00
parent f5da8ed3c4
commit c09eb45ac2
2 changed files with 21 additions and 3 deletions

View File

@ -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'
)

View File

@ -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