You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.4 KiB
51 lines
1.4 KiB
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
|
|
from jose import JWTError
|
|
|
|
from pydantic import ValidationError
|
|
|
|
from .auth import decode_jwt
|
|
from .users import get_user_by_username
|
|
|
|
from ..schemas.users import UserRead, UserWrite, UserAdmin
|
|
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth")
|
|
|
|
|
|
async def get_current_user(token: str = Depends(oauth2_scheme)):
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"}
|
|
)
|
|
try:
|
|
token_data = decode_jwt(token)
|
|
if token_data is None:
|
|
raise credentials_exception
|
|
|
|
except (JWTError, ValidationError):
|
|
raise credentials_exception
|
|
|
|
user = await get_user_by_username(token_data.username)
|
|
if user is None:
|
|
raise credentials_exception
|
|
|
|
return user
|
|
|
|
|
|
def make_right_checkers():
|
|
rights_schemas = {"read": UserRead, "write": UserWrite, "admin": UserAdmin}
|
|
dependencies = {}
|
|
for right, schema in rights_schemas.items():
|
|
async def depend_function(token: str = Depends(oauth2_scheme)):
|
|
user = await get_current_user(token=token)
|
|
return schema(**user)
|
|
|
|
dependencies[right] = depend_function
|
|
return dependencies
|
|
|
|
|
|
right_checkers = make_right_checkers()
|