permission checker
This commit is contained in:
parent
f5da8ed3c4
commit
c09eb45ac2
18
app/dependencies/permissions_checker.py
Normal file
18
app/dependencies/permissions_checker.py
Normal 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'
|
||||||
|
)
|
@ -1,5 +1,5 @@
|
|||||||
from fastapi import APIRouter, Depends
|
from fastapi import APIRouter, Depends
|
||||||
from ..dependencies import users_active
|
from ..dependencies import users_active, permissions_checker
|
||||||
from ..models import users
|
from ..models import users
|
||||||
from typing import Annotated
|
from typing import Annotated
|
||||||
|
|
||||||
@ -7,9 +7,9 @@ from typing import Annotated
|
|||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
|
|
||||||
@router.get("/users/", tags=["users"], response_model=list[users.User])
|
@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
|
return users_active.fake_users
|
||||||
|
|
||||||
@router.get("/users/me",tags=["users"], response_model=users.User)
|
@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
|
return current_user
|
Loading…
x
Reference in New Issue
Block a user