Инициализация в новом репозитории
This commit is contained in:
commit
eb1f18f53e
374 changed files with 226678 additions and 0 deletions
0
SRV/api/v1/__init__.py
Normal file
0
SRV/api/v1/__init__.py
Normal file
114
SRV/api/v1/auth.py
Normal file
114
SRV/api/v1/auth.py
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
# api/v1/auth.py
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from services.auth_service import AuthService
|
||||
from models.auth import UserCreate, UserLogin, UserResponse, Token
|
||||
from storage.json_storage import JsonStorage
|
||||
import logging
|
||||
import os
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
auth_service = AuthService()
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
|
||||
|
||||
|
||||
@router.post("/register", response_model=UserResponse)
|
||||
async def register(user: UserCreate):
|
||||
"""Регистрирует нового пользователя"""
|
||||
try:
|
||||
db_user = auth_service.register(user)
|
||||
logger.info(f"Пользователь {user.username} успешно зарегистрирован")
|
||||
return db_user
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка в register: {type(e).__name__} - {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="Не удалось зарегистрировать пользователя")
|
||||
|
||||
|
||||
@router.post("/login", response_model=Token)
|
||||
async def login(user: UserLogin, request: Request):
|
||||
"""Авторизует пользователя и создаёт сессию"""
|
||||
try:
|
||||
client_id = request.client.host
|
||||
logger.debug(f"Попытка авторизации для client_id {client_id}")
|
||||
result = auth_service.login(user, client_id)
|
||||
logger.info(f"Успешная авторизация для client_id {client_id}, session_id: {result['session_id']}")
|
||||
return result
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка в login: {type(e).__name__} - {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="Не удалось авторизовать пользователя")
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_current_user(request: Request):
|
||||
"""Возвращает данные текущего пользователя и токен"""
|
||||
try:
|
||||
client_id = request.client.host
|
||||
logger.debug(f"Запрос /me для client_id {client_id}")
|
||||
result = auth_service.get_user_by_session(client_id)
|
||||
return {
|
||||
"user": result["user"],
|
||||
"access_token": result["access_token"],
|
||||
"token_type": "bearer"
|
||||
}
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка в get_current_user: {type(e).__name__} - {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="Не удалось получить данные пользователя")
|
||||
|
||||
|
||||
@router.get("/logout")
|
||||
async def logout(request: Request):
|
||||
"""Выход из системы, удаление сессии"""
|
||||
try:
|
||||
client_id = request.client.host
|
||||
logger.debug(f"Запрос logout для client_id {client_id}")
|
||||
return auth_service.logout(client_id)
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка в logout: {type(e).__name__} - {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="Не удалось выйти из системы")
|
||||
|
||||
|
||||
@router.get("/check_json")
|
||||
async def check_users_file():
|
||||
"""Проверяет, существует ли файл users.json и содержит ли он пользователей"""
|
||||
try:
|
||||
file_path = "/etc/gonets/users.json"
|
||||
storage = JsonStorage(file_path=file_path)
|
||||
|
||||
if not os.path.exists(file_path):
|
||||
logger.info(f"Файл {file_path} не существует")
|
||||
return {
|
||||
"exists": False,
|
||||
"has_users": False,
|
||||
"message": "Файл users.json не существует"
|
||||
}
|
||||
|
||||
data = storage._read_data()
|
||||
has_users = len(data.get("users", [])) > 0
|
||||
if has_users:
|
||||
logger.info(f"Файл {file_path} существует и содержит пользователей")
|
||||
return {
|
||||
"exists": True,
|
||||
"has_users": True,
|
||||
"message": "Файл users.json существует и содержит пользователей"
|
||||
}
|
||||
else:
|
||||
logger.info(f"Файл {file_path} существует, но не содержит пользователей")
|
||||
return {
|
||||
"exists": True,
|
||||
"has_users": False,
|
||||
"message": "Файл users.json существует, но не содержит пользователей"
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при проверке файла users.json: {type(e).__name__} - {str(e)}")
|
||||
raise HTTPException(status_code=500, detail="Ошибка при проверке файла")
|
||||
449
SRV/api/v1/firewalld.py
Normal file
449
SRV/api/v1/firewalld.py
Normal file
|
|
@ -0,0 +1,449 @@
|
|||
from typing import List
|
||||
|
||||
from fastapi import APIRouter, Body, HTTPException, Path, status
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from models.firewalld import (
|
||||
FirewallPort,
|
||||
FirewallService,
|
||||
FirewallSource,
|
||||
FirewallTarget,
|
||||
FirewallZone,
|
||||
)
|
||||
from services.firewalld_service import FirewalldService
|
||||
|
||||
router = APIRouter()
|
||||
firewalld = FirewalldService()
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
"""Standard error response model"""
|
||||
|
||||
detail: str = Field(..., description="Error description")
|
||||
|
||||
|
||||
class SuccessResponse(BaseModel):
|
||||
"""Standard success response model"""
|
||||
|
||||
message: str = Field(..., description="Success message")
|
||||
|
||||
|
||||
@router.get(
|
||||
"/zones",
|
||||
response_model=List[str],
|
||||
responses={500: {"model": ErrorResponse}},
|
||||
summary="Get all available zones",
|
||||
)
|
||||
async def get_zones() -> List[str]:
|
||||
"""
|
||||
Retrieve all available firewalld zones.
|
||||
|
||||
Returns:
|
||||
List[str]: List of zone names
|
||||
"""
|
||||
try:
|
||||
return firewalld.get_zones()
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to get zones: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/zones/default",
|
||||
response_model=str,
|
||||
responses={500: {"model": ErrorResponse}},
|
||||
summary="Get default zone",
|
||||
)
|
||||
async def get_default_zone() -> str:
|
||||
"""
|
||||
Get the current default zone.
|
||||
|
||||
Returns:
|
||||
str: Name of the default zone
|
||||
"""
|
||||
try:
|
||||
return firewalld.get_default_zone()
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to get default zone: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/zones/default/{zone}",
|
||||
response_model=SuccessResponse,
|
||||
responses={404: {"model": ErrorResponse}, 500: {"model": ErrorResponse}},
|
||||
summary="Set default zone",
|
||||
)
|
||||
async def set_default_zone(
|
||||
zone: str = Path(..., description="Zone name to set as default"),
|
||||
) -> SuccessResponse:
|
||||
"""
|
||||
Set the default zone.
|
||||
|
||||
Args:
|
||||
zone (str): Name of the zone to set as default
|
||||
|
||||
Returns:
|
||||
SuccessResponse: Success confirmation message
|
||||
"""
|
||||
try:
|
||||
firewalld.set_default_zone(zone)
|
||||
return SuccessResponse(message=f"Default zone set to {zone}")
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=f"Zone '{zone}' not found"
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to set default zone: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/zones/{zone}",
|
||||
response_model=FirewallZone,
|
||||
responses={404: {"model": ErrorResponse}, 500: {"model": ErrorResponse}},
|
||||
summary="Get zone configuration",
|
||||
)
|
||||
async def get_zone(zone: str = Path(..., description="Zone name")) -> FirewallZone:
|
||||
"""
|
||||
Get detailed configuration for a specific zone.
|
||||
|
||||
Args:
|
||||
zone (str): Name of the zone
|
||||
|
||||
Returns:
|
||||
FirewallZone: Zone configuration details
|
||||
"""
|
||||
try:
|
||||
zone_info = firewalld.get_zone_settings(zone)
|
||||
return FirewallZone(
|
||||
name=zone,
|
||||
target=FirewallTarget.DEFAULT,
|
||||
interfaces=[],
|
||||
**zone_info
|
||||
)
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=f"Zone '{zone}' not found"
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to get zone settings: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/zones/{zone}/services",
|
||||
response_model=List[str],
|
||||
responses={500: {"model": ErrorResponse}},
|
||||
summary="Get services in zone",
|
||||
)
|
||||
async def get_services(zone: str = Path(..., description="Zone name")) -> List[str]:
|
||||
"""
|
||||
Get all services in a zone.
|
||||
|
||||
Args:
|
||||
zone (str): Name of the zone
|
||||
|
||||
Returns:
|
||||
List[str]: List of service names
|
||||
"""
|
||||
try:
|
||||
return firewalld.get_services(zone)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to get services: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/zones/{zone}/services",
|
||||
response_model=SuccessResponse,
|
||||
responses={404: {"model": ErrorResponse}, 500: {"model": ErrorResponse}},
|
||||
summary="Add service to zone",
|
||||
)
|
||||
async def add_service(
|
||||
zone: str = Path(..., description="Zone name"),
|
||||
rule: FirewallService = Body(..., description="Service configuration"),
|
||||
) -> SuccessResponse:
|
||||
"""
|
||||
Add a service to a zone.
|
||||
|
||||
Args:
|
||||
zone (str): Name of the zone
|
||||
rule (FirewallService): Service configuration including service name and optional timeout
|
||||
|
||||
Returns:
|
||||
SuccessResponse: Success confirmation message
|
||||
"""
|
||||
try:
|
||||
firewalld.add_service(zone, rule.name, rule.timeout)
|
||||
return SuccessResponse(message=f"Service {rule.name} added to zone {zone}")
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=f"Zone '{zone}' not found"
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to add service: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/zones/{zone}/services/{service}",
|
||||
response_model=SuccessResponse,
|
||||
responses={404: {"model": ErrorResponse}, 500: {"model": ErrorResponse}},
|
||||
summary="Remove service from zone",
|
||||
)
|
||||
async def remove_service(
|
||||
zone: str = Path(..., description="Zone name"),
|
||||
service: str = Path(..., description="Service name"),
|
||||
) -> SuccessResponse:
|
||||
"""
|
||||
Remove a service from a zone.
|
||||
|
||||
Args:
|
||||
zone (str): Name of the zone
|
||||
service (str): Name of the service
|
||||
|
||||
Returns:
|
||||
SuccessResponse: Success confirmation message
|
||||
"""
|
||||
try:
|
||||
firewalld.remove_service(zone, service)
|
||||
return SuccessResponse(message=f"Service {service} removed from zone {zone}")
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Zone '{zone}' or service '{service}' not found",
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to remove service: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/zones/{zone}/ports",
|
||||
response_model=List[str],
|
||||
responses={500: {"model": ErrorResponse}},
|
||||
summary="Get ports in zone",
|
||||
)
|
||||
async def get_ports(zone: str = Path(..., description="Zone name")) -> List[str]:
|
||||
"""
|
||||
Get all ports in a zone.
|
||||
|
||||
Args:
|
||||
zone (str): Name of the zone
|
||||
|
||||
Returns:
|
||||
List[str]: List of port configurations
|
||||
"""
|
||||
try:
|
||||
return firewalld.get_ports(zone)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to get ports: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/zones/{zone}/ports",
|
||||
response_model=SuccessResponse,
|
||||
responses={
|
||||
400: {"model": ErrorResponse},
|
||||
404: {"model": ErrorResponse},
|
||||
500: {"model": ErrorResponse},
|
||||
},
|
||||
summary="Add port to zone",
|
||||
)
|
||||
async def add_port(
|
||||
zone: str = Path(..., description="Zone name"),
|
||||
rule: FirewallPort = Body(..., description="Port configuration"),
|
||||
) -> SuccessResponse:
|
||||
"""
|
||||
Add a port to a zone.
|
||||
|
||||
Args:
|
||||
zone (str): Name of the zone
|
||||
rule (FirewallPort): Port configuration including port number, protocol and optional timeout
|
||||
|
||||
Returns:
|
||||
SuccessResponse: Success confirmation message
|
||||
"""
|
||||
try:
|
||||
firewalld.add_port(zone, rule.port, rule.protocol.value, rule.timeout)
|
||||
return SuccessResponse(
|
||||
message=f"Port {rule.port}/{rule.protocol.value} added to zone {zone}"
|
||||
)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to add port: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/zones/{zone}/ports",
|
||||
response_model=SuccessResponse,
|
||||
responses={404: {"model": ErrorResponse}, 500: {"model": ErrorResponse}},
|
||||
summary="Remove port from zone",
|
||||
)
|
||||
async def remove_port(
|
||||
zone: str = Path(..., description="Zone name"),
|
||||
rule: FirewallPort = Body(..., description="Port configuration"),
|
||||
) -> SuccessResponse:
|
||||
"""
|
||||
Remove a port from a zone.
|
||||
|
||||
Args:
|
||||
zone (str): Name of the zone
|
||||
rule (FirewallPort): Port configuration including port number and protocol
|
||||
|
||||
Returns:
|
||||
SuccessResponse: Success confirmation message
|
||||
"""
|
||||
try:
|
||||
firewalld.remove_port(zone, rule.port, rule.protocol.value)
|
||||
return SuccessResponse(
|
||||
message=f"Port {rule.port}/{rule.protocol.value} removed from zone {zone}"
|
||||
)
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=f"Zone '{zone}' not found"
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to remove port: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/zones/{zone}/sources",
|
||||
response_model=List[str],
|
||||
responses={500: {"model": ErrorResponse}},
|
||||
summary="Get sources in zone",
|
||||
)
|
||||
async def get_sources(zone: str = Path(..., description="Zone name")) -> List[str]:
|
||||
"""
|
||||
Get all sources in a zone.
|
||||
|
||||
Args:
|
||||
zone (str): Name of the zone
|
||||
|
||||
Returns:
|
||||
List[str]: List of source addresses
|
||||
"""
|
||||
try:
|
||||
return firewalld.get_sources(zone)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to get sources: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/zones/{zone}/sources",
|
||||
response_model=SuccessResponse,
|
||||
responses={404: {"model": ErrorResponse}, 500: {"model": ErrorResponse}},
|
||||
summary="Add source to zone",
|
||||
)
|
||||
async def add_source(
|
||||
zone: str = Path(..., description="Zone name"),
|
||||
rule: FirewallSource = Body(..., description="Source configuration"),
|
||||
) -> SuccessResponse:
|
||||
"""
|
||||
Add a source to a zone.
|
||||
|
||||
Args:
|
||||
zone (str): Name of the zone
|
||||
rule (FirewallSource): Source configuration including source address
|
||||
|
||||
Returns:
|
||||
SuccessResponse: Success confirmation message
|
||||
"""
|
||||
try:
|
||||
firewalld.add_source(zone, rule.address)
|
||||
return SuccessResponse(message=f"Source {rule.address} added to zone {zone}")
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail=f"Zone '{zone}' not found"
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to add source: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/zones/{zone}/sources/{source}",
|
||||
response_model=SuccessResponse,
|
||||
responses={404: {"model": ErrorResponse}, 500: {"model": ErrorResponse}},
|
||||
summary="Remove source from zone",
|
||||
)
|
||||
async def remove_source(
|
||||
zone: str = Path(..., description="Zone name"),
|
||||
source: str = Path(..., description="Source address"),
|
||||
) -> SuccessResponse:
|
||||
"""
|
||||
Remove a source from a zone.
|
||||
|
||||
Args:
|
||||
zone (str): Name of the zone
|
||||
source (str): Source address
|
||||
|
||||
Returns:
|
||||
SuccessResponse: Success confirmation message
|
||||
"""
|
||||
try:
|
||||
firewalld.remove_source(zone, source)
|
||||
return SuccessResponse(message=f"Source {source} removed from zone {zone}")
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Zone '{zone}' or source '{source}' not found",
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to remove source: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/reload",
|
||||
response_model=SuccessResponse,
|
||||
responses={500: {"model": ErrorResponse}},
|
||||
summary="Reload firewall rules",
|
||||
)
|
||||
async def reload_firewall() -> SuccessResponse:
|
||||
"""
|
||||
Reload firewall rules.
|
||||
|
||||
Returns:
|
||||
SuccessResponse: Success confirmation message
|
||||
"""
|
||||
try:
|
||||
firewalld.reload()
|
||||
return SuccessResponse(message="Firewall rules reloaded successfully")
|
||||
except Exception as e:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to reload firewall rules: {str(e)}",
|
||||
)
|
||||
37
SRV/api/v1/ip.py
Normal file
37
SRV/api/v1/ip.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
from typing import Dict, Any
|
||||
from fastapi import APIRouter, Body, HTTPException
|
||||
from services.ip_service import IPService
|
||||
|
||||
router = APIRouter()
|
||||
ip_service = IPService()
|
||||
|
||||
@router.post("/check_ip")
|
||||
async def check_ip_config(data: Dict[str, Any] = Body(...)):
|
||||
""" Проверяет доступность IP-адреса """
|
||||
try:
|
||||
result = await ip_service.check_ip_config(data)
|
||||
return result
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка проверки IP конфигурации: {str(e)}")
|
||||
|
||||
@router.post("/apply_ip")
|
||||
async def apply_ip_config(data: Dict[str, Any] = Body(...)):
|
||||
""" Применяет проверенные IP-настройки """
|
||||
try:
|
||||
await ip_service.apply_ip_config(data)
|
||||
return {"success": True, "message": f"Настройки сетевого профиля для {data['connection_id']} применены"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка проверки IP конфигурации: {str(e)}")
|
||||
|
||||
@router.post("/save_ip")
|
||||
async def save_ip_config(data: Dict[str, Any] = Body(...)):
|
||||
""" Применяет проверенные IP-настройки (Нужен для того, чтобы откатить настройки сетевого профиля обратно) """
|
||||
try:
|
||||
await ip_service.apply_ip_config(data)
|
||||
return {"success": True, "message": f"Настройки сетевого профиля для {data['connection_id']} применены"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка проверки IP конфигурации: {str(e)}")
|
||||
128
SRV/api/v1/network.py
Normal file
128
SRV/api/v1/network.py
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
from fastapi import APIRouter, Body, HTTPException
|
||||
import logging
|
||||
from typing import Dict, Tuple, List, Union
|
||||
|
||||
from services.network_service import NetworkService
|
||||
from models.network import NetworkInterfacesContainer, Activation, Deactivation, NetworkInterface, WiFiDevice
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
network_service = NetworkService()
|
||||
|
||||
|
||||
class ContainerPositionManager:
|
||||
"""
|
||||
Класс для управления позициями и состоянием контейнеров
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.positions: Dict[str, Dict[str, Union[int, bool]]] = {
|
||||
'activation': {'x': 0, 'y': 0, 'isOpen': False},
|
||||
'deactivation': {'x': 0, 'y': 0, 'isOpen': False}
|
||||
}
|
||||
|
||||
def get_position_and_state(self, container_name: str) -> Tuple[int, int, bool]:
|
||||
container = self.positions.get(container_name)
|
||||
if not container:
|
||||
raise ValueError(f"Неверное имя контейнера: {container_name}")
|
||||
return container['x'], container['y'], container['isOpen']
|
||||
|
||||
def update_position(self, container_id: int, x: int, y: int, isOpen: bool) -> None:
|
||||
container_name = 'activation' if container_id == 1 else 'deactivation'
|
||||
self.positions[container_name] = {'x': x, 'y': y, 'isOpen': isOpen}
|
||||
|
||||
|
||||
container_manager = ContainerPositionManager()
|
||||
|
||||
|
||||
async def get_network_data() -> Dict[str, Dict]:
|
||||
"""
|
||||
Возвращает текущие сетевые данные в виде словаря
|
||||
"""
|
||||
logger.debug("Вызов get_network_data()")
|
||||
try:
|
||||
network_data = await network_service.get_network_interfaces_container()
|
||||
|
||||
activation_interfaces, deactivation_interfaces = _split_interfaces(network_data.interfaces)
|
||||
|
||||
activation_x, activation_y, activation_is_open = container_manager.get_position_and_state('activation')
|
||||
deactivation_x, deactivation_y, deactivation_is_open = container_manager.get_position_and_state('deactivation')
|
||||
|
||||
activation = Activation(
|
||||
id=1,
|
||||
interfaces=activation_interfaces,
|
||||
container_x=activation_x,
|
||||
container_y=activation_y,
|
||||
isOpen=activation_is_open
|
||||
)
|
||||
deactivation = Deactivation(
|
||||
id=2,
|
||||
interfaces=deactivation_interfaces,
|
||||
container_x=deactivation_x,
|
||||
container_y=deactivation_y,
|
||||
isOpen=deactivation_is_open
|
||||
)
|
||||
|
||||
return {
|
||||
"activation": activation.model_dump(),
|
||||
"deactivation": deactivation.model_dump()
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка в get_network_data: {e}")
|
||||
raise HTTPException(status_code=500, detail="Не удалось получить сетевые данные")
|
||||
|
||||
|
||||
def _split_interfaces(interfaces: List[Union[NetworkInterface, WiFiDevice]]) -> Tuple[
|
||||
List[Union[NetworkInterface, WiFiDevice]], List[Union[NetworkInterface, WiFiDevice]]]:
|
||||
"""
|
||||
Разделяет интерфейсы на активные и неактивные
|
||||
"""
|
||||
activation_interfaces = []
|
||||
deactivation_interfaces = []
|
||||
for interface in interfaces:
|
||||
if interface.device_state == '100':
|
||||
activation_interfaces.append(interface)
|
||||
else:
|
||||
deactivation_interfaces.append(interface)
|
||||
return activation_interfaces, deactivation_interfaces
|
||||
|
||||
|
||||
@router.post("/update_container_position")
|
||||
async def update_container_position(data: Dict[str, Union[int, bool]] = Body(...)):
|
||||
"""
|
||||
Обновляет позицию и состояние контейнера
|
||||
"""
|
||||
try:
|
||||
|
||||
required_keys = ["container_id", "container_x", "container_y", "isOpen"]
|
||||
if not all(key in data for key in required_keys):
|
||||
raise ValueError("Отсутствуют обязательные поля: container_id, container_x, container_y, isOpen")
|
||||
|
||||
container_id = data["container_id"]
|
||||
container_x = data["container_x"]
|
||||
container_y = data["container_y"]
|
||||
is_open = data["isOpen"]
|
||||
|
||||
# Проверка типов
|
||||
if not isinstance(container_id, int) or not isinstance(container_x, int) or not isinstance(container_y,
|
||||
int) or not isinstance(
|
||||
is_open, bool):
|
||||
raise ValueError("Неверный тип данных в запросе")
|
||||
|
||||
container_manager.update_position(container_id, container_x, container_y, is_open)
|
||||
return {"success": True, "message": "Позиция и состояние контейнера обновлены"}
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка обновления позиции контейнера: {e}")
|
||||
raise HTTPException(status_code=400, detail=f"Не удалось обновить положение контейнера: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/get_hostname")
|
||||
async def get_hostname():
|
||||
try:
|
||||
hostname_info = await network_service.get_hostname()
|
||||
return hostname_info
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка в get_hostname: {e}")
|
||||
raise HTTPException(status_code=500, detail="Не удалось получить имя хоста")
|
||||
28
SRV/api/v1/subnet.py
Normal file
28
SRV/api/v1/subnet.py
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
from fastapi import APIRouter, HTTPException
|
||||
from typing import List
|
||||
from models.subnet import SubnetScanResult
|
||||
from models.wifi import WifiScanResult
|
||||
from services.subnet_service import SubnetService
|
||||
from services.wifi_service import WifiService
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/scan", response_model=SubnetScanResult)
|
||||
def scan_subnet(subnet: str = "192.168.1.0/24", ports: List[int] = None):
|
||||
"""Сканирует локальную подсеть и возвращает данные об устройствах"""
|
||||
try:
|
||||
subnet_service = SubnetService()
|
||||
result = subnet_service.scan_subnet(subnet, ports)
|
||||
return result
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка сканирования: {str(e)}")
|
||||
|
||||
@router.get("/wifi", response_model=WifiScanResult)
|
||||
def scan_wifi(timeout: int = 30):
|
||||
"""Сканирует Wi-Fi точки доступа и возвращает данные о них"""
|
||||
try:
|
||||
wifi_service = WifiService()
|
||||
result = wifi_service.scan_wifi(timeout=timeout)
|
||||
return result
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка сканирования Wi-Fi: {str(e)}")
|
||||
134
SRV/api/v1/ufw.py
Normal file
134
SRV/api/v1/ufw.py
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
from fastapi import APIRouter, HTTPException
|
||||
from typing import List
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from models.ufw import UFWRulesResponse, UFWStatus, UFWRule
|
||||
from services.ufw_service import UFWService
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
class RuleNumbers(BaseModel):
|
||||
numbers: List[int] = Field(..., description="Список номеров правил для удаления")
|
||||
|
||||
@router.get("/rules", response_model=UFWRulesResponse)
|
||||
async def get_ufw_rules():
|
||||
"""
|
||||
Получает все правила UFW с помощью сервиса UFWService и возвращает их в формате JSON.
|
||||
"""
|
||||
ufw_service = UFWService()
|
||||
try:
|
||||
return ufw_service.get_ufw_rules()
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
|
||||
|
||||
@router.get("/status", response_model=UFWStatus)
|
||||
async def get_ufw_status():
|
||||
"""
|
||||
Получает текущий статус UFW.
|
||||
"""
|
||||
ufw_service = UFWService()
|
||||
try:
|
||||
return ufw_service.get_ufw_status()
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
|
||||
|
||||
@router.post("/enable")
|
||||
async def enable_ufw():
|
||||
"""
|
||||
Включает UFW.
|
||||
"""
|
||||
ufw_service = UFWService()
|
||||
try:
|
||||
success = ufw_service.enable_ufw()
|
||||
if success:
|
||||
return {"status": "success", "message": "UFW успешно включен"}
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail="Не удалось включить UFW")
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
|
||||
|
||||
@router.post("/disable")
|
||||
async def disable_ufw():
|
||||
"""
|
||||
Выключает UFW.
|
||||
"""
|
||||
ufw_service = UFWService()
|
||||
try:
|
||||
success = ufw_service.disable_ufw()
|
||||
if success:
|
||||
return {"status": "success", "message": "UFW успешно выключен"}
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail="Не удалось выключить UFW")
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
|
||||
|
||||
@router.post("/rules/in")
|
||||
async def add_ufw_in_rules(rules: List[UFWRule]):
|
||||
"""
|
||||
Добавляет входящие (in) правила UFW.
|
||||
"""
|
||||
ufw_service = UFWService()
|
||||
try:
|
||||
# Проверяем статус UFW
|
||||
status = ufw_service.get_ufw_status()
|
||||
if not status.enabled:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="UFW отключен. Включите UFW перед добавлением правил."
|
||||
)
|
||||
|
||||
result = ufw_service.add_rules(rules)
|
||||
if result["success"]:
|
||||
successful_rules = len([r for r in result["results"] if r["success"]])
|
||||
total_rules = len(result["results"])
|
||||
return {
|
||||
"status": "success",
|
||||
"message": f"Добавлено {successful_rules} из {total_rules} правил",
|
||||
"details": result
|
||||
}
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail=result.get("error", "Не удалось добавить правила"))
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
|
||||
|
||||
@router.post("/rules/out")
|
||||
async def add_ufw_out_rules(rules: List[UFWRule]):
|
||||
"""
|
||||
Добавляет исходящие (out) правила UFW.
|
||||
"""
|
||||
ufw_service = UFWService()
|
||||
try:
|
||||
# Проверяем статус UFW
|
||||
status = ufw_service.get_ufw_status()
|
||||
if not status.enabled:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="UFW отключен. Включите UFW перед добавлением правил."
|
||||
)
|
||||
|
||||
success = ufw_service.add_ufw_out_rules(rules)
|
||||
if success:
|
||||
return {"status": "success", "message": "Исходящие правила UFW успешно добавлены"}
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail="Не удалось добавить исходящие правила UFW")
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
|
||||
|
||||
@router.delete("/rules")
|
||||
async def delete_ufw_rules(rule_numbers: RuleNumbers):
|
||||
"""
|
||||
Удаляет правила UFW по их номерам.
|
||||
"""
|
||||
ufw_service = UFWService()
|
||||
try:
|
||||
result = ufw_service.delete_rules(rule_numbers.numbers)
|
||||
if result["success"]:
|
||||
return {
|
||||
"status": "success",
|
||||
"message": f"Удалено {result['successful']} из {result['total']} правил",
|
||||
"details": result
|
||||
}
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail=result["error"])
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
|
||||
90
SRV/api/v1/websocket.py
Normal file
90
SRV/api/v1/websocket.py
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import asyncio
|
||||
import logging
|
||||
from typing import Set
|
||||
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
from starlette.websockets import WebSocketState
|
||||
|
||||
from .network import update_container_position, get_network_data
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class WebSocketManager:
|
||||
"""
|
||||
Класс для управления подключениями к WebSocket-серверу
|
||||
"""
|
||||
def __init__(self):
|
||||
""" Инициализация менеджера подключений к WebSocket-серверу """
|
||||
self.active_connections: Set[WebSocket] = set()
|
||||
|
||||
async def connect(self, websocket: WebSocket):
|
||||
""" Подключение клиента к WebSocket-серверу """
|
||||
await websocket.accept()
|
||||
self.active_connections.add(websocket)
|
||||
|
||||
def disconnect(self, websocket: WebSocket):
|
||||
""" Отключение клиента от WebSocket-серверу """
|
||||
self.active_connections.remove(websocket)
|
||||
|
||||
async def broadcast(self, message: dict):
|
||||
""" Трансляция сообщений всем подключенным клиентам """
|
||||
for connection in list(self.active_connections):
|
||||
try:
|
||||
if connection.client_state == WebSocketState.CONNECTED:
|
||||
await connection.send_json(message)
|
||||
except WebSocketDisconnect:
|
||||
self.disconnect(connection)
|
||||
except Exception as e:
|
||||
logger.error(f"Сообщение об ошибке трансляции: {e}")
|
||||
self.disconnect(connection)
|
||||
|
||||
manager = WebSocketManager()
|
||||
|
||||
@router.websocket("/api/v1")
|
||||
async def websocket_endpoint(websocket: WebSocket):
|
||||
""" Обработчик WebSocket-соединения """
|
||||
await manager.connect(websocket)
|
||||
try:
|
||||
while True:
|
||||
data = await websocket.receive_json()
|
||||
logger.info(f"Полученные данные: {data}")
|
||||
|
||||
if all(key in data for key in ["container_id", "container_x", "container_y"]):
|
||||
await update_container_position(data)
|
||||
|
||||
network_data = await get_network_data()
|
||||
logger.info(f"Текущие сетевые данные: {network_data}")
|
||||
|
||||
await manager.broadcast(network_data)
|
||||
await asyncio.sleep(2)
|
||||
except WebSocketDisconnect:
|
||||
logger.info("Клиент отключен")
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка в websocket_endpoint:{e}")
|
||||
finally:
|
||||
manager.disconnect(websocket)
|
||||
if websocket.client_state != WebSocketState.DISCONNECTED:
|
||||
await websocket.close()
|
||||
|
||||
@router.on_event("startup")
|
||||
async def startup_event():
|
||||
""" Запуск таска для трансляции сетевых данных """
|
||||
asyncio.create_task(broadcast_data())
|
||||
|
||||
async def broadcast_data():
|
||||
""" Таск для трансляции сетевых данных """
|
||||
while True:
|
||||
try:
|
||||
network_data = await get_network_data()
|
||||
if "activation" not in network_data:
|
||||
logger.error("Ошибка: Ключ 'activation' отсутствует в полученных данных сети")
|
||||
await asyncio.sleep(2)
|
||||
continue
|
||||
|
||||
await manager.broadcast(network_data)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка в broadcast_data:{e}")
|
||||
await asyncio.sleep(2)
|
||||
Loading…
Add table
Add a link
Reference in a new issue