advent22/api/advent22_api/routers/_security.py

66 lines
1.5 KiB
Python
Raw Normal View History

import secrets
from datetime import date
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from ..core.config import Config, get_config
2023-09-21 11:26:02 +00:00
from ..core.depends import get_all_event_dates
from ..core.helpers import EventDates
security = HTTPBasic()
async def user_is_admin(
credentials: HTTPBasicCredentials = Depends(security),
cfg: Config = Depends(get_config),
) -> bool:
2023-09-08 19:44:41 +00:00
"""
True iff der user "admin" ist
"""
2023-11-21 21:54:37 +00:00
username_correct = secrets.compare_digest(
credentials.username.lower(),
cfg.admin.name.lower(),
)
password_correct = secrets.compare_digest(
credentials.password,
cfg.admin.password,
)
return username_correct and password_correct
async def require_admin(
is_admin: bool = Depends(user_is_admin),
) -> None:
2023-09-08 19:44:41 +00:00
"""
HTTP 401 iff der user nicht "admin" ist
"""
if not is_admin:
2023-09-21 11:26:02 +00:00
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Wie unhöflich!!!")
2023-09-21 11:26:02 +00:00
async def user_visible_days(
event_dates: EventDates = Depends(get_all_event_dates),
) -> list[int]:
2023-09-08 19:44:41 +00:00
"""
Anzahl der user-sichtbaren Türchen
"""
today = date.today()
2023-09-21 11:26:02 +00:00
return [event for event, date in event_dates.dates.items() if date <= today]
async def user_can_view_day(
day: int,
2023-09-21 11:26:02 +00:00
visible_days: list[int] = Depends(user_visible_days),
) -> bool:
2023-09-08 19:44:41 +00:00
"""
True iff das Türchen von Tag `day` user-sichtbar ist
"""
2023-09-21 11:26:02 +00:00
return day in visible_days