Add internationalization support and enhance language handling
All checks were successful
CI / lint-and-test (push) Successful in 14s
All checks were successful
CI / lint-and-test (push) Successful in 14s
- Introduced a new i18n module for managing translations and language normalization, supporting both Russian and English. - Updated various handlers and services to utilize the new translation functions for user-facing messages, improving user experience based on language preferences. - Enhanced error handling and response messages to be language-aware, ensuring appropriate feedback is provided to users in their preferred language. - Added tests for the i18n module to validate language detection and translation functionality. - Updated the example environment file to include a default language configuration.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"""FastAPI dependencies: DB session, auth, date validation."""
|
||||
|
||||
import logging
|
||||
import re
|
||||
from typing import Annotated, Generator
|
||||
|
||||
from fastapi import Header, HTTPException, Query, Request
|
||||
@@ -11,23 +12,55 @@ from duty_teller.api.telegram_auth import validate_init_data_with_reason
|
||||
from duty_teller.db.repository import get_duties
|
||||
from duty_teller.db.schemas import DutyWithUser
|
||||
from duty_teller.db.session import session_scope
|
||||
from duty_teller.i18n import t
|
||||
from duty_teller.utils.dates import validate_date_range
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# First language tag from Accept-Language (e.g. "ru-RU,ru;q=0.9,en;q=0.8" -> "ru")
|
||||
_ACCEPT_LANG_TAG_RE = re.compile(r"^([a-zA-Z]{2,3})(?:-[a-zA-Z0-9]+)?\s*(?:;|,|$)")
|
||||
|
||||
def _validate_duty_dates(from_date: str, to_date: str) -> None:
|
||||
|
||||
def _lang_from_accept_language(header: str | None) -> str:
|
||||
"""Normalize Accept-Language to 'ru' or 'en'; fallback to config.DEFAULT_LANGUAGE."""
|
||||
if not header or not header.strip():
|
||||
return config.DEFAULT_LANGUAGE
|
||||
first = header.strip().split(",")[0].strip()
|
||||
m = _ACCEPT_LANG_TAG_RE.match(first)
|
||||
if not m:
|
||||
return "en"
|
||||
code = m.group(1).lower()
|
||||
return "ru" if code.startswith("ru") else "en"
|
||||
|
||||
|
||||
def _auth_error_detail(auth_reason: str, lang: str) -> str:
|
||||
"""Return translated auth error message."""
|
||||
if auth_reason == "hash_mismatch":
|
||||
return t(lang, "api.auth_bad_signature")
|
||||
return t(lang, "api.auth_invalid")
|
||||
|
||||
|
||||
def _validate_duty_dates(from_date: str, to_date: str, lang: str) -> None:
|
||||
"""Validate date range; raise HTTPException with translated detail."""
|
||||
try:
|
||||
validate_date_range(from_date, to_date)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e)) from e
|
||||
msg = str(e)
|
||||
if "YYYY-MM-DD" in msg or "формате" in msg:
|
||||
detail = t(lang, "dates.bad_format")
|
||||
else:
|
||||
detail = t(lang, "dates.from_after_to")
|
||||
raise HTTPException(status_code=400, detail=detail) from e
|
||||
|
||||
|
||||
def get_validated_dates(
|
||||
request: Request,
|
||||
from_date: str = Query(..., description="ISO date YYYY-MM-DD", alias="from"),
|
||||
to_date: str = Query(..., description="ISO date YYYY-MM-DD", alias="to"),
|
||||
) -> tuple[str, str]:
|
||||
_validate_duty_dates(from_date, to_date)
|
||||
"""Validate from/to dates; lang from Accept-Language for error messages."""
|
||||
lang = _lang_from_accept_language(request.headers.get("Accept-Language"))
|
||||
_validate_duty_dates(from_date, to_date, lang)
|
||||
return (from_date, to_date)
|
||||
|
||||
|
||||
@@ -45,15 +78,6 @@ def require_miniapp_username(
|
||||
return get_authenticated_username(request, x_telegram_init_data)
|
||||
|
||||
|
||||
def _auth_error_detail(auth_reason: str) -> str:
|
||||
if auth_reason == "hash_mismatch":
|
||||
return (
|
||||
"Неверная подпись. Убедитесь, что BOT_TOKEN на сервере совпадает с токеном бота, "
|
||||
"из которого открыт календарь (тот же бот, что в меню)."
|
||||
)
|
||||
return "Неверные данные авторизации"
|
||||
|
||||
|
||||
def _is_private_client(client_host: str | None) -> bool:
|
||||
if not client_host:
|
||||
return False
|
||||
@@ -81,17 +105,20 @@ def get_authenticated_username(
|
||||
log.warning("allowing without initData (MINI_APP_SKIP_AUTH is set)")
|
||||
return ""
|
||||
log.warning("no X-Telegram-Init-Data header (client=%s)", client_host)
|
||||
raise HTTPException(status_code=403, detail="Откройте календарь из Telegram")
|
||||
lang = _lang_from_accept_language(request.headers.get("Accept-Language"))
|
||||
raise HTTPException(status_code=403, detail=t(lang, "api.open_from_telegram"))
|
||||
max_age = config.INIT_DATA_MAX_AGE_SECONDS or None
|
||||
username, auth_reason = validate_init_data_with_reason(
|
||||
username, auth_reason, lang = validate_init_data_with_reason(
|
||||
init_data, config.BOT_TOKEN, max_age_seconds=max_age
|
||||
)
|
||||
if username is None:
|
||||
log.warning("initData validation failed: %s", auth_reason)
|
||||
raise HTTPException(status_code=403, detail=_auth_error_detail(auth_reason))
|
||||
raise HTTPException(
|
||||
status_code=403, detail=_auth_error_detail(auth_reason, lang)
|
||||
)
|
||||
if not config.can_access_miniapp(username):
|
||||
log.warning("username not in allowlist: %s", username)
|
||||
raise HTTPException(status_code=403, detail="Доступ запрещён")
|
||||
raise HTTPException(status_code=403, detail=t(lang, "api.access_denied"))
|
||||
return username
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user