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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
# app/api/auth.py
"""

Authentication endpoints β€” production-hardened.



Endpoints:

  POST /api/auth/register        β€” create account, returns token pair

  POST /api/auth/login           β€” authenticate, returns token pair

  POST /api/auth/refresh         β€” rotate refresh token

  POST /api/auth/logout          β€” blacklist access token, clear refresh token

  POST /api/auth/change-password β€” change password with old password verification

  GET  /api/auth/profile         β€” get current user profile

  PATCH /api/auth/profile        β€” update name / coach_personality

"""

import logging
from datetime import timezone

from fastapi import APIRouter, Depends, HTTPException, Request, status
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.core.security import (
    blacklist_token,
    create_token_pair_with_session,
    generate_selector_verifier,
    verify_verifier,
    set_cached_versions,
    get_current_token,
    get_current_user,
    hash_password,
    record_failed_login,
    reset_failed_logins,
    verify_password,
)
from datetime import datetime, timedelta
from app.core.limiter import limiter
from app.core.redis_client import get_redis as _get_redis
from app.models.user import User
from app.schemas.auth import (
    ChangePasswordRequest,
    LoginRequest,
    MessageResponse,
    RefreshTokenRequest,
    RefreshTokenResponse,
    RegisterRequest,
    TokenResponse,
    UpdateProfileRequest,
    UserProfile,
)

logger = logging.getLogger("hale.api.auth")
router = APIRouter(prefix="/api/auth", tags=["Authentication"])


# ──────────────────────────────────────────────
# Register
# ──────────────────────────────────────────────

@router.post(

    "/register",

    response_model=TokenResponse,

    status_code=status.HTTP_201_CREATED,

    summary="Create a new user account",

)
@limiter.limit("3/minute")
def register(

    request: Request,

    payload: RegisterRequest,

    db: Session = Depends(get_db),

) -> TokenResponse:
    # Username uniqueness
    if db.query(User).filter(User.user_id == payload.user_id).first():
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail=f"Username '{payload.user_id}' is already taken",
        )

    # Email uniqueness (if provided)
    if payload.email:
        if db.query(User).filter(User.email == payload.email).first():
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT,
                detail="Email already registered",
            )

    user = User(
        user_id=payload.user_id,
        email=payload.email,
        name=payload.name or payload.user_id,
        hashed_password=hash_password(payload.password),
        last_login_at=datetime.now(timezone.utc),   # Set on creation so inactivity decay works
    )
    db.add(user)
    db.commit()
    db.refresh(user)

    # Issue token pair with active UserSession
    from app.models.session import UserSession
    tokens = create_token_pair_with_session(user.user_id, 1, user.user_version)
    user_session = UserSession(
        user_id=user.user_id,
        selector=tokens["selector"],
        verifier_hash=tokens["verifier_hash"],
        session_version=1,
        ip_address=request.client.host if request.client else None,
        user_agent=request.headers.get("User-Agent"),
        is_compromised=False,
        expires_at=datetime.now(timezone.utc) + timedelta(days=30),
    )
    db.add(user_session)
    db.commit()

    redis = _get_redis()
    if redis:
        set_cached_versions(user.user_id, tokens["selector"], user.user_version, 1)

    logger.info("New user registered: %s", user.user_id)

    return TokenResponse(
        access_token=tokens["access_token"],
        refresh_token=tokens["refresh_token"],
        user_id=user.user_id,
        name=user.name,
    )


async def get_login_payload(request: Request) -> LoginRequest:
    content_type = request.headers.get("content-type", "")
    if "application/x-www-form-urlencoded" in content_type:
        form_data = await request.form()
        user_id = form_data.get("username") or form_data.get("user_id")
        password = form_data.get("password")
        if not user_id or not password:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Missing username or password in form data",
            )
        return LoginRequest(user_id=str(user_id), password=str(password))
    else:
        try:
            body = await request.json()
            return LoginRequest(**body)
        except Exception:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="Invalid JSON payload or content-type",
            )


@router.post(

    "/login",

    response_model=TokenResponse,

    summary="Login and receive a JWT token pair",

)
@limiter.limit("5/minute")
def login(

    request: Request,

    payload: LoginRequest = Depends(get_login_payload),

    db: Session = Depends(get_db),

) -> TokenResponse:
    # Find user by user_id OR email (case-insensitive)
    user_id_lower = payload.user_id.lower().strip()
    user = db.query(User).filter(
        (User.user_id.ilike(user_id_lower)) | (User.email.ilike(user_id_lower))
    ).first()

    # Unknown user
    if not user:
        logger.warning("[Login] User not found: %s", payload.user_id)
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid credentials",
        )

    if not user.hashed_password:
        logger.error("[Login] User %s exists but has no password hash!", user.user_id)
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid credentials",
        )

    # Account lockout check
    if user.is_locked:
        logger.warning("[Login] Locked account attempt: %s", user.user_id)
        raise HTTPException(
            status_code=status.HTTP_423_LOCKED,
            detail=(
                "Account temporarily locked due to too many failed login attempts. "
                "Please try again in a few minutes."
            ),
        )

    # Wrong password
    if not verify_password(payload.password, user.hashed_password):
        logger.warning("[Login] Password mismatch for user: %s", user.user_id)
        record_failed_login(db, user)
        remaining = max(0, 5 - (user.failed_login_count or 0))
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"Invalid credentials. {remaining} attempt(s) remaining before lockout.",
        )

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

    # Success β€” reset lockout, issue tokens with active UserSession
    reset_failed_logins(db, user)   # Also sets last_login_at
    
    from app.models.session import UserSession
    tokens = create_token_pair_with_session(user.user_id, 1, user.user_version)
    user_session = UserSession(
        user_id=user.user_id,
        selector=tokens["selector"],
        verifier_hash=tokens["verifier_hash"],
        session_version=1,
        ip_address=request.client.host if request.client else None,
        user_agent=request.headers.get("User-Agent"),
        is_compromised=False,
        expires_at=datetime.now(timezone.utc) + timedelta(days=30),
    )
    db.add(user_session)
    db.commit()

    redis = _get_redis()
    if redis:
        set_cached_versions(user.user_id, tokens["selector"], user.user_version, 1)

    logger.info("User logged in: %s", user.user_id)

    return TokenResponse(
        access_token=tokens["access_token"],
        refresh_token=tokens["refresh_token"],
        user_id=user.user_id,
        name=user.name,
    )


# ──────────────────────────────────────────────
# Refresh
# ──────────────────────────────────────────────

@router.post(

    "/refresh",

    response_model=RefreshTokenResponse,

    summary="Rotate refresh token and get a new access token",

)
@limiter.limit("10/minute")
def refresh_token(

    request: Request,

    payload: RefreshTokenRequest,

    db: Session = Depends(get_db),

) -> RefreshTokenResponse:
    """

    Validates the provided selector-verifier refresh token, rotates it (single-use RTR),

    checks the concurrency idempotency cache, and issues a fresh versioned token pair.

    """
    from app.models.session import UserSession
    import json

    token_str = payload.refresh_token
    if not token_str or "." not in token_str:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid or expired refresh token",
        )

    try:
        selector, verifier = token_str.split(".", 1)
    except ValueError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid token format",
        )

    redis = _get_redis()
    idempotency_key = f"hale:idempotency:refresh:{selector}"

    # 1. Check Idempotency Cache for parallel tab storms / retries
    if redis:
        try:
            cached_val = redis.get(idempotency_key)
            if cached_val:
                logger.info("[Refresh] Idempotency Cache Hit for selector: %s", selector)
                resp_data = json.loads(cached_val)
                return RefreshTokenResponse(**resp_data)
        except Exception as exc:
            logger.warning("Redis idempotency read failed: %s", exc)

    # 2. Database selector lookup (B-Tree unique index hit, O(1) DB lookups)
    session = db.query(UserSession).filter(UserSession.selector == selector).first()
    if not session:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid or expired refresh token",
        )

    # 3. Fraud / Compromise detection
    if session.is_compromised:
        # Invalidate all user sessions on replay outside grace window
        db.query(UserSession).filter(UserSession.user_id == session.user_id).update({"is_compromised": True})
        db.commit()
        logger.error("[Refresh] Replay detected! Session compromised. User: %s", session.user_id)
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Suspicious activity detected. All active sessions revoked.",
        )

    # 4. Expiry checks
    if not session.expires_at:
        db.delete(session)
        db.commit()
        raise HTTPException(status_code=401, detail="Session expired")

    session_expiry = session.expires_at.replace(tzinfo=timezone.utc) if session.expires_at.tzinfo is None else session.expires_at
    if datetime.now(timezone.utc) > session_expiry:
        db.delete(session)
        db.commit()
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Session expired",
        )

    # 5. Cryptographic constant-time verification of the verifier hash
    if not verify_verifier(verifier, session.verifier_hash):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid or expired refresh token",
        )

    user = db.query(User).filter(User.user_id == session.user_id).first()
    if not user or not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Account is deactivated or not found",
        )

    # 6. Rotate (Atomic Session Version Update / Compare-And-Swap)
    current_version = session.session_version
    plain_token, new_selector, verifier_hash = generate_selector_verifier()

    # CAS update to prevent parallel worker overwrites
    updated_rows = (
        db.query(UserSession)
        .filter(UserSession.id == session.id, UserSession.session_version == current_version)
        .update({
            "selector": new_selector,
            "verifier_hash": verifier_hash,
            "session_version": current_version + 1,
            "last_active_at": datetime.now(timezone.utc),
            "ip_address": request.client.host if request.client else None,
            "user_agent": request.headers.get("User-Agent"),
        })
    )
    db.commit()

    if updated_rows == 0:
        # Fall back to won race cached response if available
        if redis:
            cached_val = redis.get(idempotency_key)
            if cached_val:
                resp_data = json.loads(cached_val)
                return RefreshTokenResponse(**resp_data)
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="Refresh conflict. Please retry.",
        )

    # Generate new versioned access token
    from app.core.security import create_access_token
    access = create_access_token(data={
        "sub": user.user_id,
        "sid": new_selector,
        "sv": current_version + 1,
        "uv": user.user_version
    })

    response_payload = {
        "access_token": access,
        "refresh_token": plain_token,
        "token_type": "bearer"
    }

    # 7. Write to Idempotency Cache (30s) and Version Cache
    if redis:
        try:
            redis.setex(idempotency_key, 30, json.dumps(response_payload))
            set_cached_versions(user.user_id, new_selector, user.user_version, current_version + 1)
        except Exception as exc:
            logger.warning("Redis cache update failed inside refresh: %s", exc)

    logger.info("Session rotated successfully for user: %s", user.user_id)
    return RefreshTokenResponse(**response_payload)


# ──────────────────────────────────────────────
# Logout
# ──────────────────────────────────────────────

@router.post(

    "/logout",

    response_model=MessageResponse,

    summary="Invalidate current access token and clear refresh token",

)
def logout(

    current_user: User = Depends(get_current_user),

    token: str = Depends(get_current_token),

    db: Session = Depends(get_db),

) -> MessageResponse:
    """Invalidate current session by blacklisting the access token and deleting the session selector."""
    from app.models.session import UserSession
    from app.core.security import decode_token, clear_cached_versions

    # Blacklist the current access token
    blacklist_token(token)

    # Decode claims to retrieve selector and invalidate session
    try:
        payload = decode_token(token)
        session_id = payload.get("sid")
        if session_id:
            db.query(UserSession).filter(UserSession.selector == session_id).delete()
            db.commit()
            clear_cached_versions(current_user.user_id, session_id)
    except Exception as exc:
        logger.error("[Logout] Failed to delete session cleanly: %s", exc)

    logger.info("User logged out: %s", current_user.user_id)
    return MessageResponse(message="Logged out successfully")


# ──────────────────────────────────────────────
# Change password
# ──────────────────────────────────────────────

@router.post(

    "/change-password",

    response_model=MessageResponse,

    summary="Change password with old password verification",

)
@limiter.limit("3/minute")
def change_password(

    request: Request,

    payload: ChangePasswordRequest,

    current_user: User = Depends(get_current_user),

    db: Session = Depends(get_db),

) -> MessageResponse:
    """Change user password, increment user_version (stateless invalidation), and delete all active sessions."""
    from app.models.session import UserSession
    from app.core.security import clear_cached_versions

    if not verify_password(payload.old_password, current_user.hashed_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Old password is incorrect",
        )

    if payload.old_password == payload.new_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="New password must be different from the old password",
        )

    current_user.hashed_password = hash_password(payload.new_password)
    
    # Stateless invalidation: Increment user_version
    current_user.user_version = (current_user.user_version or 0) + 1
    
    # Revoke all multi-device sessions for this user in DB
    db.query(UserSession).filter(UserSession.user_id == current_user.user_id).delete()
    db.commit()

    # Invalidate all version caches
    clear_cached_versions(current_user.user_id)

    logger.info("Password changed and all active sessions globally revoked for: %s", current_user.user_id)
    return MessageResponse(message="Password changed successfully. Please log in again.")


# ──────────────────────────────────────────────
# Profile
# ──────────────────────────────────────────────

@router.get(

    "/profile",

    response_model=UserProfile,

    summary="Get the current user's profile",

)
def get_profile(current_user: User = Depends(get_current_user)) -> User:
    return current_user


@router.patch(

    "/profile",

    response_model=UserProfile,

    summary="Update profile fields (name, coach_personality)",

)
def update_profile(

    updates: UpdateProfileRequest,

    current_user: User = Depends(get_current_user),

    db: Session = Depends(get_db),

) -> User:
    """Update allowed profile fields. Only non-None fields are applied."""
    if updates.name is not None:
        current_user.name = updates.name
    if updates.coach_personality is not None:
        current_user.coach_personality = updates.coach_personality

    db.commit()
    db.refresh(current_user)
    return current_user