File size: 1,949 Bytes
30698e9
2c8882f
 
302fbfe
30698e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25a6568
30698e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from datetime import datetime, timedelta
import jwt

# ===================== JWT Config =====================
def get_jwt_config():
    """Get JWT configuration based on environment"""
    # Check if we're in HuggingFace Space
    if os.getenv("SPACE_ID"):
        # Cloud mode - use secrets from environment
        jwt_secret = os.getenv("JWT_SECRET")
        if not jwt_secret:
            log("⚠️  WARNING: JWT_SECRET not found in environment, using fallback")
            jwt_secret = "flare-admin-secret-key-change-in-production"  # Fallback
    else:
        # On-premise mode - use .env file
        from dotenv import load_dotenv
        load_dotenv()
        jwt_secret = os.getenv("JWT_SECRET", "flare-admin-secret-key-change-in-production")
    
    return {
        "secret": jwt_secret,
        "algorithm": os.getenv("JWT_ALGORITHM", "HS256"),
        "expiration_hours": int(os.getenv("JWT_EXPIRATION_HOURS", "24"))
    }

# ===================== Auth Helpers =====================
def create_token(username: str) -> str:
    """Create JWT token for user"""
    config = get_jwt_config()
    expiry = datetime.now(timezone.utc) + timedelta(hours=config["expiration_hours"])
    
    payload = {
        "sub": username,
        "exp": expiry,
        "iat": datetime.now(timezone.utc)
    }
    
    return jwt.encode(payload, config["secret"], algorithm=config["algorithm"])

def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)) -> str:
    """Verify JWT token and return username"""
    token = credentials.credentials
    config = get_jwt_config()
    
    try:
        payload = jwt.decode(token, config["secret"], algorithms=[config["algorithm"]])
        return payload["sub"]
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token expired")
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="Invalid token")