Spaces:
Paused
Paused
dushyantsingh0
Fix workspace onboarding crash: make admin user resolve idempotent to prevent UniqueViolation on existing email
bfc34e2 Download api/v1/workspace.py from 3SCError404/miracle: direct link, hf CLI and curl.
- Browser
- Download file 8.84 kB
-
https://huggingface.co/spaces/3SCError404/miracle/resolve/main/api/v1/workspace.py
- Command line
-
hf download hf://spaces/3SCError404/miracle/api/v1/workspace.py
-
curl -L -o workspace.py https://huggingface.co/spaces/3SCError404/miracle/resolve/main/api/v1/workspace.py
8.84 kB
| from typing import Any, List, Optional | |
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy import select | |
| from core.deps import get_db, get_current_user | |
| from core.permissions import require_roles, WORKSPACE_ADMIN_ROLES | |
| from models.user import User, UserRole | |
| from models.workspace import Workspace | |
| from schemas.workspace import WorkspaceUpdate, WorkspaceResponse, WorkspaceWithRole, OnboardRequest | |
| router = APIRouter() | |
| async def onboard_customer( | |
| payload: OnboardRequest, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ): | |
| """ | |
| Superadmin only: Atomic onboarding of a new customer tenant. | |
| Creates Workspace, Admin User, and Default Project in one transaction. | |
| """ | |
| if not current_user.is_platform_admin: | |
| raise HTTPException(status_code=403, detail="Superadmin authority required") | |
| # 1. Create Workspace | |
| new_ws = Workspace( | |
| name=payload.workspace_name, | |
| branding={ | |
| "colors": payload.branding_colors or {}, | |
| "personality": payload.ai_personality | |
| } | |
| ) | |
| db.add(new_ws) | |
| await db.flush() # Get ID | |
| # 2. Resolve Admin User (idempotent onboarding) | |
| user_stmt = select(User).where(User.email == payload.admin_email) | |
| res = await db.execute(user_stmt) | |
| existing_user = res.scalar_one_or_none() | |
| if existing_user: | |
| new_user = existing_user | |
| if not new_user.global_role: | |
| new_user.global_role = UserRole.CUSTOMER_ADMIN | |
| if not new_user._legacy_workspace_id: | |
| new_user._legacy_workspace_id = new_ws.id | |
| db.add(new_user) | |
| await db.flush() | |
| else: | |
| from core.security import get_password_hash | |
| import secrets | |
| password = payload.admin_password or secrets.token_urlsafe(12) | |
| new_user = User( | |
| email=payload.admin_email, | |
| full_name=payload.admin_name, | |
| hashed_password=get_password_hash(password), | |
| _legacy_workspace_id=new_ws.id, | |
| global_role=UserRole.CUSTOMER_ADMIN | |
| ) | |
| db.add(new_user) | |
| await db.flush() | |
| # 3. Create Link | |
| from models.user_workspace import UserWorkspace | |
| link = UserWorkspace( | |
| user_id=new_user.id, | |
| workspace_id=new_ws.id, | |
| role=UserRole.CUSTOMER_ADMIN, | |
| is_primary=True | |
| ) | |
| db.add(link) | |
| # 4. Create Default Project | |
| from models.project import Project | |
| default_proj = Project( | |
| workspace_id=new_ws.id, | |
| name="GENERAL SUPPORT", | |
| description="Standard support project for automated ticket routing." | |
| ) | |
| db.add(default_proj) | |
| await db.commit() | |
| await db.refresh(new_ws) | |
| # Invalidate Global Workspace Cache | |
| from core.cache import delete_by_pattern | |
| await delete_by_pattern("workspaces:v2:user:*") | |
| return new_ws | |
| async def list_available_workspaces( | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """List all workspaces with user roles (Cached 15m).""" | |
| from core.cache import get_cached_object, set_cached_object | |
| # Force refresh by bumping cache version after security fix | |
| cache_key = f"workspaces:v2:user:{current_user.id}" | |
| # Check cache first | |
| cached_data = await get_cached_object(cache_key) | |
| if cached_data: | |
| return cached_data | |
| from models.user_workspace import UserWorkspace | |
| # 1. Global Platform Admin visibility (Superadmin, SC Admin, SC Lead) | |
| if current_user.is_platform_admin: | |
| stmt = select(Workspace).where( | |
| Workspace.deleted_at.is_(None), | |
| ~Workspace.name.ilike("SOFTDELETE%") | |
| ) | |
| result = await db.execute(stmt) | |
| workspaces = result.scalars().all() | |
| res_payload = [ | |
| { | |
| **WorkspaceResponse.model_validate(w).model_dump(mode='json'), | |
| "role": UserRole.SC_ADMIN.value, | |
| "is_primary": (str(w.id) == current_user.workspace_id) | |
| } for w in workspaces | |
| ] | |
| await set_cached_object(cache_key, res_payload, ttl=900) | |
| return res_payload | |
| # 2. Association-based discovery for standard users | |
| stmt = ( | |
| select(Workspace, UserWorkspace.role, UserWorkspace.is_primary) | |
| .join(UserWorkspace, Workspace.id == UserWorkspace.workspace_id) | |
| .where( | |
| UserWorkspace.user_id == current_user.id, | |
| Workspace.deleted_at.is_(None) | |
| ) | |
| ) | |
| result = await db.execute(stmt) | |
| rows = result.all() | |
| res_payload = [ | |
| { | |
| **WorkspaceResponse.model_validate(row[0]).model_dump(mode='json'), | |
| "role": row[1].value if hasattr(row[1], 'value') else row[1], | |
| "is_primary": row[2] | |
| } for row in rows | |
| ] | |
| # Cache the result for 15 minutes | |
| await set_cached_object(cache_key, res_payload, ttl=900) | |
| return res_payload | |
| async def get_my_workspace( | |
| workspace_id: Optional[str] = None, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """Get current workspace details (Cached). Supports explicit workspace targeting.""" | |
| from core.permissions import get_effective_context | |
| from core.cache import get_cached_object, set_cached_object | |
| # 1. Resolve strict context | |
| target_ws_id, _ = await get_effective_context(db, current_user, workspace_id) | |
| cache_key = f"ws:meta:{target_ws_id}" | |
| cached = await get_cached_object(cache_key) | |
| if cached: | |
| return cached | |
| stmt = select(Workspace).where( | |
| Workspace.id == target_ws_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") | |
| # Cache for 1 hour (workspace data is slow-changing) | |
| response_data = WorkspaceResponse.model_validate(workspace) | |
| await set_cached_object(cache_key, response_data.model_dump(mode='json'), ttl=3600) | |
| return response_data | |
| async def update_workspace( | |
| payload: WorkspaceUpdate, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """ | |
| Update workspace settings/branding. | |
| Staff/Platform Admins can update any workspace they are associated with. | |
| Customers can only update their home workspace. | |
| """ | |
| from core.permissions import get_effective_context, WORKSPACE_ADMIN_ROLES | |
| # 1. Resolve strict context (BOLA/IDOR protection) | |
| target_ws_id, effective_role = await get_effective_context(db, current_user, payload.workspace_id) | |
| # 2. Verify role has administrative authority in THIS context | |
| # Convert role to string for membership check | |
| role_str = effective_role.value if hasattr(effective_role, 'value') else str(effective_role) | |
| allowed_values = [str(r.value if hasattr(r, 'value') else r) for r in WORKSPACE_ADMIN_ROLES] | |
| if role_str not in allowed_values: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail=f"Access Denied: Role {role_str} lacks administrative authority for this workspace." | |
| ) | |
| # 3. Perform update | |
| stmt = select(Workspace).where( | |
| Workspace.id == target_ws_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") | |
| if payload.name is not None: | |
| workspace.name = payload.name | |
| if payload.branding is not None: | |
| workspace.branding = payload.branding | |
| from sqlalchemy.orm.attributes import flag_modified | |
| flag_modified(workspace, "branding") | |
| db.add(workspace) | |
| await db.commit() | |
| await db.refresh(workspace) | |
| # Invalidate Cache | |
| from core.cache import invalidate_cache | |
| await invalidate_cache(f"ws:meta:{target_ws_id}") | |
| return workspace | |
| async def get_workspace_branding( | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """Get standalone branding config (logo, colors).""" | |
| stmt = select(Workspace).where( | |
| Workspace.id == current_user.workspace_id, | |
| Workspace.deleted_at.is_(None) | |
| ) | |
| result = await db.execute(stmt) | |
| workspace = result.scalar_one_or_none() | |
| return workspace.branding or {} | |