""" 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_@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 "" )