File size: 6,955 Bytes
59e06b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3d6c3c
59e06b1
f3d6c3c
 
 
 
59e06b1
 
 
 
 
67e8d0a
 
 
59e06b1
 
67e8d0a
 
 
 
59e06b1
 
67e8d0a
 
 
 
 
 
 
 
59e06b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3d6c3c
59e06b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67e8d0a
59e06b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
"""
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