Spaces:
Paused
Paused
Download api/v1/auth.py from 3SCError404/nexus: direct link, hf CLI and curl.
- Browser
- Download file 20.5 kB
-
https://huggingface.co/spaces/3SCError404/nexus/resolve/main/api/v1/auth.py
- Command line
-
hf download hf://spaces/3SCError404/nexus/api/v1/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/3SCError404/nexus/resolve/main/api/v1/auth.py
20.5 kB
| """ | |
| Authentication endpoints: Registration, Login, Token generation, Password management. | |
| """ | |
| import secrets | |
| from uuid import UUID | |
| from fastapi import APIRouter, Depends, HTTPException, status, Header | |
| 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 | |
| from core.config import get_settings | |
| from core.logging import get_logger | |
| 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 | |
| router = APIRouter() | |
| logger = get_logger(__name__) | |
| async def login_diagnostic(): | |
| return {"message": "Login endpoint is active"} | |
| async def register_user(user_in: UserRegister, db: AsyncSession = Depends(get_db)) -> 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)) | |
| result = await db.execute(stmt) | |
| if result.scalar_one_or_none(): | |
| logger.warning(f"Registration failed: User with email {user_in.email} already exists") | |
| raise HTTPException(status_code=400, detail="User with this email already exists") | |
| # 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}") | |
| 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}") | |
| # 2. Create Dedicated Local Internal Admin (e.g., admin.acme-corp@3sc.com) | |
| import re | |
| slug = re.sub(r'[^a-z0-9]', '-', workspace.name.lower()).strip('-') | |
| local_admin_email = f"admin.{slug}@3sc.com" | |
| # Check if this local admin account exists | |
| la_stmt = select(User).where(func.lower(User.email) == func.lower(local_admin_email)) | |
| existing_la = (await db.execute(la_stmt)).scalar_one_or_none() | |
| if not existing_la: | |
| local_admin = User( | |
| email=local_admin_email, | |
| full_name=f"{workspace.name} Internal Admin", | |
| hashed_password=get_password_hash("NexusAdmin2024!"), # Default internal password | |
| is_active=True | |
| ) | |
| db.add(local_admin) | |
| await db.flush() | |
| db.add(UserWorkspace( | |
| user_id=local_admin.id, | |
| workspace_id=workspace.id, | |
| role=UserRole.SC_ADMIN, | |
| is_primary=True | |
| )) | |
| logger.info(f"PROVISION: Created dedicated Local Admin {local_admin_email} for workspace {workspace.id}") | |
| else: | |
| # If they already exist (e.g. from a previous registration attempt), ensure they are linked | |
| la_link_stmt = select(UserWorkspace).where( | |
| UserWorkspace.user_id == existing_la.id, | |
| UserWorkspace.workspace_id == workspace.id | |
| ) | |
| if not (await db.execute(la_link_stmt)).scalar_one_or_none(): | |
| db.add(UserWorkspace( | |
| user_id=existing_la.id, | |
| workspace_id=workspace.id, | |
| role=UserRole.SC_ADMIN, | |
| is_primary=False | |
| )) | |
| logger.info(f"PROVISION: Linked existing Local Admin {local_admin_email} to workspace {workspace.id}") | |
| # 2. Check if User already exists on the platform | |
| stmt = select(User).where(func.lower(User.email) == func.lower(user_in.email)) | |
| res = await db.execute(stmt) | |
| existing_user = res.scalar_one_or_none() | |
| if existing_user: | |
| # 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) | |
| # 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"} | |
| async def login( | |
| form_data: OAuth2PasswordRequestForm = Depends(), | |
| db: AsyncSession = Depends(get_db), | |
| 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"}, | |
| ) | |
| stmt = select(User).where( | |
| func.lower(User.email) == func.lower(form_data.username), | |
| User.deleted_at.is_(None) | |
| ) | |
| result = await db.execute(stmt) | |
| user = result.scalar_one_or_none() | |
| if not user: | |
| logger.warning(f"Login failed: Account not found for {form_data.username}") | |
| raise credentials_exception | |
| # Check is_active BEFORE password verification to avoid confirming passwords for banned users | |
| 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}") | |
| raise credentials_exception | |
| # --- PORTAL AUTHORIZATION (Hardened) --- | |
| # Default to 'customer' mode for fail-safe security if header is missing | |
| portal = x_nexus_portal or "customer" | |
| # Get active workspace link | |
| stmt = select(UserWorkspace).where(UserWorkspace.user_id == user.id) | |
| # Default to primary or first | |
| stmt = stmt.order_by(UserWorkspace.is_primary.desc()) | |
| link_res = await db.execute(stmt) | |
| active_link = link_res.scalars().first() | |
| # 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})") | |
| 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"} | |
| async def change_password( | |
| payload: PasswordChangeRequest, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> 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() | |
| return {"message": "Password updated successfully"} | |
| 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"} | |
| 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"} | |
| async def logout( | |
| current_user: User = Depends(get_current_user), | |
| token: str = Depends(oauth2_scheme) | |
| ) -> Any: | |
| """ | |
| Log out the current user by adding the token's JTI to the blocklist. | |
| The token becomes immediately invalid and will be rejected by get_current_user(). | |
| """ | |
| from jose import jwt as jwt_lib | |
| from core.token_blocklist import blocklist_token | |
| from core.config import get_settings | |
| settings = get_settings() | |
| try: | |
| payload = jwt_lib.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) | |
| jti = payload.get("jti") | |
| exp = payload.get("exp") | |
| if jti and exp: | |
| import time | |
| remaining_seconds = max(0, int(exp - time.time())) | |
| await blocklist_token(jti, remaining_seconds) | |
| logger.info(f"User {current_user.email} logged out (token revoked, TTL: {remaining_seconds}s)") | |
| else: | |
| # Legacy tokens without JTI — can't revoke, just acknowledge | |
| logger.warning(f"User {current_user.email} logged out (legacy token without JTI, cannot revoke)") | |
| except Exception as e: | |
| logger.error(f"Logout token revocation error: {e}") | |
| return {"message": "Successfully logged out"} | |
| async def forgot_password(payload: ForgotPasswordRequest, db: AsyncSession = Depends(get_db)) -> 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 (Simulated for Hackathon) | |
| from core.email import send_email | |
| reset_link = f"https://nexus.ai/reset-password?token={reset_token}" | |
| email_body = 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_body) | |
| 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.", | |
| "token": reset_token, # DEV ONLY | |
| "reset_token": reset_token # DEV ONLY | |
| } | |
| async def reset_password( | |
| payload: ResetPasswordRequest, | |
| db: AsyncSession = Depends(get_db) | |
| ) -> 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() | |
| 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") | |
| async def get_my_profile(current_user: User = Depends(get_current_user)) -> Any: | |
| """Get profile of the currently logged-in user.""" | |
| return { | |
| "id": str(current_user.id), | |
| "email": current_user.email, | |
| "full_name": current_user.full_name, | |
| "role": current_user.role, | |
| "workspace_id": str(current_user.workspace_id) | |
| } | |