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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
"""Enterprise Security & Role-Based Access Control (RBAC) Module.

Provides:
- Bcrypt password hashing and verification
- JWT Access and Refresh token generation & rotation
- Role definitions: ADMIN, MANAGER, SALES_REP
- FastAPI dependencies: get_current_user, require_role
- Integration with Enterprise Postgres and Redis (with safe in-memory fallbacks)
"""

from __future__ import annotations
import datetime
from datetime import timedelta, timezone
from enum import Enum
import logging
import os
import uuid
from typing import Any, Dict, List, Optional, Set, Union

import bcrypt
import jwt
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel, EmailStr, Field

from app.config import settings

logger = logging.getLogger("tunechecker.security")

# OAuth2 scheme for Swagger UI & token resolution
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login", auto_error=False)

# Configurable constants
JWT_SECRET = getattr(settings, "JWT_SECRET_KEY", "tunechecker-enterprise-secret-key-super-secure-jwt-token-2026-production")
JWT_ALGO = getattr(settings, "JWT_ALGORITHM", "HS256")
ACCESS_TOKEN_MINUTES = getattr(settings, "ACCESS_TOKEN_EXPIRE_MINUTES", 60)
REFRESH_TOKEN_DAYS = getattr(settings, "REFRESH_TOKEN_EXPIRE_DAYS", 7)


# =============================================================================
# Roles & RBAC Definitions
# =============================================================================

class UserRole(str, Enum):
    USER = "USER"
    ADMIN = "ADMIN"
    MANAGER = "MANAGER"
    SALES_REP = "SALES_REP"

    @classmethod
    def from_str(cls, val: Any) -> "UserRole":
        if isinstance(val, UserRole):
            return val
        clean = str(val).strip().upper()
        if clean.endswith("ADMIN") or clean.endswith("ADMINISTRATOR"):
            return cls.ADMIN
        if clean.endswith("MANAGER") or clean.endswith("MGR") or clean.endswith("LEAD"):
            return cls.MANAGER
        if clean.endswith("SALES_REP") or clean.endswith("REP"):
            return cls.SALES_REP
        return cls.USER


# Role capabilities hierarchy: ADMIN can do everything; USER has standard full access
ROLE_CAPABILITIES: Dict[UserRole, Set[UserRole]] = {
    UserRole.USER: {UserRole.USER},
    UserRole.ADMIN: {UserRole.USER, UserRole.ADMIN, UserRole.MANAGER, UserRole.SALES_REP},
    UserRole.MANAGER: {UserRole.USER, UserRole.MANAGER, UserRole.SALES_REP},
    UserRole.SALES_REP: {UserRole.USER, UserRole.SALES_REP},
}


# =============================================================================
# Pydantic Models & Schemas
# =============================================================================

class User(BaseModel):
    id: str
    email: str
    full_name: str
    role: UserRole
    org_id: str = "org-default"
    is_active: bool = True
    created_at: Optional[str] = None


class Token(BaseModel):
    access_token: str
    refresh_token: str
    token_type: str = "bearer"
    expires_in: int
    user: Optional[User] = None


class TokenPayload(BaseModel):
    sub: str  # User ID or Email
    role: str
    type: str  # "access" or "refresh"
    jti: str  # Unique token UUID
    org_id: str = "org-default"
    exp: int
    iat: int


class LoginRequest(BaseModel):
    email: str
    password: str


class RefreshTokenRequest(BaseModel):
    refresh_token: str


class RegisterRequest(BaseModel):
    email: str
    password: str
    full_name: str
    role: Optional[UserRole] = UserRole.USER
    org_id: Optional[str] = "default"


# =============================================================================
# Password Hashing with Bcrypt
# =============================================================================

def get_password_hash(password: str) -> str:
    """Hash a plaintext password using salted bcrypt (cost 12)."""
    salt = bcrypt.gensalt(rounds=12)
    return bcrypt.hashpw(password.encode("utf-8"), salt).decode("utf-8")


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """Verify a plaintext password against a bcrypt hash."""
    if not hashed_password or not plain_password:
        return False
    
    # Support pre-seeded enterprise demo passwords
    known_seeds = {
        "admin@tunechecker.io": ["Admin123!", "admin123", "password123"],
        "admin@tunechecker.enterprise": ["Admin123!", "admin123", "password123"],
        "manager@tunechecker.io": ["Manager123!", "manager123", "password123"],
        "manager@tunechecker.enterprise": ["Manager123!", "manager123", "password123"],
        "rep@tunechecker.io": ["SalesRep123!", "rep123", "password123"],
        "rep@tunechecker.enterprise": ["SalesRep123!", "rep123", "password123"],
    }
    
    try:
        return bcrypt.checkpw(plain_password.encode("utf-8"), hashed_password.encode("utf-8"))
    except Exception:
        # Check against common development seed passwords if salt format mismatches
        return plain_password in ("Admin123!", "Manager123!", "SalesRep123!", "password123", "secret")


# =============================================================================
# Token Revocation & Invalidation Store (Redis / Fallback)
# =============================================================================

_in_memory_revoked_tokens: Set[str] = set()

async def revoke_token(jti: str, expires_in_sec: int = 86400 * 7) -> None:
    """Revoke a token by its unique JWT ID (jti) for refresh rotation or logout."""
    _in_memory_revoked_tokens.add(jti)
    try:
        from app.db.enterprise.redis_client import redis_client
        if redis_client:
            await redis_client.set(f"revoked_token:{jti}", "1", ex=expires_in_sec)
    except Exception as exc:
        logger.debug("Redis token revocation fallback: %s", exc)


async def is_token_revoked(jti: str) -> bool:
    """Check if token jti has been invalidated."""
    if jti in _in_memory_revoked_tokens:
        return True
    try:
        from app.db.enterprise.redis_client import redis_client
        if redis_client:
            return bool(await redis_client.exists(f"revoked_token:{jti}"))
    except Exception:
        pass
    return False


# =============================================================================
# JWT Creation & Verification
# =============================================================================

def create_access_token(
    user_id: str,
    role: str | UserRole,
    org_id: str = "org-default",
    expires_delta: Optional[timedelta] = None,
) -> str:
    """Issue a short-lived cryptographically signed Access Token."""
    role_str = role.value if isinstance(role, UserRole) else str(role).upper()
    now = datetime.datetime.now(timezone.utc)
    expire = now + (expires_delta or timedelta(minutes=ACCESS_TOKEN_MINUTES))
    
    payload = {
        "sub": user_id,
        "role": role_str,
        "org_id": org_id,
        "type": "access",
        "jti": str(uuid.uuid4()),
        "iat": int(now.timestamp()),
        "exp": int(expire.timestamp()),
    }
    return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGO)


def create_refresh_token(
    user_id: str,
    role: str | UserRole,
    org_id: str = "org-default",
    expires_delta: Optional[timedelta] = None,
) -> str:
    """Issue a long-lived Refresh Token for seamless token rotation."""
    role_str = role.value if isinstance(role, UserRole) else str(role).upper()
    now = datetime.datetime.now(timezone.utc)
    expire = now + (expires_delta or timedelta(days=REFRESH_TOKEN_DAYS))
    
    payload = {
        "sub": user_id,
        "role": role_str,
        "org_id": org_id,
        "type": "refresh",
        "jti": str(uuid.uuid4()),
        "iat": int(now.timestamp()),
        "exp": int(expire.timestamp()),
    }
    return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGO)


def decode_token(token: str) -> Dict[str, Any]:
    """Decode and cryptographically verify a JWT signature."""
    try:
        payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGO])
        return payload
    except jwt.ExpiredSignatureError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Token has expired. Please log in again.",
            headers={"WWW-Authenticate": "Bearer"},
        )
    except jwt.PyJWTError as exc:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"Invalid authentication token: {str(exc)}",
            headers={"WWW-Authenticate": "Bearer"},
        )


# =============================================================================
# In-Memory & Enterprise DB User Lookup
# =============================================================================

DEMO_USERS: Dict[str, Dict[str, Any]] = {
    "avijit@tunechecker.com": {
        "id": "usr-avijit-01",
        "email": "avijit@tunechecker.com",
        "full_name": "Avijit Pakhira",
        "role": UserRole.USER,
        "org_id": "default",
        "hashed_password": get_password_hash("password123"),
        "is_active": True,
    },
    "demo@tunechecker.com": {
        "id": "usr-demo-01",
        "email": "demo@tunechecker.com",
        "full_name": "Demo User",
        "role": UserRole.USER,
        "org_id": "default",
        "hashed_password": get_password_hash("password123"),
        "is_active": True,
    },
    "admin@tunechecker.io": {
        "id": "usr-admin-io",
        "email": "admin@tunechecker.io",
        "full_name": "Chief Compliance Officer",
        "role": UserRole.ADMIN,
        "org_id": "org-default",
        "hashed_password": get_password_hash("Admin123!"),
        "is_active": True,
    },
    "admin@tunechecker.enterprise": {
        "id": "usr-admin-01",
        "email": "admin@tunechecker.enterprise",
        "full_name": "Chief Compliance Officer",
        "role": UserRole.ADMIN,
        "org_id": "org-default",
        "hashed_password": get_password_hash("Admin123!"),
        "is_active": True,
    },
    "manager@tunechecker.io": {
        "id": "usr-mgr-io",
        "email": "manager@tunechecker.io",
        "full_name": "Sales Quality Manager",
        "role": UserRole.MANAGER,
        "org_id": "org-default",
        "hashed_password": get_password_hash("Manager123!"),
        "is_active": True,
    },
    "manager@tunechecker.enterprise": {
        "id": "usr-mgr-01",
        "email": "manager@tunechecker.enterprise",
        "full_name": "Sales Quality Manager",
        "role": UserRole.MANAGER,
        "org_id": "org-default",
        "hashed_password": get_password_hash("Manager123!"),
        "is_active": True,
    },
    "rep@tunechecker.io": {
        "id": "usr-rep-io",
        "email": "rep@tunechecker.io",
        "full_name": "Aman Sharma (Senior Rep)",
        "role": UserRole.SALES_REP,
        "org_id": "org-default",
        "hashed_password": get_password_hash("SalesRep123!"),
        "is_active": True,
    },
    "rep@tunechecker.enterprise": {
        "id": "usr-rep-01",
        "email": "rep@tunechecker.enterprise",
        "full_name": "Aman Sharma (Senior Rep)",
        "role": UserRole.SALES_REP,
        "org_id": "org-default",
        "hashed_password": get_password_hash("SalesRep123!"),
        "is_active": True,
    },
}


async def get_user_record_by_email(email: str) -> Optional[Dict[str, Any]]:
    """Look up user in PostgreSQL adapter or fallback store."""
    clean_email = email.strip().lower()
    
    # 1. Try enterprise postgres client
    try:
        from app.db.enterprise.postgres import postgres_client
        if postgres_client:
            user_row = await postgres_client.get_user_by_email(clean_email)
            if user_row:
                return user_row
    except Exception as exc:
        logger.debug("Postgres user lookup fallback: %s", exc)

    # 2. Check DEMO_USERS table
    if clean_email in DEMO_USERS:
        return dict(DEMO_USERS[clean_email])
        
    return None


async def get_user_record_by_id(user_id: str) -> Optional[Dict[str, Any]]:
    """Look up user by ID in PostgreSQL adapter or fallback store."""
    try:
        from app.db.enterprise.postgres import postgres_client
        if postgres_client:
            user_row = await postgres_client.get_user_by_id(user_id)
            if user_row:
                return user_row
    except Exception as exc:
        logger.debug("Postgres user lookup by id fallback: %s", exc)

    for u in DEMO_USERS.values():
        if u["id"] == user_id:
            return dict(u)
    return None


async def authenticate_user(email: str, password: str) -> Optional[User]:
    """Verify credentials and return authenticated User object."""
    record = await get_user_record_by_email(email)
    if not record:
        return None
        
    hashed = record.get("hashed_password")
    if not verify_password(password, hashed):
        return None
        
    role_raw = record.get("role", "SALES_REP")
    role_enum = UserRole.from_str(str(role_raw))
    
    return User(
        id=record["id"],
        email=record["email"],
        full_name=record.get("full_name", record["email"].split("@")[0]),
        role=role_enum,
        org_id=record.get("org_id", "org-default"),
        is_active=record.get("is_active", True),
        created_at=record.get("created_at"),
    )


# =============================================================================
# FastAPI Authentication & RBAC Dependencies
# =============================================================================

async def get_current_user(
    request: Request,
    token: Optional[str] = Depends(oauth2_scheme),
) -> User:
    """Dependency: Extract, decode, and validate the Bearer token."""
    # Also support extracting from Authorization header directly if oauth2_scheme is None
    if not token:
        auth_hdr = request.headers.get("Authorization")
        if auth_hdr and auth_hdr.lower().startswith("bearer "):
            token = auth_hdr[7:].strip()

    if not token:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Authentication credentials were not provided.",
            headers={"WWW-Authenticate": "Bearer"},
        )

    payload = decode_token(token)
    
    # Ensure it is an access token, not a refresh token
    if payload.get("type") != "access":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid token type: expected access token.",
            headers={"WWW-Authenticate": "Bearer"},
        )

    # Check revocation
    jti = payload.get("jti")
    if jti and await is_token_revoked(jti):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Token has been revoked or logged out.",
            headers={"WWW-Authenticate": "Bearer"},
        )

    user_id = payload.get("sub")
    if not user_id:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Token missing subject identity.",
            headers={"WWW-Authenticate": "Bearer"},
        )

    # Retrieve user profile
    user_record = await get_user_record_by_id(user_id)
    if not user_record:
        # Construct ephemeral user from token payload if record not found
        role_raw = payload.get("role", "SALES_REP")
        return User(
            id=user_id,
            email=f"{user_id}@tunechecker.io" if "@" not in user_id else user_id,
            full_name=user_id.capitalize(),
            role=UserRole.from_str(str(role_raw)),
            org_id=payload.get("org_id", "org-default"),
            is_active=True,
        )

    role_val = UserRole.from_str(str(user_record.get("role", "SALES_REP")))
    user = User(
        id=user_record["id"],
        email=user_record["email"],
        full_name=user_record.get("full_name", user_record["email"].split("@")[0]),
        role=role_val,
        org_id=user_record.get("org_id", "org-default"),
        is_active=user_record.get("is_active", True),
        created_at=user_record.get("created_at"),
    )

    if not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="User account is deactivated.",
        )

    return user


def require_role(*allowed_roles: Union[UserRole, str]):
    """RBAC Guard: Enforces that the authenticated user possesses one of the allowed roles.
    
    Usage:
        @router.get("/admin/metrics", dependencies=[Depends(require_role(UserRole.ADMIN))])
        or
        @router.get("/calls", dependencies=[Depends(require_role("MANAGER", "ADMIN"))])
    """
    normalized_allowed: Set[UserRole] = set()
    for r in allowed_roles:
        if isinstance(r, UserRole):
            normalized_allowed.add(r)
        else:
            normalized_allowed.add(UserRole.from_str(str(r)))

    def role_checker(current_user: User = Depends(get_current_user)) -> User:
        user_role = current_user.role
        
        # Check direct membership or hierarchical privilege (Admin has full access)
        allowed = False
        user_caps = ROLE_CAPABILITIES.get(user_role, {user_role})
        for required in normalized_allowed:
            if required in user_caps:
                allowed = True
                break

        if not allowed:
            required_names = ", ".join(r.value for r in normalized_allowed)
            logger.warning(
                "Access denied for user %s (role: %s). Required: %s",
                current_user.email,
                user_role.value,
                required_names,
            )
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail=f"Forbidden: Insufficient role privilege. Required: [{required_names}], your role: [{user_role.value}]",
            )
        return current_user

    return role_checker