Spaces:
Paused
Paused
Download api/v1/users.py from 3SCError404/miracle: direct link, hf CLI and curl.
- Browser
- Download file 16.8 kB
-
https://huggingface.co/spaces/3SCError404/miracle/resolve/main/api/v1/users.py
- Command line
-
hf download hf://spaces/3SCError404/miracle/api/v1/users.py
-
curl -L -o users.py https://huggingface.co/spaces/3SCError404/miracle/resolve/main/api/v1/users.py
16.8 kB
| """ | |
| User endpoints: profile and admin management. | |
| """ | |
| from datetime import datetime | |
| from typing import Any, List, Optional | |
| from fastapi import APIRouter, Depends, HTTPException, status, Request, BackgroundTasks | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from sqlalchemy import select, cast, String | |
| from core.deps import get_db, get_current_user | |
| from core.permissions import require_roles, WORKSPACE_ADMIN_ROLES, ALL_CUSTOMER_ROLES | |
| from core.security import get_password_hash | |
| from core.logging import get_logger | |
| from core.audit import log_action | |
| from models.user import User, UserRole | |
| from models.user_workspace import UserWorkspace | |
| from schemas.user import UserResponse, UserUpdate, UserAdminUpdate, UserCreate | |
| router = APIRouter() | |
| logger = get_logger(__name__) | |
| async def create_workspace_user( | |
| payload: UserCreate, | |
| current_user: User = Depends(require_roles(WORKSPACE_ADMIN_ROLES)), | |
| db: AsyncSession = Depends(get_db), | |
| background_tasks: BackgroundTasks = BackgroundTasks() | |
| ) -> Any: | |
| """ | |
| Administratively create a new user within the current workspace. | |
| - CUSTOMER_ADMIN can create CUSTOMER_ADMIN and CUSTOMER_USER. | |
| - SC_ADMIN can create SC_LEAD and SC_AGENT. | |
| """ | |
| # 1. Role Validation: Determine what roles the current user is allowed to assign/manage | |
| allowed_roles = [] | |
| user_role = current_user.role | |
| # Platform Super Admins have absolute global authority | |
| if current_user.is_platform_admin or user_role == UserRole.SUPERADMIN: | |
| allowed_roles = [r for r in UserRole] | |
| # Internal Staff (Admins and Leads) can manage both customers and other staff | |
| elif user_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD]: | |
| # They can always manage customers | |
| allowed_roles = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER, UserRole.SC_AGENT, UserRole.SC_LEAD] | |
| # Only SC_ADMIN can promote/create other SC_ADMINs | |
| if user_role == UserRole.SC_ADMIN: | |
| allowed_roles.append(UserRole.SC_ADMIN) | |
| # Customer Admins can only manage their own organization's users | |
| elif user_role == UserRole.CUSTOMER_ADMIN: | |
| allowed_roles = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER] | |
| # Stringify the target role for comparison and cleaner error messages | |
| target_role = str(payload.role.value if hasattr(payload.role, 'value') else payload.role) | |
| allowed_role_strs = [str(r.value if hasattr(r, 'value') else r) for r in allowed_roles] | |
| if target_role not in allowed_role_strs: | |
| raise HTTPException( | |
| status_code=403, | |
| detail=f"Permission denied: Your role ({user_role}) cannot assign/manage the role: {target_role}" | |
| ) | |
| # 2. Duplicate Check (excluding soft-deleted users) | |
| stmt = select(User).where(User.email == payload.email, User.deleted_at.is_(None)) | |
| result = await db.execute(stmt) | |
| if result.scalar_one_or_none(): | |
| raise HTTPException(status_code=400, detail="User with this email already exists") | |
| # 3. Creation | |
| new_user = User( | |
| email=payload.email, | |
| real_email=payload.real_email or payload.email, | |
| hashed_password=get_password_hash(payload.password), | |
| full_name=payload.full_name, | |
| team=payload.team.upper() if payload.team else None, | |
| is_active=True | |
| ) | |
| db.add(new_user) | |
| await db.flush() # Get user id | |
| # 4. Create Workspace Association | |
| # Priority: Payload WS (for admins) > Current Context WS | |
| target_ws = payload.workspace_id or current_user.workspace_id | |
| logger.info(f"π€ Provisioning user {new_user.email} into workspace {target_ws} (Requested by: {current_user.id})") | |
| new_link = UserWorkspace( | |
| user_id=new_user.id, | |
| workspace_id=target_ws, | |
| role=payload.role, | |
| is_primary=True | |
| ) | |
| db.add(new_link) | |
| await db.commit() | |
| await db.refresh(new_user) | |
| log_action( | |
| background_tasks, | |
| workspace_id=target_ws, | |
| entity_type="user", | |
| entity_id=new_user.id, | |
| action="admin_user_create", | |
| user_id=current_user.id, | |
| new_value={"email": new_user.email, "role": payload.role} | |
| ) | |
| # Attach context for response | |
| setattr(new_user, "role", payload.role) | |
| setattr(new_user, "workspace_id", target_ws) | |
| logger.info(f"User created: {new_user.email} (Role: {payload.role}) in workspace {target_ws}") | |
| # Invalidate List Cache | |
| from core.cache import delete_by_pattern | |
| await delete_by_pattern(f"users:list:*:{target_ws}*") | |
| return new_user | |
| async def read_user_me(current_user: User = Depends(get_current_user)) -> Any: | |
| return current_user | |
| async def update_user_me( | |
| payload: UserUpdate, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| for field, value in payload.model_dump(exclude_unset=True).items(): | |
| setattr(current_user, field, value) | |
| db.add(current_user) | |
| await db.commit() | |
| await db.refresh(current_user) | |
| # Proactive Cache Invalidation | |
| from core.cache import invalidate_cache | |
| await invalidate_cache(f"user:profile:{current_user.id}") | |
| return current_user | |
| async def list_users( | |
| request: Request, | |
| workspace_id: Optional[str] = None, | |
| skip: int = 0, limit: int = 100, | |
| mention: bool = False, | |
| bypass_cache: bool = False, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """List users - many-to-many aware (Cached 15m).""" | |
| # 0. Role Class Normalization for Cache Isolation | |
| from core.cache import get_cached_object, set_cached_object, SemanticCacheManager | |
| # Ensure role is stringified correctly for normalization | |
| raw_role = str(current_user.global_role or current_user.role or "customer_user") | |
| role_class = SemanticCacheManager._normalize_role_class(raw_role) | |
| portal = request.headers.get("X-Nexus-Portal", "unknown") | |
| # 1. Check for Global Visibility (Platform Super Admin ONLY) | |
| is_global = (workspace_id == "all" and current_user.is_platform_admin) | |
| if is_global: | |
| target_ws = None | |
| else: | |
| from core.permissions import get_effective_context | |
| target_ws, _ = await get_effective_context(db, current_user, workspace_id) | |
| # Secure Cache Key: Includes portal and role_class to prevent cross-persona pollution | |
| cache_key = f"users:list:{portal}:{role_class}:{'global' if is_global else target_ws}:{skip}:{limit}:{mention}" | |
| if not bypass_cache: | |
| cached = await get_cached_object(cache_key) | |
| if cached: | |
| logger.info(f"β‘ Cache HIT [User List]: {target_ws} ({role_class} persona, mention={mention})") | |
| return cached | |
| else: | |
| logger.info(f"π Cache BYPASS [User List]: {target_ws} ({role_class} persona) requested by {current_user.id}") | |
| # When bypassing cache, also clear the specific key to ensure consistency | |
| from core.cache import invalidate_cache | |
| await invalidate_cache(cache_key) | |
| # 2. Build Query | |
| from sqlalchemy import or_ | |
| # Secure Retrieval: Fetch User and their workspace-specific role/status in one go | |
| # For Internal Portal, we use outer join to include platform admins who might not have a link to this specific WS | |
| is_internal = (portal == "internal") | |
| stmt = ( | |
| select(User, UserWorkspace.role, UserWorkspace.is_active) | |
| .join(UserWorkspace, User.id == UserWorkspace.user_id, isouter=is_internal) | |
| .where(User.deleted_at.is_(None)) | |
| ) | |
| if is_global: | |
| # Platform-wide view (Used by platform admins) | |
| # Filter out duplicates if a user has multiple associations | |
| stmt = stmt.distinct(User.id) | |
| else: | |
| # STRICT isolation: ONLY users associated with this workspace OR global superadmins (for internal view) | |
| if is_internal: | |
| stmt = stmt.where(or_( | |
| UserWorkspace.workspace_id == target_ws, | |
| User.global_role == UserRole.SUPERADMIN | |
| )) | |
| else: | |
| stmt = stmt.where(UserWorkspace.workspace_id == target_ws) | |
| stmt = stmt.where(UserWorkspace.is_active.is_(True)) | |
| # --- PORTAL ISOLATION & MENTION LOGIC --- | |
| if mention: | |
| if portal == "customer": | |
| # Customers mentioning: show INTERNAL STAFF (Agents/Leads/Admins) | |
| stmt = stmt.where(cast(UserWorkspace.role, String).notin_(['customer_user', 'customer_admin'])) | |
| else: | |
| # Internal Portal mentioning: show EVERYONE in the workspace | |
| pass | |
| else: | |
| # Default view (Team/List) | |
| if portal == "customer": | |
| # Customers should only see other Customers in their workspace list (Privacy) | |
| stmt = stmt.where(cast(UserWorkspace.role, String).ilike('customer%')) | |
| # Internal portal sees everyone by default | |
| # Finalize query with deterministic ordering | |
| stmt = stmt.order_by(User.full_name).offset(skip).limit(limit) | |
| result = await db.execute(stmt) | |
| rows = result.all() # Result will be list of (User, role, is_active) | |
| logger.info(f"π [User List] DB returned {len(rows)} raw rows for {target_ws}") | |
| users_map = {} | |
| for u, role, is_active in rows: | |
| uid_str = str(u.id) | |
| if uid_str in users_map: | |
| # If we already have this user, but this row has the ACTUAL workspace role we want, | |
| # prioritize it over a global/fallback role. | |
| # We check if the current row has a role and the stored one is just a fallback. | |
| existing_user, existing_role = users_map[uid_str] | |
| if role and not existing_role: | |
| # Update with better role info | |
| pass | |
| else: | |
| continue | |
| # Role Fallback: If no workspace-specific role (due to outer join), use global role | |
| final_role = role or u.global_role or "customer_user" | |
| setattr(u, "role", final_role) | |
| setattr(u, "is_active", is_active if is_active is not None else True) | |
| # Workspace ID Fallback: UserResponse requires a workspace_id. | |
| if not hasattr(u, "workspace_id") or u.workspace_id is None: | |
| try: | |
| from uuid import UUID | |
| setattr(u, "workspace_id", UUID(target_ws) if isinstance(target_ws, str) else target_ws) | |
| except Exception: | |
| pass | |
| users_map[uid_str] = (u, role) | |
| final_users = [val[0] for val in users_map.values()] | |
| logger.info(f"β [User List] Deduplicated to {len(final_users)} unique users") | |
| # 3. Cache the result | |
| from schemas.user import UserResponse | |
| res_payload = [UserResponse.model_validate(u).model_dump(mode='json') for u in final_users] | |
| if not is_global: | |
| await set_cached_object(cache_key, res_payload, ttl=900) | |
| return res_payload | |
| async def revoke_user_access( | |
| user_id: str, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db), | |
| background_tasks: BackgroundTasks = BackgroundTasks() | |
| ) -> Any: | |
| """ | |
| Revoke user access for the CURRENT workspace. | |
| Marks UserWorkspace association as inactive instead of deleting the global user. | |
| """ | |
| stmt = select(UserWorkspace).where( | |
| UserWorkspace.user_id == user_id, | |
| UserWorkspace.workspace_id == current_user.workspace_id | |
| ) | |
| result = await db.execute(stmt) | |
| association = result.scalar_one_or_none() | |
| if not association: | |
| raise HTTPException(status_code=404, detail="Membership not found in this workspace") | |
| association.is_active = False | |
| db.add(association) | |
| await db.commit() | |
| log_action( | |
| background_tasks, | |
| workspace_id=current_user.workspace_id, | |
| entity_type="user", | |
| entity_id=user_id, | |
| action="workspace_access_revoked", | |
| user_id=current_user.id | |
| ) | |
| # Invalidate Cache | |
| from core.cache import delete_by_pattern | |
| await delete_by_pattern(f"users:list:*:{current_user.workspace_id}*") | |
| logger.info(f"Access revoked for user {user_id} in workspace {current_user.workspace_id} by admin {current_user.id}") | |
| return {"status": "revoked"} | |
| async def legacy_delete_proxy(user_id: str, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db), background_tasks: BackgroundTasks = BackgroundTasks()): | |
| """Alias DELETE to Revoke for frontend compatibility without breaking existing flows.""" | |
| return await revoke_user_access(user_id, current_user, db, background_tasks) | |
| async def update_user_admin( | |
| user_id: str, | |
| payload: UserAdminUpdate, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db), | |
| background_tasks: BackgroundTasks = BackgroundTasks() | |
| ) -> Any: | |
| """ | |
| Administratively update another user's role or status. | |
| Uses the same hierarchy logic as creation. | |
| """ | |
| # 1. Fetch User (Global check) | |
| stmt = select(User).where(User.id == user_id, 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 not found") | |
| # 2. Fetch Association for CURRENT workspace | |
| assoc_stmt = select(UserWorkspace).where( | |
| UserWorkspace.user_id == user_id, | |
| UserWorkspace.workspace_id == current_user.workspace_id | |
| ) | |
| association = (await db.execute(assoc_stmt)).scalar_one_or_none() | |
| if not association: | |
| raise HTTPException(status_code=403, detail="User is not in your workspace") | |
| update_data = payload.model_dump(exclude_unset=True) | |
| # Role validation | |
| if "role" in update_data: | |
| allowed_roles = [] | |
| user_role = current_user.role | |
| # Absolute Authority for Platform Admins | |
| if current_user.is_platform_admin or user_role == UserRole.SUPERADMIN: | |
| allowed_roles = [r for r in UserRole] | |
| # Internal Staff management (Customers + Staff) | |
| elif user_role in [UserRole.SC_ADMIN, UserRole.SC_LEAD]: | |
| allowed_roles = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER, UserRole.SC_AGENT, UserRole.SC_LEAD] | |
| if user_role == UserRole.SC_ADMIN: | |
| allowed_roles.append(UserRole.SC_ADMIN) | |
| # Customer isolation | |
| elif user_role == UserRole.CUSTOMER_ADMIN: | |
| allowed_roles = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER] | |
| target_role = str(update_data["role"].value if hasattr(update_data["role"], 'value') else update_data["role"]) | |
| allowed_role_strs = [str(r.value if hasattr(r, 'value') else r) for r in allowed_roles] | |
| if target_role not in allowed_role_strs: | |
| raise HTTPException( | |
| status_code=403, | |
| detail=f"Permission denied: Your role ({user_role}) cannot assign/manage the role: {target_role}" | |
| ) | |
| # Update association role, not user role | |
| association.role = update_data.pop("role") | |
| # Update other User fields (name, avatar, etc) | |
| for field, value in update_data.items(): | |
| setattr(user, field, value) | |
| db.add(user) | |
| db.add(association) | |
| await db.commit() | |
| log_action( | |
| background_tasks, | |
| workspace_id=current_user.workspace_id, | |
| entity_type="user", | |
| entity_id=user.id, | |
| action="admin_user_update", | |
| user_id=current_user.id, | |
| new_value=update_data | |
| ) | |
| await db.refresh(user) | |
| # Inject context for response | |
| setattr(user, "role", association.role) | |
| setattr(user, "workspace_id", current_user.workspace_id) | |
| logger.info(f"User {user_id} updated by admin {current_user.id}: {update_data}") | |
| # Invalidate Cache | |
| from core.cache import invalidate_cache, delete_by_pattern | |
| await invalidate_cache(f"user:profile:{user_id}") | |
| await delete_by_pattern(f"users:list:*:{current_user.workspace_id}*") | |
| return user | |