TestFastApi/api_v1/auth/views.py

56 lines
1.4 KiB
Python

from typing import Annotated
import secrets
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
router = APIRouter(prefix="/auth", tags=["auth"])
security = HTTPBasic()
@router.get("/basic-auth")
def basic_auth_credentials(
credentials: Annotated[HTTPBasicCredentials, Depends(security)],
):
return {
"message": "Hello",
"username": credentials.username,
"password": credentials.password,
}
username_to_password = {
"admin": "admin",
"user": "user",
}
def get_auth_user_username(
credentials: Annotated[HTTPBasicCredentials, Depends(security)],
):
unauth_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
correct_password = username_to_password.get(credentials.username)
if correct_password is None:
raise unauth_exception
if not secrets.compare_digest(
credentials.password.encode("utf-8"),
correct_password.encode("utf-8"),
):
raise unauth_exception
return credentials.username
@router.get("/basic-auth-username")
def basic_auth_username(
auth_username: str = Depends(get_auth_user_username),
):
return {
"message": f"Hello {auth_username}",
"username": auth_username,
}