| 1 | from fastapi import APIRouter |
| 2 | from fastapi import Depends |
| 3 | from fastapi import HTTPException |
| 4 | from fastapi import Security |
| 5 | from loguru import logger |
| 6 | from sqlalchemy.ext.asyncio import AsyncSession |
| 7 | from sqlalchemy.future import select |
| 8 | |
| 9 | from app.auth.utils import AuthHandler |
| 10 | from app.customer_provisioning.schema.decommission import DecommissionCustomerResponse |
| 11 | from app.customer_provisioning.services.decommission import decomission_wazuh_customer |
| 12 | from app.db.db_session import get_db |
| 13 | from app.db.universal_models import CustomersMeta |
| 14 | |
| 15 | # App specific imports |
| 16 | |
| 17 | |
| 18 | customer_decommissioning_router = APIRouter() |
| 19 | |
| 20 | |
| 21 | async def check_customermeta_exists( |
| 22 | customer_code: str, |
| 23 | session: AsyncSession = Depends(get_db), |
| 24 | ) -> CustomersMeta: |
| 25 | """ |
| 26 | Check if a customer exists in the database. |
| 27 | |
| 28 | Args: |
| 29 | customer_code (str): The customer code of the customer to check. |
| 30 | session (AsyncSession, optional): The database session. Defaults to Depends(get_db). |
| 31 | |
| 32 | Returns: |
| 33 | CustomersMeta: The customer object if found. |
| 34 | |
| 35 | Raises: |
| 36 | HTTPException: If the customer is not found. |
| 37 | """ |
| 38 | logger.info(f"Checking if customer {customer_code} exists") |
| 39 | result = await session.execute( |
| 40 | select(CustomersMeta).filter(CustomersMeta.customer_code == customer_code), |
| 41 | ) |
| 42 | customer_meta = result.scalars().first() |
| 43 | |
| 44 | if not customer_meta: |
| 45 | raise HTTPException( |
| 46 | status_code=404, |
| 47 | detail=f"Customer: {customer_code} not found. Please create the customer first.", |
| 48 | ) |
| 49 | |
| 50 | return customer_meta |
| 51 | |
| 52 | |
| 53 | @customer_decommissioning_router.post( |
| 54 | "/decommission", |
| 55 | response_model=DecommissionCustomerResponse, |
| 56 | description="Decommission Customer", |
| 57 | dependencies=[Security(AuthHandler().require_any_scope("admin", "analyst"))], |
| 58 | ) |
| 59 | async def decommission_customer_route( |
| 60 | _customer: CustomersMeta = Depends(check_customermeta_exists), |
| 61 | session: AsyncSession = Depends(get_db), |
| 62 | ): |
| 63 | """ |
| 64 | Decommission Customer Route |
| 65 | |
| 66 | This route is used to decommission a customer. It requires the user to have either the "admin" or "analyst" scope. |
| 67 | |
| 68 | Parameters: |
| 69 | - _customer (CustomersMeta): The customer metadata. |
| 70 | - session (AsyncSession): The database session. |
| 71 | |
| 72 | Returns: |
| 73 | - DecommissionCustomerResponse: The response model containing the decommissioned customer information. |
| 74 | """ |
| 75 | logger.info("Decommissioning customer") |
| 76 | customer_decommission = await decomission_wazuh_customer(_customer, session=session) |
| 77 | return customer_decommission |