File size: 6,652 Bytes
3a006a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Security utilities β€” password hashing, JWT, rate limiting.



Zero-cost: bcrypt, PyJWT, in-memory rate limiter.

No Redis. No external services. Free for 10K users.

"""

import hashlib
import secrets
import time
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional

import jwt as pyjwt
import httpx
from loguru import logger
from passlib.context import CryptContext

from app.config.settings import settings


# ─── Password Hashing ───────────────────────────────────────────────────────

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def hash_password(password: str) -> str:
    return pwd_context.hash(password)

def verify_password(plain: str, hashed: str) -> bool:
    try:
        return pwd_context.verify(plain, hashed)
    except Exception:
        return False  # Sentinel values like "GOOGLE_OAUTH" won't crash

def hash_legacy_gas_password(password: str, email: str, salt: str = "BRIGAWAN_AUTH_SALT_2026") -> str:
    """Replicate GAS hashPassword() for backward compatibility."""
    pre_hash = hashlib.sha256((password + email.lower()).encode()).hexdigest()
    return hashlib.sha256((pre_hash + salt).encode()).hexdigest()


# ─── JWT ────────────────────────────────────────────────────────────────────

def create_access_token(subject: str, email: str, role: str = "talent",

                        expires_delta: Optional[timedelta] = None) -> str:
    now = datetime.now(timezone.utc)
    payload = {
        "sub": subject, "email": email, "role": role,
        "iat": now, "exp": now + (expires_delta or timedelta(hours=settings.jwt_expiry_hours)),
    }
    return pyjwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)

def decode_access_token(token: str) -> Optional[Dict[str, Any]]:
    try:
        return pyjwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm])
    except (pyjwt.ExpiredSignatureError, pyjwt.InvalidTokenError):
        return None

async def verify_supabase_token(token: str) -> Optional[Dict[str, Any]]:
    """Verify standard JWT token directly with Supabase Auth server."""
    if not settings.supabase_url or not settings.supabase_anon_key:
        logger.warning("Supabase URL or Anon Key is missing from settings")
        return None
    try:
        async with httpx.AsyncClient(timeout=10.0) as client:
            headers = {
                "apikey": settings.supabase_anon_key,
                "Authorization": f"Bearer {token}"
            }
            response = await client.get(f"{settings.supabase_url}/auth/v1/user", headers=headers)
            if response.status_code == 200:
                data = response.json()
                email = data.get("email")
                user_id = data.get("id")
                
                app_metadata = data.get("app_metadata", {})
                user_metadata = data.get("user_metadata", {})
                role = user_metadata.get("role") or app_metadata.get("role") or "talent"
                
                return {
                    "sub": user_id,
                    "email": email,
                    "role": role,
                    "name": user_metadata.get("full_name") or user_metadata.get("name") or "User"
                }
            else:
                logger.warning(f"Supabase auth check returned status {response.status_code}: {response.text}")
    except Exception as e:
        logger.error(f"Failed to verify token with Supabase: {str(e)}")
    return None

def generate_session_token() -> str:
    return secrets.token_urlsafe(32)


# ─── In-Memory Rate Limiter ─────────────────────────────────────────────────

class RateLimiter:
    """Sliding-window in-memory rate limiter.

    

    Max 15K tracked IPs. Oldest entries evicted when limit exceeded.

    Free tier: 100 req/hr. Authenticated: up to 2000 req/hr.

    """

    def __init__(self, max_requests: int = 100, window_seconds: int = 3600, max_buckets: int = 15000):
        self.max_requests = max_requests
        self.window_seconds = window_seconds
        self.max_buckets = max_buckets
        self._buckets: Dict[str, list] = {}
        self._prune_counter = 0
        self._prune_threshold = 100

    def is_allowed(self, key: str, limit: Optional[int] = None) -> bool:
        """Check if request is allowed under the given (or default) limit.

        

        Args:

            key: The rate-limit bucket key (e.g. client IP).

            limit: Optional per-request limit override. If None, uses self.max_requests.

        """
        now = time.time()
        cutoff = now - self.window_seconds
        effective_limit = limit if limit is not None else self.max_requests

        # Evict oldest bucket if over limit
        if len(self._buckets) >= self.max_buckets and key not in self._buckets:
            oldest = min(self._buckets.keys(), key=lambda k: self._buckets[k][-1] if self._buckets[k] else 0)
            del self._buckets[oldest]

        if key not in self._buckets:
            self._buckets[key] = []

        # Prune expired timestamps
        bucket = [t for t in self._buckets[key] if t > cutoff]
        self._buckets[key] = bucket

        if len(bucket) >= effective_limit:
            return False

        self._buckets[key].append(now)

        self._prune_counter += 1
        if self._prune_counter >= self._prune_threshold:
            self._prune()
            self._prune_counter = 0

        return True

    def _prune(self):
        now = time.time()
        cutoff = now - self.window_seconds * 2
        stale = [k for k, v in self._buckets.items() if not v or max(v) < cutoff]
        for k in stale:
            del self._buckets[k]

    def get_remaining(self, key: str, limit: Optional[int] = None) -> int:
        effective_limit = limit if limit is not None else self.max_requests
        if key not in self._buckets:
            return effective_limit
        bucket = [t for t in self._buckets[key] if t > time.time() - self.window_seconds]
        return max(0, effective_limit - len(bucket))


rate_limiter = RateLimiter(max_requests=100, window_seconds=3600)