Spaces:
Paused
Paused
Download api/v1/users.py from 3SCError404/nexus: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/spaces/3SCError404/nexus/resolve/main/api/v1/users.py
- Command line
-
hf download hf://spaces/3SCError404/nexus/api/v1/users.py
-
curl -L -o users.py https://huggingface.co/spaces/3SCError404/nexus/resolve/main/api/v1/users.py
10.5 kB
| """ | |
| User endpoints: profile and admin management. | |
| """ | |
| from datetime import datetime | |
| 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 core.security import get_password_hash | |
| from core.logging import get_logger | |
| 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) | |
| ) -> 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 | |
| allowed_roles = [] | |
| if current_user.role == UserRole.CUSTOMER_ADMIN: | |
| allowed_roles = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER] | |
| elif current_user.role == UserRole.SC_ADMIN: | |
| allowed_roles = [UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SC_ADMIN] | |
| if payload.role not in allowed_roles: | |
| raise HTTPException( | |
| status_code=403, | |
| detail=f"You do not have permission to assign the role: {payload.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 | |
| # Note: Use current_user.workspace_id (the active context) | |
| new_link = UserWorkspace( | |
| user_id=new_user.id, | |
| workspace_id=current_user.workspace_id, | |
| role=payload.role, | |
| is_primary=True # For simplicity, first association is primary | |
| ) | |
| db.add(new_link) | |
| await db.commit() | |
| await db.refresh(new_user) | |
| # Attach context for response (UserResponse expects role/workspace_id) | |
| setattr(new_user, "role", payload.role) | |
| setattr(new_user, "workspace_id", current_user.workspace_id) | |
| logger.info(f"User created: {new_user.email} (Role: {payload.role}) in workspace {current_user.workspace_id}") | |
| # Invalidate List Cache | |
| from core.cache import delete_by_pattern | |
| await delete_by_pattern(f"users:list:{current_user.workspace_id}*") | |
| 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( | |
| workspace_id: Optional[str] = None, | |
| skip: int = 0, limit: int = 100, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| """List users - many-to-many aware (Cached 15m).""" | |
| from core.cache import get_cached_object, set_cached_object | |
| target_ws = workspace_id if (workspace_id and current_user.is_platform_admin) else current_user.workspace_id | |
| is_global = (workspace_id == "all" and current_user.is_platform_admin) | |
| cache_key = f"users:list:{'global' if is_global else target_ws}:{skip}:{limit}" | |
| cached = await get_cached_object(cache_key) | |
| if cached: | |
| logger.info(f"⚡ Cache HIT [User List]: {target_ws}") | |
| return cached | |
| # 1. Check for Global Visibility (Platform Super Admin ONLY) | |
| is_global = (workspace_id == "all" and current_user.is_platform_admin) | |
| stmt = select(User).join(UserWorkspace, User.id == UserWorkspace.user_id) | |
| if is_global: | |
| # Platform-wide view | |
| pass | |
| else: | |
| # Strict Isolation | |
| target_ws = workspace_id if (workspace_id and current_user.is_platform_admin) else current_user.workspace_id | |
| stmt = stmt.where(UserWorkspace.workspace_id == target_ws) | |
| # Role hierarchy for local admins | |
| if current_user.role == UserRole.CUSTOMER_ADMIN: | |
| allowed_roles = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER] | |
| stmt = stmt.where(UserWorkspace.role.in_(allowed_roles)) | |
| elif current_user.role == UserRole.SC_LEAD: | |
| allowed_roles = [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT] | |
| stmt = stmt.where(UserWorkspace.role.in_(allowed_roles)) | |
| stmt = stmt.where(User.deleted_at.is_(None)).offset(skip).limit(limit) | |
| result = await db.execute(stmt) | |
| users = result.scalars().all() | |
| # 2. Inject context for the response | |
| for u in users: | |
| # Determine the workspace context for role discovery | |
| # If global, we use the user's primary/active context for role lookup | |
| context_ws = current_user.workspace_id if is_global else target_ws | |
| # Performance: find role for response context (safely fallback to primary if global) | |
| assoc_stmt = select(UserWorkspace.role).where( | |
| UserWorkspace.user_id == u.id | |
| ) | |
| if not is_global: | |
| assoc_stmt = assoc_stmt.where(UserWorkspace.workspace_id == context_ws) | |
| u_role = (await db.execute(assoc_stmt.limit(1))).scalar() or UserRole.CUSTOMER_USER | |
| setattr(u, "role", u_role) | |
| setattr(u, "workspace_id", context_ws) | |
| # 3. Cache the result | |
| from schemas.user import UserResponse | |
| res_payload = [UserResponse.model_validate(u).model_dump(mode='json') for u in users] | |
| await set_cached_object(cache_key, res_payload, ttl=900) | |
| return res_payload | |
| async def deactivate_user_v3( | |
| user_id: str, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> Any: | |
| stmt = select(User).where( | |
| User.id == user_id, | |
| User.workspace_id == current_user.workspace_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") | |
| user.is_active = False | |
| user.deleted_at = datetime.utcnow() | |
| user.deleted_by_id = current_user.id | |
| db.add(user) | |
| await db.commit() | |
| # 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}*") | |
| logger.info(f"User deactivated/soft-deleted: {user_id} by admin {current_user.id}") | |
| return {"status": "deleted"} | |
| async def update_user_admin( | |
| user_id: str, | |
| payload: UserAdminUpdate, | |
| current_user: User = Depends(get_current_user), | |
| db: AsyncSession = Depends(get_db) | |
| ) -> 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 = [] | |
| if current_user.role == UserRole.CUSTOMER_ADMIN: | |
| allowed_roles = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER] | |
| elif current_user.role == UserRole.SC_ADMIN: | |
| allowed_roles = [UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SC_ADMIN] | |
| if update_data["role"] not in allowed_roles: | |
| raise HTTPException(status_code=403, detail=f"Permission denied for role: {update_data['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() | |
| 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 | |