File size: 9,506 Bytes
4c9881b
adbcca0
4c9881b
adbcca0
4c9881b
adbcca0
4c9881b
 
 
adbcca0
 
4c9881b
 
 
adbcca0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9881b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
adbcca0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9881b
 
adbcca0
4c9881b
adbcca0
 
 
4c9881b
 
adbcca0
 
 
4c9881b
adbcca0
 
 
 
 
 
 
 
 
4c9881b
adbcca0
 
 
 
 
4c9881b
adbcca0
4c9881b
adbcca0
 
 
 
 
 
4c9881b
adbcca0
4c9881b
 
 
 
adbcca0
4c9881b
adbcca0
 
4c9881b
adbcca0
 
 
 
 
 
4c9881b
adbcca0
4c9881b
 
 
adbcca0
 
 
 
 
 
4c9881b
 
 
 
 
 
 
 
adbcca0
4c9881b
 
adbcca0
 
 
 
 
 
 
 
 
 
 
4c9881b
 
adbcca0
4c9881b
 
 
 
adbcca0
 
 
4c9881b
 
adbcca0
 
 
4c9881b
adbcca0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9881b
 
adbcca0
4c9881b
 
 
 
adbcca0
 
 
4c9881b
 
adbcca0
 
 
 
4c9881b
adbcca0
4c9881b
 
adbcca0
 
 
 
 
 
 
4cde766
 
adbcca0
 
4cde766
adbcca0
4cde766
adbcca0
 
 
4cde766
adbcca0
4cde766
adbcca0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c9881b
 
 
adbcca0
 
 
 
 
 
 
 
 
 
 
 
 
4c9881b
adbcca0
 
 
 
 
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
# ============================================================
# app/core/security.py - JWT & Password Management (Secure)
# ============================================================

import jwt
import uuid
import logging
from datetime import datetime, timedelta, timezone
from typing import Optional, Dict, Any
from passlib.context import CryptContext
from app.config import settings

logger = logging.getLogger(__name__)

# ============================================================
# Startup Validation
# ============================================================

def validate_jwt_config():
    """Validate JWT configuration at startup - FAIL if secrets not set"""
    if not settings.JWT_SECRET:
        raise RuntimeError(
            "CRITICAL: JWT_SECRET environment variable must be set! "
            "Cannot start application without a secure JWT secret."
        )
    if not settings.JWT_REFRESH_SECRET:
        raise RuntimeError(
            "CRITICAL: JWT_REFRESH_SECRET environment variable must be set! "
            "Cannot start application without a secure refresh token secret."
        )
    if settings.JWT_SECRET == settings.JWT_REFRESH_SECRET:
        raise RuntimeError(
            "CRITICAL: JWT_SECRET and JWT_REFRESH_SECRET must be different!"
        )
    logger.info("✅ JWT configuration validated")

# ============================================================
# Password Hashing
# ============================================================

pwd_context = CryptContext(
    schemes=["bcrypt"],
    deprecated="auto",
    bcrypt__rounds=settings.BCRYPT_ROUNDS,
)

def hash_password(password: str) -> str:
    """Hash password using bcrypt"""
    try:
        return pwd_context.hash(password)
    except Exception as e:
        logger.error(f"Error hashing password: {str(e)}")
        raise

def verify_password(plain_password: str, hashed_password: str) -> bool:
    """Verify password against hash"""
    try:
        return pwd_context.verify(plain_password, hashed_password)
    except Exception as e:
        logger.error(f"Error verifying password: {str(e)}")
        return False

# ============================================================
# Password Strength Validation
# ============================================================

import re

def validate_password_strength(password: str) -> None:
    """
    Validate password meets security requirements.
    Raises ValueError if password is too weak.
    """
    errors = []
    
    if len(password) < 8:
        errors.append("at least 8 characters")
    if not re.search(r"[A-Z]", password):
        errors.append("an uppercase letter")
    if not re.search(r"[a-z]", password):
        errors.append("a lowercase letter")
    if not re.search(r"\d", password):
        errors.append("a number")
    
    if errors:
        raise ValueError(f"Password must contain {', '.join(errors)}")

# ============================================================
# JWT Token Management - Dual Token Strategy
# ============================================================

def _create_token(
    data: Dict[str, Any],
    secret: str,
    expires_delta: timedelta,
    token_type: str,
) -> str:
    """
    Internal: Create JWT token with full security claims
    """
    now = datetime.now(timezone.utc)
    
    to_encode = data.copy()
    to_encode.update({
        "exp": now + expires_delta,
        "iat": now,                          # Issued At
        "jti": str(uuid.uuid4()),            # JWT ID (for blacklisting)
        "iss": settings.JWT_ISSUER,          # Issuer
        "aud": settings.JWT_AUDIENCE,        # Audience
        "type": token_type,
    })
    
    encoded_jwt = jwt.encode(
        to_encode,
        secret,
        algorithm=settings.JWT_ALGORITHM,
    )
    
    return encoded_jwt


def _verify_token(
    token: str,
    secret: str,
    expected_type: str,
) -> Optional[Dict[str, Any]]:
    """
    Internal: Verify and decode JWT token with full validation
    """
    try:
        payload = jwt.decode(
            token,
            secret,
            algorithms=[settings.JWT_ALGORITHM],
            issuer=settings.JWT_ISSUER,
            audience=settings.JWT_AUDIENCE,
        )
        
        # Verify token type
        if payload.get("type") != expected_type:
            logger.warning(f"Token type mismatch: expected {expected_type}, got {payload.get('type')}")
            return None
        
        return payload
        
    except jwt.ExpiredSignatureError:
        logger.warning("Token has expired")
        return None
    except jwt.InvalidIssuerError:
        logger.warning("Invalid token issuer")
        return None
    except jwt.InvalidAudienceError:
        logger.warning("Invalid token audience")
        return None
    except jwt.InvalidTokenError as e:
        logger.warning(f"Invalid token: {str(e)}")
        return None
    except Exception as e:
        logger.error(f"Error verifying token: {str(e)}")
        return None

# ============================================================
# Access Token (Short-lived: 15 minutes)
# ============================================================

def create_access_token(
    user_id: str,
    email: Optional[str],
    phone: Optional[str],
    role: str,
) -> str:
    """
    Create short-lived access token (15 minutes).
    Use this for API authentication.
    """
    return _create_token(
        data={
            "user_id": user_id,
            "sub": user_id,  # Standard JWT subject claim
            "email": email,
            "phone": phone,
            "role": role,
        },
        secret=settings.JWT_SECRET,
        expires_delta=timedelta(minutes=settings.JWT_ACCESS_EXPIRY_MINUTES),
        token_type="access",
    )

def verify_access_token(token: str) -> Optional[Dict[str, Any]]:
    """Verify and decode access token"""
    return _verify_token(token, settings.JWT_SECRET, "access")

# ============================================================
# Refresh Token (Long-lived: 30 days)
# ============================================================

def create_refresh_token(
    user_id: str,
    email: Optional[str],
    phone: Optional[str],
    role: str,
) -> str:
    """
    Create long-lived refresh token (30 days).
    Use this to obtain new access tokens without re-login.
    """
    return _create_token(
        data={
            "user_id": user_id,
            "sub": user_id,
            "email": email,
            "phone": phone,
            "role": role,
        },
        secret=settings.JWT_REFRESH_SECRET,  # Different secret!
        expires_delta=timedelta(days=settings.JWT_REFRESH_EXPIRY_DAYS),
        token_type="refresh",
    )

def verify_refresh_token(token: str) -> Optional[Dict[str, Any]]:
    """Verify and decode refresh token"""
    return _verify_token(token, settings.JWT_REFRESH_SECRET, "refresh")

# ============================================================
# Token Pair Creation (Login Response)
# ============================================================

def create_token_pair(
    user_id: str,
    email: Optional[str],
    phone: Optional[str],
    role: str,
) -> Dict[str, str]:
    """
    Create long-lived access token for login.
    Returns dict with access_token.
    """
    access_token = create_access_token(user_id, email, phone, role)
    # refresh_token = create_refresh_token(user_id, email, phone, role) # DEPRECATED
    
    logger.info(f"Long-lived token created for user: {user_id}")
    
    return {
        "access_token": access_token,
        # "refresh_token": refresh_token, # DEPRECATED
        "token_type": "bearer",
        "expires_in": settings.JWT_ACCESS_EXPIRY_MINUTES * 60,  # In seconds (60 days)
    }

# ============================================================
# Password Reset Token (Short-lived: 10 minutes)
# ============================================================

def create_reset_token(identifier: str) -> str:
    """Create short-lived password reset token (10 minutes)"""
    return _create_token(
        data={
            "identifier": identifier,
            "purpose": "password_reset",
        },
        secret=settings.JWT_SECRET,
        expires_delta=timedelta(minutes=settings.JWT_RESET_EXPIRY_MINUTES),
        token_type="reset",
    )

def verify_reset_token(token: str) -> Optional[Dict[str, Any]]:
    """Verify and decode reset token"""
    payload = _verify_token(token, settings.JWT_SECRET, "reset")
    if payload and payload.get("purpose") != "password_reset":
        logger.warning("Reset token has wrong purpose")
        return None
    return payload

# ============================================================
# Legacy Aliases (for backward compatibility)
# ============================================================

def create_login_token(user_id: str, email: Optional[str], phone: Optional[str], role: str) -> str:
    """DEPRECATED: Use create_access_token() instead"""
    logger.warning("create_login_token is deprecated, use create_access_token")
    return create_access_token(user_id, email, phone, role)

def decode_reset_token(token: str) -> Optional[Dict[str, Any]]:
    """DEPRECATED: Use verify_reset_token() instead"""
    return verify_reset_token(token)

def decode_access_token(token: str) -> Optional[Dict[str, Any]]:
    """DEPRECATED: Use verify_access_token() instead"""
    return verify_access_token(token)

# Alias for backward compatibility
verify_token = verify_access_token