Spaces:
Running
Running
Download backend/app/api/team.py from axeronis/microfunnel-api: direct link, hf CLI and curl.
- Browser
- Download file 7.69 kB
-
https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/team.py
- Command line
-
hf download hf://spaces/axeronis/microfunnel-api/backend/app/api/team.py
-
curl -L -o team.py https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/team.py
7.69 kB
| """ | |
| Team Management API - Managing users within a tenant | |
| """ | |
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from sqlmodel import select | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from pydantic import BaseModel, EmailStr | |
| from typing import List, Optional | |
| from uuid import UUID | |
| from app.core.database import get_async_session | |
| from app.core.logging import get_logger | |
| from app.api.deps import get_current_user | |
| from app.models.user import User, UserRole | |
| from app.models.tenant import Tenant | |
| logger = get_logger(__name__) | |
| router = APIRouter(prefix="/team", tags=["team"]) | |
| # ==================== SCHEMAS ==================== | |
| class CreateManagerRequest(BaseModel): | |
| """Request to create a new manager""" | |
| email: EmailStr | |
| full_name: str | |
| password: str | |
| class ManagerResponse(BaseModel): | |
| """Manager user response""" | |
| id: str | |
| email: str | |
| full_name: Optional[str] | |
| role: str | |
| is_active: bool | |
| created_at: str | |
| class TeamMembersResponse(BaseModel): | |
| """Team members list response""" | |
| members: List[ManagerResponse] | |
| class MessageResponse(BaseModel): | |
| """Generic message response""" | |
| message: str | |
| # ==================== ENDPOINTS ==================== | |
| async def get_team_members( | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Get all team members (OWNER + MANAGERs) for current tenant | |
| Only OWNER can access this endpoint | |
| """ | |
| if current_user.role != UserRole.OWNER: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Only OWNER can view team members" | |
| ) | |
| # Get all users in the same tenant | |
| result = await session.execute( | |
| select(User).where(User.tenant_id == current_user.tenant_id) | |
| ) | |
| users = result.scalars().all() | |
| members = [ | |
| ManagerResponse( | |
| id=str(user.id), | |
| email=user.email, | |
| full_name=user.full_name, | |
| role=user.role, | |
| is_active=user.is_active, | |
| created_at=user.created_at.isoformat() | |
| ) | |
| for user in users | |
| ] | |
| return TeamMembersResponse(members=members) | |
| async def create_manager( | |
| body: CreateManagerRequest, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Create a new MANAGER user for the current tenant | |
| Only OWNER can create managers | |
| Managers inherit the same tenant_id as the OWNER | |
| """ | |
| if current_user.role != UserRole.OWNER: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Only OWNER can create managers" | |
| ) | |
| # Validate password strength | |
| if len(body.password) < 8: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="Password must be at least 8 characters long" | |
| ) | |
| # Check if email already exists | |
| result = await session.execute( | |
| select(User).where(User.email == body.email) | |
| ) | |
| existing_user = result.scalar_one_or_none() | |
| if existing_user: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="User with this email already exists" | |
| ) | |
| # Create manager user with same tenant_id as OWNER | |
| hashed_password = User.get_password_hash(body.password) | |
| new_manager = User( | |
| email=body.email, | |
| hashed_password=hashed_password, | |
| full_name=body.full_name, | |
| tenant_id=current_user.tenant_id, # Same tenant as OWNER | |
| role=UserRole.MANAGER, # MANAGER role | |
| is_active=True | |
| ) | |
| session.add(new_manager) | |
| await session.commit() | |
| await session.refresh(new_manager) | |
| logger.info( | |
| "Manager created", | |
| manager_email=new_manager.email, | |
| tenant_id=str(current_user.tenant_id), | |
| created_by=current_user.email | |
| ) | |
| return ManagerResponse( | |
| id=str(new_manager.id), | |
| email=new_manager.email, | |
| full_name=new_manager.full_name, | |
| role=new_manager.role, | |
| is_active=new_manager.is_active, | |
| created_at=new_manager.created_at.isoformat() | |
| ) | |
| async def delete_manager( | |
| user_id: UUID, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Delete a MANAGER user | |
| Only OWNER can delete managers | |
| Cannot delete OWNER | |
| """ | |
| if current_user.role != UserRole.OWNER: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Only OWNER can delete managers" | |
| ) | |
| # Find the user | |
| result = await session.execute( | |
| select(User).where(User.id == user_id) | |
| ) | |
| user_to_delete = result.scalar_one_or_none() | |
| if not user_to_delete: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail="User not found" | |
| ) | |
| # Check same tenant | |
| if user_to_delete.tenant_id != current_user.tenant_id: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Cannot delete user from another tenant" | |
| ) | |
| # Cannot delete OWNER | |
| if user_to_delete.role == UserRole.OWNER: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="Cannot delete OWNER" | |
| ) | |
| await session.delete(user_to_delete) | |
| await session.commit() | |
| logger.info( | |
| "Manager deleted", | |
| manager_email=user_to_delete.email, | |
| deleted_by=current_user.email | |
| ) | |
| return MessageResponse(message="Manager deleted successfully") | |
| async def toggle_manager_status( | |
| user_id: UUID, | |
| current_user: User = Depends(get_current_user), | |
| session: AsyncSession = Depends(get_async_session) | |
| ): | |
| """ | |
| Toggle manager active/inactive status | |
| Only OWNER can toggle status | |
| Cannot toggle OWNER status | |
| """ | |
| if current_user.role != UserRole.OWNER: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Only OWNER can toggle manager status" | |
| ) | |
| # Find the user | |
| result = await session.execute( | |
| select(User).where(User.id == user_id) | |
| ) | |
| manager = result.scalar_one_or_none() | |
| if not manager: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail="User not found" | |
| ) | |
| # Check same tenant | |
| if manager.tenant_id != current_user.tenant_id: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Cannot modify user from another tenant" | |
| ) | |
| # Cannot toggle OWNER | |
| if manager.role == UserRole.OWNER: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="Cannot toggle OWNER status" | |
| ) | |
| # Toggle status | |
| manager.is_active = not manager.is_active | |
| await session.commit() | |
| status_text = "активирован" if manager.is_active else "деактивирован" | |
| logger.info( | |
| f"Manager {status_text}", | |
| manager_email=manager.email, | |
| new_status=manager.is_active, | |
| changed_by=current_user.email | |
| ) | |
| return MessageResponse(message=f"Менеджер {status_text}") | |