Spaces:
Paused

File size: 2,748 Bytes
3a72608
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b769fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a72608
 
 
 
 
 
 
8b769fb
3a72608
 
 
8b769fb
3a72608
 
 
8b769fb
3a72608
8b769fb
 
 
 
 
 
 
 
 
 
 
 
 
3a72608
 
 
 
 
 
8b769fb
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from datetime import datetime, timedelta, timezone
from typing import Any

import jwt
from fastapi import Header, HTTPException

from .config import get_settings


ALGORITHM = "HS256"



def _encode(payload: dict[str, Any]) -> str:
    settings = get_settings()
    return jwt.encode(payload, settings.app_jwt_secret, algorithm=ALGORITHM)



def _decode(token: str) -> dict[str, Any]:
    settings = get_settings()
    try:
        return jwt.decode(token, settings.app_jwt_secret, algorithms=[ALGORITHM])
    except jwt.ExpiredSignatureError as exc:
        raise HTTPException(status_code=401, detail="Session login sudah expired. Silakan login ulang.") from exc
    except jwt.InvalidTokenError as exc:
        raise HTTPException(status_code=401, detail="Token login tidak valid.") from exc



def create_session_token(access_code: str, user_name: str, model_mode: int) -> str:
    settings = get_settings()
    now = datetime.now(timezone.utc)
    payload = {
        "sub": access_code,
        "name": user_name,
        "model_mode": model_mode,
        "token_type": "user",
        "iat": int(now.timestamp()),
        "exp": int((now + timedelta(hours=settings.access_token_ttl_hours)).timestamp()),
    }
    return _encode(payload)



def create_admin_token(username: str) -> str:
    settings = get_settings()
    now = datetime.now(timezone.utc)
    payload = {
        "sub": username,
        "token_type": "admin",
        "iat": int(now.timestamp()),
        "exp": int((now + timedelta(hours=settings.admin_token_ttl_hours)).timestamp()),
    }
    return _encode(payload)



def decode_session_token(token: str) -> dict[str, Any]:
    return _decode(token)


async def get_current_session(authorization: str | None = Header(default=None)) -> dict[str, Any]:
    if not authorization or not authorization.lower().startswith("bearer "):
        raise HTTPException(status_code=401, detail="Authorization Bearer token wajib dikirim.")
    token = authorization.split(" ", 1)[1].strip()
    payload = decode_session_token(token)
    if payload.get("token_type") != "user":
        raise HTTPException(status_code=401, detail="Token user tidak valid.")
    return payload


async def get_current_admin_session(authorization: str | None = Header(default=None)) -> dict[str, Any]:
    if not authorization or not authorization.lower().startswith("bearer "):
        raise HTTPException(status_code=401, detail="Authorization Bearer token admin wajib dikirim.")
    token = authorization.split(" ", 1)[1].strip()
    payload = decode_session_token(token)
    if payload.get("token_type") != "admin":
        raise HTTPException(status_code=401, detail="Token admin tidak valid.")
    return payload