advent22/api/advent22_api/routers/user.py

37 lines
904 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 ..core.config import Config
2022-11-15 22:17:32 +00:00
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(Config.get_config),
2022-11-15 22:17:32 +00:00
) -> bool:
2023-09-03 16:44:18 +00:00
username_correct = secrets.compare_digest(credentials.username, config.admin.name)
2022-11-15 23:43:13 +00:00
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