""" Authentication helpers for the FastAPI version of Explorer Consultant Bot. Cookies work properly here — FastAPI sets and reads real HTTP cookies through the standard Request / Response objects. No iframes, no async components, no timing races. Persistent login is trivially reliable. Usage in routes --------------- # Read-only (returns None if not logged in) user = get_current_user(request) # Protected route dependency (redirects to /login if not logged in) user: dict = Depends(require_auth) # Set cookie after successful login set_session_cookie(response, token) # Clear cookie on logout clear_session_cookie(response) """ from __future__ import annotations import hashlib import os import secrets from datetime import datetime, timezone, timedelta from typing import Optional from fastapi import Depends, Request, Response from fastapi.responses import RedirectResponse from core import database as db # --------------------------------------------------------------------------- # Config # --------------------------------------------------------------------------- COOKIE_NAME = "ecb_session" SESSION_DAYS = 30 # 30 days; extend by logging in again _ADMIN_EMAIL = os.environ.get("ADMIN_EMAIL", "").strip().lower() # Secure cookies (HTTPS-only) unless ENVIRONMENT=local or ENVIRONMENT=development _SECURE_COOKIES = os.environ.get("ENVIRONMENT", "production").lower() not in ("local", "development", "dev") # --------------------------------------------------------------------------- # Role / page access # --------------------------------------------------------------------------- ROLE_LEVEL: dict = {"admin": 3, "manager": 2, "managers": 2, "staff": 1} BROWSE_RESPONSE_EDIT_ROLES = {"admin", "manager", "managers"} PAGE_ACCESS: dict = { "consultants": ["admin", "manager", "managers", "staff"], "analytics": ["admin", "manager", "managers", "staff"], "browse": ["admin", "manager", "managers", "staff"], "admin_panel": ["admin", "manager", "managers"], } def _role_key(user: Optional[dict]) -> str: return str((user or {}).get("role", "")).strip().lower() def can_edit_browse_response(user: Optional[dict]) -> bool: return _role_key(user) in BROWSE_RESPONSE_EDIT_ROLES # --------------------------------------------------------------------------- # Password helpers # --------------------------------------------------------------------------- def _hash_password(password: str, salt: str = "") -> str: if not salt: salt = os.urandom(16).hex() key = hashlib.pbkdf2_hmac( "sha256", password.encode("utf-8"), salt.encode("utf-8"), 260_000, ).hex() return salt + ":" + key def verify_password(password: str, stored: str) -> bool: if not stored or ":" not in stored: return False salt, _ = stored.split(":", 1) return _hash_password(password, salt) == stored def set_user_password(email: str, new_password: str) -> None: hashed = _hash_password(new_password) from core.database import _conn, _push_db with _conn() as con: con.execute( "UPDATE users SET password_hash = ? WHERE email = ?", (hashed, email.strip().lower()), ) _push_db() # --------------------------------------------------------------------------- # Cookie helpers — the simple, correct way # --------------------------------------------------------------------------- def set_session_cookie(response: Response, token: str) -> None: """Write the session token as a browser cookie. One line. Always works.""" response.set_cookie( key=COOKIE_NAME, value=token, max_age=SESSION_DAYS * 86400, # seconds httponly=True, # JS can't steal it samesite="lax", secure=_SECURE_COOKIES, # True on HF Spaces/Railway; set ENVIRONMENT=local to disable ) def clear_session_cookie(response: Response) -> None: """Delete the session cookie.""" response.delete_cookie(key=COOKIE_NAME, samesite="lax") # --------------------------------------------------------------------------- # Session / user helpers # --------------------------------------------------------------------------- def get_current_user(request: Request) -> Optional[dict]: """Read and validate the session cookie. Returns the user dict or None.""" token = request.cookies.get(COOKIE_NAME) if not token: return None email = db.get_session_email(token) if not email: return None user = db.get_user(email) if not user or not user.get("active"): return None return user # --------------------------------------------------------------------------- # FastAPI dependency — use with Depends(require_auth) # --------------------------------------------------------------------------- class _NotAuthenticated(Exception): """Raised by require_auth when the user is not logged in.""" pass def require_auth(request: Request) -> dict: """FastAPI dependency: returns the current user or raises _NotAuthenticated. Register the exception handler in main.py: @app.exception_handler(_NotAuthenticated) async def _not_auth(request, exc): return RedirectResponse("/login", status_code=303) """ user = get_current_user(request) if user is None: raise _NotAuthenticated() return user def require_role(page_key: str): """Return a FastAPI dependency that enforces page-level role access.""" def _check(user: dict = Depends(require_auth)) -> dict: allowed = PAGE_ACCESS.get(page_key, []) if _role_key(user) not in allowed: from fastapi import HTTPException raise HTTPException(status_code=403, detail="Access denied.") return user return _check # --------------------------------------------------------------------------- # Login # --------------------------------------------------------------------------- def attempt_login(email: str, password: str) -> Optional[dict]: """Validate credentials. Returns user dict on success, None on failure.""" email = email.strip().lower() user = db.get_user(email) if user is None or user.get("active") == 0: return None # Env-var bypass for admin (HF Spaces / Railway secret) admin_env_pw = os.environ.get("ADMIN_PASSWORD", "").strip() if admin_env_pw and email == _ADMIN_EMAIL and password == admin_env_pw: return user stored = user.get("password_hash") or "" if not verify_password(password, stored): return None return user def create_session(user: dict) -> str: """Create a DB session for the user and return the token.""" token = secrets.token_urlsafe(32) expires = datetime.now(timezone.utc) + timedelta(days=SESSION_DAYS) db.create_session(token, user["email"], expires.strftime("%Y-%m-%d %H:%M:%S")) return token