advent22/api/advent22_api/routers/user.py

39 lines
918 B
Python
Raw Normal View History

2022-11-15 23:43:13 +00:00
import secrets
2022-11-15 22:17:32 +00:00
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from ..config import Config, get_config
router = APIRouter(prefix="/user", tags=["user"])
security = HTTPBasic()
2022-11-15 23:43:13 +00:00
async def user_is_admin(
2022-11-15 22:17:32 +00:00
credentials: HTTPBasicCredentials = Depends(security),
config: Config = Depends(get_config),
) -> bool:
2022-11-15 23:43:13 +00:00
username_correct = secrets.compare_digest(
credentials.username, config.admin.name
)
password_correct = secrets.compare_digest(
credentials.password, config.admin.password
)
return username_correct and password_correct
2022-11-15 22:17:32 +00:00
async def require_admin(
2022-11-15 23:43:13 +00:00
is_admin: bool = Depends(user_is_admin),
2022-11-15 22:17:32 +00:00
) -> None:
if not is_admin:
raise HTTPException(status.HTTP_401_UNAUTHORIZED)
@router.get("/admin")
def check_admin(
_: None = Depends(require_admin),
2022-11-15 23:43:13 +00:00
) -> bool:
return True