0Mart00
v2.0: AI cache, valtozo szo hossz (4-7), dashboard stats, multiplayer gateway, success modal, univerzalis Dockerfile, docker-compose mindket service
fc7b2a8 Download src/wordgame/core/auth.py from humut/WordGame: direct link, hf CLI and curl.
- Browser
- Download file 6.7 kB
-
https://huggingface.co/spaces/humut/WordGame/resolve/main/src/wordgame/core/auth.py
- Command line
-
hf download hf://spaces/humut/WordGame/src/wordgame/core/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/humut/WordGame/resolve/main/src/wordgame/core/auth.py
6.7 kB
| """Központi autentikációs utility a public és private appokhoz. | |
| Ez a modul biztosítja, hogy a public (WordGame) és private (Lingo) HF Space-ek | |
| között egységesen működjön a felhasználó azonosítása a Supabase JWT | |
| token-eken keresztül. Mivel a két Space más-más domain alatt fut | |
| (humut-WordGame.hf.space vs humut-Lingo.hf.space), a cookie-k natívan | |
| nem oszthatók meg – ehelyett a cross-domain SSO callback (Lingo | |
| /auth/sso) hidat épít a kettő közé. | |
| """ | |
| from typing import Optional | |
| from fastapi import Cookie, HTTPException, status, Response | |
| from .database import supabase | |
| from .config import settings | |
| # A cookie neve, amit mindenütt használunk. | |
| ACCESS_TOKEN_COOKIE = "access_token" | |
| # A rejtett admin email-ek – a settings.ADMIN_EMAILS-ből jönnek. | |
| _ADMIN_EMAILS_SET = None | |
| def _get_admin_emails() -> set: | |
| """Parse admin emails from settings (vesszővel elválasztott string).""" | |
| global _ADMIN_EMAILS_SET | |
| if _ADMIN_EMAILS_SET is None: | |
| raw = settings.ADMIN_EMAILS or "adminn@wordgame.hu,admin@wordgame.com" | |
| _ADMIN_EMAILS_SET = {e.strip() for e in raw.split(",") if e.strip()} | |
| return _ADMIN_EMAILS_SET | |
| # --------------------------------------------------------------------------- | |
| # Dependency-k | |
| # --------------------------------------------------------------------------- | |
| async def get_user_optional( | |
| access_token: Optional[str] = Cookie(default=None, alias=ACCESS_TOKEN_COOKIE) | |
| ): | |
| """Visszaadja a Supabase user objektumot, ha van érvényes cookie. | |
| Publikus route-okhoz való, ahol a user lehet belépve vagy sem. | |
| Soha nem dob kivételt – ha bármi baj van, egyszerűen None-t ad vissza, | |
| és a route eldönti, hogy ez mit jelent (pl. login gomb mutatása). | |
| """ | |
| if not access_token: | |
| return None | |
| try: | |
| res = supabase.auth.get_user(access_token) | |
| return res.user if res and res.user else None | |
| except Exception: | |
| return None | |
| async def require_user( | |
| access_token: Optional[str] = Cookie(default=None, alias=ACCESS_TOKEN_COOKIE) | |
| ): | |
| """Kötelező bejelentkezés – 401-et dob, ha nincs érvényes session. | |
| Privát route-okhoz (dashboard, szoba, deck, invite) való. | |
| A kapott felhasználót a `profilok` táblában is ellenőrzi, hogy | |
| a profil létezik-e (a Supabase auth.users és a profilok tábla | |
| közötti eltérés kezelésére). | |
| """ | |
| if not access_token: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Bejelentkezés szükséges", | |
| ) | |
| try: | |
| res = supabase.auth.get_user(access_token) | |
| if not res or not res.user: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Érvénytelen munkamenet", | |
| ) | |
| return res.user | |
| except HTTPException: | |
| raise | |
| except Exception: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Érvénytelen munkamenet", | |
| ) | |
| async def require_admin( | |
| access_token: Optional[str] = Cookie(default=None, alias=ACCESS_TOKEN_COOKIE) | |
| ): | |
| """Admin jogosultságot kér – 403-at dob, ha a user emailje nem admin. | |
| A rejtett /a7d9f2e1b4c6 route-ok és műveletek védelmére való. | |
| """ | |
| user = await require_user(access_token) | |
| if not user.email or user.email not in _get_admin_emails(): | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Admin jogosultság szükséges", | |
| ) | |
| return user | |
| # --------------------------------------------------------------------------- | |
| # Prémium státusz ellenőrzése | |
| # --------------------------------------------------------------------------- | |
| def is_premium(user_id: str) -> bool: | |
| """Megnézi a `profilok` táblából, hogy a user prémium-e (szinkron). | |
| A függvény szinkron, mert a supabase-py kliens execute() hívása is szinkron | |
| (asyncio wrapper nélkül). Ha hiba van, False-szal tér vissza – a route | |
| dönti el, hogy ez elfogadható-e (pl. szobacsatlakozásnál igen, fizetésnél nem). | |
| """ | |
| try: | |
| profile = supabase.table(settings.TABLE_PROFILES)\ | |
| .select("is_premium")\ | |
| .eq("id", user_id)\ | |
| .execute() | |
| if profile.data and len(profile.data) > 0: | |
| return bool(profile.data[0].get("is_premium", False)) | |
| except Exception: | |
| pass | |
| return False | |
| async def is_premium_async(user_id: str) -> bool: | |
| """Async wrapper az is_premium() köré – nem blokkolja az event loop-ot.""" | |
| import asyncio | |
| loop = asyncio.get_running_loop() | |
| return await loop.run_in_executor(None, is_premium, user_id) | |
| # --------------------------------------------------------------------------- | |
| # Cookie beállítás / törlés helper-ek | |
| # --------------------------------------------------------------------------- | |
| def set_access_cookie( | |
| response: Response, | |
| token: str, | |
| max_age: int = 3600, | |
| ) -> None: | |
| """Beállítja az access_token cookie-t a Response objektumon. | |
| A cookie paraméterei környezetfüggőek: | |
| - production (DEBUG=False): secure=True, samesite="none" (mert a | |
| private Lingo Space cross-domain cookie-t fogad a public WordGame | |
| Space SSO callback-jén keresztül) | |
| - development (DEBUG=True): secure=False, samesite="lax" (hogy a | |
| böngésző local fejlesztésnél is elfogadja) | |
| """ | |
| is_prod = not settings.DEBUG | |
| response.set_cookie( | |
| key=ACCESS_TOKEN_COOKIE, | |
| value=token, | |
| httponly=True, | |
| secure=is_prod, | |
| samesite="none" if is_prod else "lax", | |
| max_age=max_age, | |
| expires=max_age, | |
| domain=None, # a saját (HF Space) domainre szól | |
| path="/", | |
| ) | |
| def clear_access_cookie(response: Response) -> None: | |
| """Törli az access_token cookie-t (logout-hoz).""" | |
| is_prod = not settings.DEBUG | |
| response.delete_cookie( | |
| key=ACCESS_TOKEN_COOKIE, | |
| path="/", | |
| secure=is_prod, | |
| samesite="none" if is_prod else "lax", | |
| domain=None, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Backward-compat alias-ok | |
| # --------------------------------------------------------------------------- | |
| # A régi route-ok (game_routes, dashboard_routes, room_routes, admin_routes) | |
| # különböző neveken hivatkoztak a saját auth helper-jeikre. Ezek az alias-ok | |
| # megkönnyítik a fokozatos átállást, de a terv szerint a route-okat a későbbi | |
| # lépésekben átírjuk, hogy közvetlenül a fenti függvényeket hívják. | |
| get_current_user = get_user_optional # game_routes régi neve | |