Spaces:
Running

File size: 11,113 Bytes
7e79d39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
"""
Authentication & Authorization for PanelThTuanIT.

Supports:
1. Standalone local authentication (self-hosted, no external worker needed).
   - Local user database in users.json.
   - Secure PBKDF2-HMAC-SHA256 password hashing.
   - Built-in HS256 JWT generation and validation with persistent secret key.
2. Optional fallback to external ADMIN_API_URL if configured.
"""

import base64
import hashlib
import hmac
import json
import os
import secrets
import time
import uuid
from dataclasses import dataclass
from pathlib import Path

try:
    import httpx
except ImportError:
    httpx = None

try:
    from fastapi import Request, WebSocket, HTTPException
except ImportError:
    Request = WebSocket = HTTPException = object

from config import ADMIN_API_URL, USERS_FILE, SETTINGS_FILE, JWT_SECRET_FILE


@dataclass
class AuthUser:
    """Authenticated user extracted from JWT."""
    sub: str        # user ID
    username: str
    role: str       # "admin" or "user"


# ── Secret Key Management ─────────────────────

def _get_jwt_secret() -> bytes:
    """Retrieve or generate persistent JWT secret key."""
    env_secret = os.environ.get("JWT_SECRET")
    if env_secret:
        return env_secret.encode("utf-8")

    if JWT_SECRET_FILE.exists():
        return JWT_SECRET_FILE.read_text(encoding="utf-8").strip().encode("utf-8")

    # Generate and persist new secret
    new_secret = secrets.token_hex(32)
    try:
        JWT_SECRET_FILE.parent.mkdir(parents=True, exist_ok=True)
        JWT_SECRET_FILE.write_text(new_secret, encoding="utf-8")
    except Exception:
        pass
    return new_secret.encode("utf-8")


_JWT_SECRET = _get_jwt_secret()


# ── JWT Utility Functions (HS256) ─────────────

def _b64url_encode(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).decode("utf-8").rstrip("=")


def _b64url_decode(s: str) -> bytes:
    padding = "=" * ((4 - len(s) % 4) % 4)
    return base64.urlsafe_b64decode(s + padding)


def create_jwt(user: AuthUser, expires_in: int = 86400 * 30) -> str:
    """Generate a standard HS256 JWT valid for 30 days by default."""
    header = {"alg": "HS256", "typ": "JWT"}
    payload = {
        "sub": user.sub,
        "username": user.username,
        "role": user.role,
        "exp": int(time.time()) + expires_in,
        "iat": int(time.time()),
    }

    hdr_b64 = _b64url_encode(json.dumps(header, separators=(",", ":")).encode("utf-8"))
    payload_b64 = _b64url_encode(json.dumps(payload, separators=(",", ":")).encode("utf-8"))
    signing_input = f"{hdr_b64}.{payload_b64}".encode("utf-8")

    sig = hmac.new(_JWT_SECRET, signing_input, hashlib.sha256).digest()
    sig_b64 = _b64url_encode(sig)

    return f"{hdr_b64}.{payload_b64}.{sig_b64}"


def decode_jwt(token: str) -> dict | None:
    """Verify and decode a local HS256 JWT."""
    try:
        parts = token.split(".")
        if len(parts) != 3:
            return None
        hdr_b64, payload_b64, sig_b64 = parts

        signing_input = f"{hdr_b64}.{payload_b64}".encode("utf-8")
        expected_sig = hmac.new(_JWT_SECRET, signing_input, hashlib.sha256).digest()
        actual_sig = _b64url_decode(sig_b64)

        if not hmac.compare_digest(expected_sig, actual_sig):
            return None

        payload = json.loads(_b64url_decode(payload_b64).decode("utf-8"))
        exp = payload.get("exp")
        if exp and exp < time.time():
            return None
        return payload
    except Exception:
        return None


# ── Password Hashing (PBKDF2-HMAC-SHA256) ──────

def hash_password(password: str) -> str:
    """Hash password using salt + PBKDF2-HMAC-SHA256."""
    salt = secrets.token_bytes(16)
    pw_hash = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 100_000)
    return f"{salt.hex()}${pw_hash.hex()}"


def verify_password(password: str, stored_hash: str) -> bool:
    """Verify password against salt$hash string."""
    try:
        salt_hex, hash_hex = stored_hash.split("$")
        salt = bytes.fromhex(salt_hex)
        expected_hash = bytes.fromhex(hash_hex)
        actual_hash = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, 100_000)
        return hmac.compare_digest(expected_hash, actual_hash)
    except Exception:
        return False


# ── Local User Database ───────────────────────

_users_cache: dict[str, dict] = {}
_users_mtime: float = 0.0

_settings_cache: dict = {}
_settings_mtime: float = 0.0


def load_users() -> dict[str, dict]:
    """Load users mapping from USERS_FILE with in-memory mtime cache."""
    global _users_cache, _users_mtime
    if USERS_FILE.exists():
        try:
            mtime = os.path.getmtime(USERS_FILE)
            if mtime != _users_mtime:
                _users_cache = json.loads(USERS_FILE.read_text(encoding="utf-8"))
                _users_mtime = mtime
            return _users_cache
        except Exception:
            return _users_cache
    return {}


def save_users(users: dict):
    """Save users mapping atomically to USERS_FILE and update cache."""
    global _users_cache, _users_mtime
    tmp = USERS_FILE.with_suffix(".tmp")
    tmp.parent.mkdir(parents=True, exist_ok=True)
    tmp.write_text(json.dumps(users, indent=2, default=str), encoding="utf-8")
    tmp.replace(USERS_FILE)
    _users_cache = users
    try:
        _users_mtime = os.path.getmtime(USERS_FILE)
    except Exception:
        pass


def load_settings() -> dict:
    """Load global settings with in-memory mtime cache."""
    global _settings_cache, _settings_mtime
    defaults = {
        "max_zones": 0,
        "motd": "",
        "disable_registration": False,
        "hf_token": "",
        "hf_repo": "",
    }
    if SETTINGS_FILE.exists():
        try:
            mtime = os.path.getmtime(SETTINGS_FILE)
            if mtime != _settings_mtime or not _settings_cache:
                saved = json.loads(SETTINGS_FILE.read_text(encoding="utf-8"))
                defaults.update(saved)
                _settings_cache = defaults
                _settings_mtime = mtime
            return _settings_cache
        except Exception:
            return _settings_cache or defaults
    return defaults


def save_settings(settings: dict):
    """Save settings atomically and update cache."""
    global _settings_cache, _settings_mtime
    tmp = SETTINGS_FILE.with_suffix(".tmp")
    tmp.parent.mkdir(parents=True, exist_ok=True)
    tmp.write_text(json.dumps(settings, indent=2, default=str), encoding="utf-8")
    tmp.replace(SETTINGS_FILE)
    _settings_cache = settings
    try:
        _settings_mtime = os.path.getmtime(SETTINGS_FILE)
    except Exception:
        pass


def create_user(username: str, email: str, password: str) -> AuthUser:
    """Create a new local user. First user is automatically assigned 'admin' role."""
    uname = username.strip().lower()
    if not uname or len(uname) < 3:
        raise ValueError("Username phải có ít nhất 3 ký tự")
    if not password or len(password) < 6:
        raise ValueError("Mật khẩu phải có ít nhất 6 ký tự")

    users = load_users()
    if uname in users:
        raise ValueError(f"Username '{uname}' đã tồn tại")

    email_clean = email.strip().lower()
    for u in users.values():
        if email_clean and u.get("email") == email_clean:
            raise ValueError(f"Email '{email}' đã được sử dụng")

    # First user created is admin
    role = "admin" if len(users) == 0 else "user"
    user_id = uuid.uuid4().hex

    users[uname] = {
        "id": user_id,
        "username": uname,
        "email": email_clean,
        "password_hash": hash_password(password),
        "role": role,
        "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
    }
    save_users(users)
    return AuthUser(sub=user_id, username=uname, role=role)


def authenticate_user(username_or_email: str, password: str) -> AuthUser | None:
    """Authenticate user with username/email and password."""
    target = username_or_email.strip().lower()
    users = load_users()

    found = None
    if target in users:
        found = users[target]
    else:
        for u in users.values():
            if u.get("email") == target:
                found = u
                break

    if not found:
        return None

    if not verify_password(password, found.get("password_hash", "")):
        return None

    return AuthUser(
        sub=found.get("id", ""),
        username=found.get("username", ""),
        role=found.get("role", "user"),
    )


# ── Token Verification (Local first, fallback to Worker if configured) ──

def verify_token(token: str) -> AuthUser | None:
    """Verify token locally; fall back to external worker if configured and local fails."""
    if not token:
        return None

    # 1. Try local decode first
    payload = decode_jwt(token)
    if payload and "sub" in payload and "username" in payload:
        return AuthUser(
            sub=payload["sub"],
            username=payload["username"],
            role=payload.get("role", "user"),
        )

    # 2. If ADMIN_API_URL is configured, try remote worker
    if ADMIN_API_URL:
        try:
            resp = httpx.get(
                f"{ADMIN_API_URL}/auth/me",
                headers={"Authorization": f"Bearer {token}"},
                timeout=10,
            )
            if resp.status_code == 200:
                user_data = resp.json().get("user", {})
                if user_data.get("id") and user_data.get("username"):
                    return AuthUser(
                        sub=user_data.get("id"),
                        username=user_data.get("username"),
                        role=user_data.get("role", "user"),
                    )
        except Exception:
            pass

    return None


# ── FastAPI Dependencies ──────────────────────

def get_current_user(request: Request) -> AuthUser:
    """FastAPI dependency: extract and verify JWT from Authorization header, query param, or cookie."""
    token = ""
    auth_header = request.headers.get("Authorization", "")
    if auth_header.startswith("Bearer "):
        token = auth_header[7:]
    elif "token" in request.query_params:
        token = request.query_params["token"]
    elif "panelthtuanit_token" in request.cookies:
        token = request.cookies["panelthtuanit_token"]

    if not token:
        raise HTTPException(401, "Chưa đăng nhập")

    user = verify_token(token)
    if not user:
        raise HTTPException(401, "Token không hợp lệ hoặc đã hết hạn")
    return user


def get_ws_user(websocket: WebSocket) -> AuthUser | None:
    """Extract and verify JWT from WebSocket query parameter ?token=... or cookie."""
    token = websocket.query_params.get("token", "")
    if not token:
        token = websocket.cookies.get("panelthtuanit_token", "")
    if not token:
        return None
    return verify_token(token)