Spaces:
Paused

File size: 24,882 Bytes
5eb4857
 
 
 
b7980f7
 
b0867f8
5eb4857
 
b7980f7
5eb4857
 
b7980f7
0243ced
b7980f7
5eb4857
0509823
b0867f8
5eb4857
b7980f7
5eb4857
5efb6af
5eb4857
0509823
5eb4857
 
 
accf280
988d204
 
 
 
accf280
9eaba40
5eb4857
 
 
 
b7980f7
 
6df4737
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3143c25
b7980f7
 
3143c25
 
 
 
b7980f7
3143c25
 
 
9eaba40
 
 
3143c25
 
 
9eaba40
3143c25
 
b7980f7
3143c25
 
5eb4857
b7980f7
3143c25
5eb4857
3143c25
b7980f7
3143c25
 
9eaba40
3143c25
bc57ae4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9eaba40
bc57ae4
b7980f7
6df4737
b7980f7
 
dbc31e7
 
 
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
 
 
dbc31e7
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
3143c25
b7980f7
 
3143c25
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
b7980f7
5eb4857
9377380
 
 
 
 
b7980f7
 
 
5eb4857
b7980f7
 
 
5eb4857
 
 
 
accf280
5eb4857
 
 
b0867f8
5eb4857
 
 
b7980f7
 
 
 
 
 
0509823
 
 
 
 
 
 
 
 
5eb4857
 
0509823
 
 
 
5eb4857
b0867f8
 
 
 
 
 
 
 
b7980f7
 
0509823
 
b7980f7
 
 
5eb4857
 
 
b0867f8
 
0509823
b0867f8
 
 
 
 
b7980f7
5eb4857
5cb3875
 
b7980f7
 
 
 
3143c25
 
b7980f7
 
 
3143c25
 
 
5cb3875
5eb4857
 
 
 
5cb3875
b7980f7
5cb3875
 
5eb4857
 
 
 
 
b7980f7
b0867f8
 
 
 
 
 
 
 
 
b7980f7
5eb4857
 
 
 
 
accf280
5eb4857
 
 
b0867f8
 
5eb4857
 
 
 
 
 
 
 
b0867f8
 
 
 
 
 
 
 
5eb4857
 
 
accf280
5eb4857
 
 
 
 
 
b7980f7
 
5eb4857
 
 
 
accf280
b7980f7
 
 
 
 
 
 
 
 
 
3143c25
 
b7980f7
 
 
 
 
 
3143c25
b7980f7
3143c25
b7980f7
 
 
 
 
 
 
 
3143c25
b7980f7
 
3143c25
b7980f7
 
 
3143c25
b7980f7
 
 
 
 
 
 
 
 
 
 
 
accf280
b7980f7
0509823
b7980f7
 
 
5eb4857
0509823
 
5eb4857
b7980f7
 
bd0fa52
 
b7980f7
0509823
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
accf280
b0867f8
 
 
 
 
5eb4857
b7980f7
 
 
5eb4857
b7980f7
 
 
 
 
 
 
 
 
 
 
 
3143c25
b7980f7
3143c25
 
 
 
 
185724a
 
 
b7980f7
9377380
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7be7487
185724a
 
 
 
 
 
 
 
 
 
 
 
3143c25
b0867f8
 
 
 
 
 
 
 
 
3143c25
5eb4857
6ba1c48
5eb4857
 
 
3143c25
accf280
5eb4857
 
b0867f8
 
5eb4857
 
b7980f7
 
 
5eb4857
b7980f7
 
 
 
 
 
 
 
 
 
 
5eb4857
 
b7980f7
5eb4857
 
b7980f7
5eb4857
 
 
 
b7980f7
5eb4857
b7980f7
5eb4857
 
 
 
b0867f8
 
 
 
 
 
 
 
b7980f7
5eb4857
b7980f7
 
 
 
 
5eb4857
 
0243ced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5efb6af
 
5eb4857
5efb6af
 
 
 
 
 
 
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
"""
Authentication endpoints: Registration, Login, Token generation, Password management.
"""

import secrets
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, status, Header, BackgroundTasks
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func
from typing import Any, Optional

from core.deps import get_db, get_current_user, get_current_refresh_user, oauth2_scheme
from core.security import verify_password, get_password_hash, create_access_token, create_refresh_token, create_reset_token, create_ws_ticket
from core.config import get_settings
from core.logging import get_logger
from core.rate_limiter import auth_rate_limit
from core.audit import log_action
from models.user import User, UserRole
from models.user_workspace import UserWorkspace
from models.workspace import Workspace
from schemas.auth import Token, UserRegister, PasswordChangeRequest, TokenRefreshResponse, ForgotPasswordRequest, ResetPasswordRequest, UserMeResponse

router = APIRouter(dependencies=[Depends(auth_rate_limit)])
logger = get_logger(__name__)


@router.get("/login/")
async def login_diagnostic():
    return {"message": "Login endpoint is active"}


@router.post("/register/", response_model=Token, status_code=status.HTTP_201_CREATED)
async def register_user(user_in: UserRegister, db: AsyncSession = Depends(get_db), background_tasks: BackgroundTasks = BackgroundTasks()) -> Any:
    """
    Register a new user. If workspace_id is absent, creates a new workspace and makes the user a CUSTOMER_ADMIN.
    Otherwise joins an existing workspace as CUSTOMER_USER.
    """
    # Check if user exists (Case-insensitive)
    stmt = select(User).where(func.lower(User.email) == func.lower(user_in.email))
    existing_user = await db.scalar(stmt)

    # Handle Workspace
    if user_in.workspace_id:
        # Join existing workspace
        stmt = select(Workspace).where(
            Workspace.id == user_in.workspace_id,
            Workspace.deleted_at.is_(None)
        )
        result = await db.execute(stmt)
        workspace = result.scalar_one_or_none()
        if not workspace:
            raise HTTPException(status_code=404, detail="Workspace not found")
        role = UserRole.CUSTOMER_USER
    else:
        # Create new workspace
        ws_name = user_in.workspace_name or f"{user_in.full_name}'s Workspace"
        workspace = Workspace(name=ws_name)
        db.add(workspace)
        await db.flush() # get id
        role = UserRole.CUSTOMER_ADMIN

        # --- AUTOMATED PROVISIONING: INTERNAL STAFF ---
        settings = get_settings()
        
        # 1. Ensure Platform Super Admin Oversight
        super_email = settings.SUPER_ADMIN_EMAIL
        sc_stmt = select(User).where(func.lower(User.email) == func.lower(super_email))
        super_admin = (await db.execute(sc_stmt)).scalar_one_or_none()
        
        if super_admin:
            # Link Super Admin to EVERY new workspace
            db.add(UserWorkspace(
                user_id=super_admin.id,
                workspace_id=workspace.id,
                role=UserRole.SC_ADMIN,
                is_primary=False
            ))
            logger.info(f"PROVISION: Linked Platform Admin {super_email} to workspace {workspace.id}")
            log_action(background_tasks, workspace_id=workspace.id, entity_type="user", entity_id=super_admin.id, action="provision_super_admin_linked", metadata_json={"email": super_email, "workspace_id": str(workspace.id)})
        else:
            # Safety: If Super Admin doesn't exist (e.g. first run), create them
            sc_password = secrets.token_urlsafe(16)
            super_admin = User(
                email=super_email,
                hashed_password=get_password_hash(sc_password),
                full_name=settings.SUPER_ADMIN_NAME,
                global_role=UserRole.SUPERADMIN,
            )
            db.add(super_admin)
            await db.flush()
            db.add(UserWorkspace(user_id=super_admin.id, workspace_id=workspace.id, role=UserRole.SC_ADMIN, is_primary=True))
            logger.info(f"PROVISION: Created & Linked Initial Super Admin {super_email}")
            log_action(background_tasks, workspace_id=workspace.id, entity_type="user", entity_id=super_admin.id, action="provision_super_admin_created", metadata_json={"email": super_email, "workspace_id": str(workspace.id)})

        # 2. Local Workspace Admin Provisioning (Feature Request)
        # Automatically create admin_<workspace>@3sc.com and grant SC_ADMIN
        import re
        safe_ws_name = re.sub(r'[^a-zA-Z0-9]', '', ws_name).lower()
        if safe_ws_name:
            local_admin_email = f"admin_{safe_ws_name}@3sc.com"
            local_admin_stmt = select(User).where(func.lower(User.email) == local_admin_email)
            local_admin = (await db.execute(local_admin_stmt)).scalar_one_or_none()
            
            if not local_admin:
                local_admin_pw = secrets.token_urlsafe(16)
                local_admin = User(
                    email=local_admin_email,
                    hashed_password=get_password_hash(local_admin_pw),
                    full_name=f"Internal Admin ({ws_name})",
                    is_active=True
                )
                db.add(local_admin)
                await db.flush()
                
            # Link exactly to this workspace as SC_ADMIN
            db.add(UserWorkspace(
                user_id=local_admin.id,
                workspace_id=workspace.id,
                role=UserRole.SC_ADMIN,
                is_primary=True
            ))
            logger.info(f"PROVISION: Created & Linked Local Internal Admin {local_admin_email} for workspace {workspace.id}")
            log_action(background_tasks, workspace_id=workspace.id, entity_type="user", entity_id=local_admin.id, action="provision_local_admin", metadata_json={"email": local_admin_email, "workspace_id": str(workspace.id)})

    # 2. Check if User already exists on the platform
    # existing_user was already fetched at the start (L41)

    if existing_user:
        # Verify password before allowing account to join a new workspace.
        # Without this check any caller who knows a valid email could join any workspace.
        if not verify_password(user_in.password, existing_user.hashed_password):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="Invalid credentials.",
            )

        # Check if they are already in this workspace
        link_stmt = select(UserWorkspace).where(
            UserWorkspace.user_id == existing_user.id,
            UserWorkspace.workspace_id == workspace.id
        )
        existing_link = (await db.execute(link_stmt)).scalar_one_or_none()
        if existing_link:
             raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"User {user_in.email} is already a member of {workspace.name}"
            )

        # Link existing user to new workspace
        new_link = UserWorkspace(
            user_id=existing_user.id,
            workspace_id=workspace.id,
            role=role,
            is_primary=False # Usually first registration is primary
        )
        db.add(new_link)
        user = existing_user
        logger.info(f"Existing user {user.email} joined workspace {workspace.name}")
    else:
        # 3. Create NEW User
        user = User(
            email=user_in.email.lower(),
            real_email=user_in.real_email or user_in.email.lower(),
            hashed_password=get_password_hash(user_in.password),
            full_name=user_in.full_name,

            # No global_role for customer registrations by default
        )
        db.add(user)
        await db.flush()

        # Create M2M Workspace association (Primary for new users)
        new_link = UserWorkspace(
            user_id=user.id,
            workspace_id=workspace.id,
            role=role,
            is_primary=True
        )
        db.add(new_link)
        logger.info(f"New user registered: {user.email} (ID: {user.id}) in {workspace.name}")

    await db.commit()
    await db.refresh(user)

    # Invalidate Global Workspace Cache if a new workspace was created
    if not user_in.workspace_id:
        from core.cache import delete_by_pattern
        await delete_by_pattern("workspaces:v2:user:*")

    # Inject context into the user object (shim support)
    setattr(user, "workspace_id", workspace.id)
    setattr(user, "role", role)

    # 4. Generate tokens for the Session
    access_token = create_access_token(subject=user.id, workspace_id=workspace.id)
    refresh_token = create_refresh_token(subject=user.id)

    return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}


@router.post("/login/", response_model=Token)
async def login(
    form_data: OAuth2PasswordRequestForm = Depends(), 
    db: AsyncSession = Depends(get_db),
    background_tasks: BackgroundTasks = BackgroundTasks(),
    x_nexus_portal: Optional[str] = Header(None, alias="X-Nexus-Portal")
) -> Any:
    """OAuth2 compatible token login, get an access token for future requests."""
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid email or password.",
        headers={"WWW-Authenticate": "Bearer"},
    )
    
    # --- IDENTITY & PORTAL AUTHORIZATION (Consolidated JOIN) ---
    stmt = (
        select(User, UserWorkspace)
        .outerjoin(UserWorkspace, UserWorkspace.user_id == User.id)
        .where(
            func.lower(User.email) == func.lower(form_data.username),
            User.deleted_at.is_(None)
        )
        .order_by(UserWorkspace.is_primary.desc())
    )
    result = await db.execute(stmt)
    # The first row from results will have our primary workspace link (if any)
    row = result.first()
    
    if not row:
        logger.warning(f"Login failed: Account not found for {form_data.username}")
        log_action(
            background_tasks,
            workspace_id=None,
            entity_type="user",
            entity_id=UUID("00000000-0000-0000-0000-000000000000"),
            action="login_failure_not_found",
            metadata_json={"email": form_data.username}
        )
        raise credentials_exception

    user, active_link = row

    if not user.is_active:
        logger.warning(f"Login failed: Account inactive for {form_data.username}")
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Account has been deactivated. Please contact your administrator.")

    if not verify_password(form_data.password, user.hashed_password):
        logger.warning(f"Login failed: Invalid password for {form_data.username}")
        log_action(
            background_tasks,
            workspace_id=active_link.workspace_id if active_link else None,
            entity_type="user",
            entity_id=user.id,
            action="login_failure_invalid_password",
            user_id=user.id
        )
        raise credentials_exception
    
    portal = x_nexus_portal or "customer"
    
    # Context-aware user role
    user_role = user.global_role or (active_link.role if active_link else UserRole.CUSTOMER_USER)
    active_ws_id = active_link.workspace_id if active_link else None

    # GLOBAL BYPASS: Platform Super Admins can access any portal/interface
    if user_role == UserRole.SUPERADMIN:
        logger.info(f"Portal Bypass: Super Admin {user.email} accessing {portal} portal")
        pass
    elif portal == "internal":
        # Internal staff access (including local admins)
        if user_role not in [UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN]:

            logger.warning(f"Security Alert: Customer {user.email} attempted Internal Portal access")
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN, 
                detail="Access Denied: Customers cannot access the Operations Console."
            )
    else: # Default/Customer Mode
        if user_role not in [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]:
            # Staff are strictly forbidden from the customer portal by default
            logger.warning(f"Security Alert: Staff {user.email} attempted Customer Portal access")
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN, 
                detail="Access Denied: Staff must use the Operations Console."
            )

    logger.info(f"User login successful: {user.email} (Active Workspace ID: {active_ws_id})")
    log_action(
        background_tasks,
        workspace_id=active_ws_id,
        entity_type="user",
        entity_id=user.id,
        action="login_success",
        user_id=user.id,
        metadata_json={"portal": portal}
    )
    access_token = create_access_token(subject=user.id, workspace_id=active_ws_id, role=user_role)
    refresh_token = create_refresh_token(subject=user.id)

    return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}


@router.post("/change-password/")
async def change_password(
    payload: PasswordChangeRequest,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
    background_tasks: BackgroundTasks = BackgroundTasks()
) -> Any:
    """Change user password."""
    if not verify_password(payload.old_password, current_user.hashed_password):
        raise HTTPException(status_code=400, detail="Invalid old password")
    
    current_user.hashed_password = get_password_hash(payload.new_password)
    db.add(current_user)
    await db.commit()
    log_action(
        background_tasks,
        workspace_id=current_user.workspace_id,
        entity_type="user",
        entity_id=current_user.id,
        action="password_change",
        user_id=current_user.id
    )
    return {"message": "Password updated successfully"}


@router.post("/refresh/", response_model=TokenRefreshResponse)
async def refresh_token(
    current_user: User = Depends(get_current_refresh_user)
) -> Any:
    """Exchange a refresh token for a new access token."""
    new_access_token = create_access_token(
        subject=current_user.id, 
        workspace_id=current_user.workspace_id,
        role=current_user.role
    )
    return {"access_token": new_access_token, "token_type": "bearer"}


@router.post("/switch-workspace/", response_model=Token)
async def switch_workspace(
    target_workspace_id: UUID,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    """
    Switch the active workspace context for the current user.
    Verifies the user belongs to the target workspace before issuing a new token.
    """
    # 1. Verify User has access to the target workspace
    # ONLY the designated Platform Super Admin can switch to any workspace without a link
    if current_user.is_platform_admin:
        # Check if the workspace actually exists
        ws_stmt = select(Workspace).where(Workspace.id == target_workspace_id, Workspace.deleted_at.is_(None))
        ws_exists = (await db.execute(ws_stmt)).scalar_one_or_none()
        if not ws_exists:
            raise HTTPException(status_code=404, detail="Target workspace not found")
        
        target_role = UserRole.SUPERADMIN
    else:
        # Strict Isolation: Check explicit association for everyone else
        assoc_stmt = select(UserWorkspace).where(
            UserWorkspace.user_id == current_user.id,
            UserWorkspace.workspace_id == target_workspace_id
        )
        assoc_res = await db.execute(assoc_stmt)
        association = assoc_res.scalar_one_or_none()
        
        if not association:
            logger.warning(f"UNAUTHORIZED ACCESS ATTEMPT: User {current_user.email} tried to switch to workspace {target_workspace_id}")
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="Access Denied: You are not authorized to access this workspace."
            )
        target_role = association.role


    # 2. Issue new tokens for the new context
    access_token = create_access_token(
        subject=current_user.id, 
        workspace_id=target_workspace_id,
        role=target_role
    )
    refresh_token = create_refresh_token(subject=current_user.id)

    logger.info(f"User {current_user.email} switched to workspace {target_workspace_id}")
    return {"access_token": access_token, "refresh_token": refresh_token, "token_type": "bearer"}


@router.post("/logout/")
async def logout(
    refresh_token: Optional[str] = None,
    current_user: User = Depends(get_current_user),
    token: str = Depends(oauth2_scheme)
) -> Any:
    """
    Log out the current user by adding the access token JTI to the blocklist.
    Optionally blocklists the refresh token to prevent further token issuance (GAP-1 Fix).
    """
    from jose import jwt as jwt_lib
    from core.token_blocklist import blocklist_token
    from core.config import get_settings
    settings = get_settings()

    async def _revoke_token(t: str, label: str):
        try:
            p = jwt_lib.decode(t, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
            j = p.get("jti")
            e = p.get("exp")
            if j and e:
                import time
                rem = max(0, int(e - time.time()))
                await blocklist_token(j, rem)
                logger.debug(f"{label} revoked: {j[:8]}")
        except Exception as err:
            logger.warning(f"Failed to revoke {label}: {err}")

    # 1. Revoke Access Token
    await _revoke_token(token, "Access Token")

    # 2. Revoke Refresh Token (GAP-1 Fix)
    if refresh_token:
        await _revoke_token(refresh_token, "Refresh Token")

    logger.info(f"User {current_user.email} logged out (Revocation complete)")
    return {"message": "Successfully logged out"}


@router.post("/forgot-password/")
async def forgot_password(
    payload: ForgotPasswordRequest, 
    db: AsyncSession = Depends(get_db),
    background_tasks: BackgroundTasks = BackgroundTasks()
) -> Any:
    """
    Initiate password reset.
    Always returns 200 to prevent email enumeration attacks.
    Uses a dedicated reset token type that cannot be used as an access token.
    """
    # Verify user exists and is active (Case-insensitive)
    stmt = select(User).where(
        func.lower(User.email) == func.lower(payload.email),
        User.deleted_at.is_(None)
    )
    result = await db.execute(stmt)
    user = result.scalar_one_or_none()
    
    if not user:
        logger.warning(f"Password reset requested for non-existent email: {payload.email}")
        # Always return 200 to prevent email enumeration (Gap 1 fix)
        return {"message": "If an account exists with this email, a password reset link has been sent."}
    # Use dedicated reset token with type='reset'
    reset_token = create_reset_token(subject=payload.email)

    # Resolve delivery target (Gap 4 fix: Notification redirect)
    delivery_target = user.real_email or user.email

    
    # 3. Actually send the email (Professionalized)
    from core.email import send_email, template_nexus_email
    app_settings = get_settings()
    
    # --- INTELLIGENT PORTAL ROUTING (Security Fix) ---
    # We shouldn't trust the client-side 'portal' parameter for routing.
    # We check the user's actual roles to decide where to send them.
    is_staff = False
    if user.global_role == UserRole.SUPERADMIN:
        is_staff = True
    else:
        # Check if they have ANY staff-level association in any workspace
        staff_roles = {UserRole.SC_AGENT, UserRole.SC_LEAD, UserRole.SC_ADMIN}
        stmt = select(UserWorkspace).where(UserWorkspace.user_id == user.id)
        links = (await db.execute(stmt)).scalars().all()
        if any(link.role in staff_roles for link in links):
            is_staff = True
    
    portal_path = "internal" if is_staff else "customer"
    reset_link = f"{app_settings.effective_frontend_url}/{portal_path}/?reset_token={reset_token}"
    
    email_html = template_nexus_email(
        title="Password Reset Request",
        message=f"Hello {user.full_name},\n\nA password reset has been requested for your Nexus AI account. Please click the button below to secure your account and set a new password.",
        action_link=reset_link,
        action_label="Reset Password",
        footer_note="If you did not request this reset, no further action is required. This link expires in 15 minutes."
    )
    
    email_text = f"Hello {user.full_name},\n\nYou requested a password reset. Please use the following link:\n{reset_link}\n\nThis link will expire in 15 minutes."
    
    await send_email(delivery_target, "Nexus Password Reset Request", email_text, html_body=email_html)
    
    log_action(
        background_tasks,
        workspace_id=user.workspace_id if hasattr(user, 'workspace_id') else None,
        entity_type="user",
        entity_id=user.id,
        action="forgot_password_requested",
        user_id=user.id
    )
    
    logger.info(f"Password reset token sent to {delivery_target} (Login Email: {user.email})")
    return {
        "message": "If an account exists with this email, a password reset link has been sent."
    }



@router.post("/reset-password/")
async def reset_password(
    payload: ResetPasswordRequest,
    db: AsyncSession = Depends(get_db),
    background_tasks: BackgroundTasks = BackgroundTasks()
) -> Any:
    """Reset password using a token."""
    from jose import jwt, JWTError
    settings = get_settings()
    
    try:
        try:
            decoded_payload = jwt.decode(payload.token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        except JWTError:
            raise HTTPException(status_code=400, detail="Invalid or expired reset token")

        # Validate this is actually a reset token, not an access/refresh token (Gap 2 fix)
        token_type = decoded_payload.get("type")
        if token_type != "reset":
            logger.warning(f"Password reset attempted with non-reset token (type={token_type})")
            raise HTTPException(status_code=400, detail="Invalid reset token. Please request a new password reset.")

        email: str = decoded_payload.get("sub")
        if not email:
            raise HTTPException(status_code=400, detail="Invalid token payload")
            
        stmt = select(User).where(
            func.lower(User.email) == func.lower(email),
            User.deleted_at.is_(None)
        )
        result = await db.execute(stmt)
        user = result.scalar_one_or_none()
        
        if not user:
            raise HTTPException(status_code=404, detail="User associated with this token no longer exists")
            
        user.hashed_password = get_password_hash(payload.new_password)
        db.add(user)
        await db.commit()
        log_action(
            background_tasks,
            workspace_id=user.workspace_id if hasattr(user, 'workspace_id') else None,
            entity_type="user",
            entity_id=user.id,
            action="password_reset_success",
            user_id=user.id
        )
        logger.info(f"Password reset successful for {email}")
        return {"message": "Password reset successful"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Unexpected error during password reset: {e}")
        raise HTTPException(status_code=500, detail="An internal error occurred during password reset")


@router.post("/ws-ticket/")
async def get_ws_ticket(current_user: User = Depends(get_current_user)) -> Any:
    """
    Issue a 60-second WebSocket authentication ticket.

    Clients should call this endpoint immediately before opening (or reopening)
    a WebSocket connection and pass the returned ticket as the ?token= query
    parameter.  This prevents the stale-token reconnect loop: when a WS
    connection drops, the client calls this endpoint with its still-valid
    refresh token flow to get a fresh ticket, then reconnects.
    """
    ticket = create_ws_ticket(
        subject=current_user.id,
        workspace_id=current_user.workspace_id,
        role=str(current_user.role),
    )
    return {"ws_ticket": ticket, "expires_in": 60}


@router.get("/me/", response_model=UserMeResponse)
async def get_my_profile(current_user: User = Depends(get_current_user)) -> UserMeResponse:
    """Get profile of the currently logged-in user."""
    return UserMeResponse(
        id=str(current_user.id),
        email=current_user.email,
        full_name=current_user.full_name,
        role=str(current_user.role),
        workspace_id=str(current_user.workspace_id) if current_user.workspace_id else ""
    )