Refactor Omada class methods for clarity; update device blocking logic in DeviceBlockAPIView and improve user verification error handling
Some checks failed
Build and Push Docker Images / Build and Push Docker Images (push) Failing after 3m14s

This commit is contained in:
2025-06-23 23:14:40 +05:00
parent 9688635f44
commit 570cf80019
4 changed files with 36 additions and 14 deletions

View File

@ -20,7 +20,7 @@ class Omada:
if not self.group_id: if not self.group_id:
raise ValueError("OMADA_GROUP_ID is not set in the environment variables.") raise ValueError("OMADA_GROUP_ID is not set in the environment variables.")
def get_existing_omada_devices(self): def _get_existing_omada_devices(self):
""" """
Get existing Omada devices from the database. Get existing Omada devices from the database.
:return: List of existing device names. :return: List of existing device names.
@ -64,7 +64,7 @@ class Omada:
"portMaskList": None, "portMaskList": None,
"domainNamePort": None, "domainNamePort": None,
} }
existing_devices = self.get_existing_omada_devices() existing_devices = self._get_existing_omada_devices()
PAYLOAD["macAddressList"] = existing_devices PAYLOAD["macAddressList"] = existing_devices
print("Payload with existing devices: ", PAYLOAD) print("Payload with existing devices: ", PAYLOAD)
for device in new_devices: for device in new_devices:
@ -91,3 +91,22 @@ class Omada:
print(f"Failed to add devices: {response.text}") print(f"Failed to add devices: {response.text}")
except requests.RequestException as e: except requests.RequestException as e:
print(f"Error adding devices to Omada: {e}") print(f"Error adding devices to Omada: {e}")
def block_device(self, mac_address: str, operation: str = "block"):
"""
Block a device in Omada.
:param mac_address: The MAC address of the device to block.
"""
try:
url = f"{self.proxy_url}/9fd0cffa3475a74ae4e4d37de0d12414/api/v2/sites/{self.site_id}/cmd/clients/{mac_address}/{operation}"
response = requests.post(
url,
headers={"X-API-Key": str(self.api_key)},
)
if response.status_code == 200:
data = response.json()
return data
else:
print(f"Failed to block device: {response.text}")
except requests.RequestException as e:
print(f"Error blocking device in Omada: {e}")

View File

@ -55,14 +55,6 @@ def deactivate_expired_devices():
} }
def get_existing_omada_devices():
"""
Get existing Omada devices from Omada API via Omada class.
:return: List of existing device names.
"""
return omada_client.get_existing_omada_devices()
@shared_task @shared_task
def add_new_devices_to_omada(new_devices: list[dict]): def add_new_devices_to_omada(new_devices: list[dict]):
""" """
@ -77,7 +69,13 @@ def verify_user_with_person_api_task(user_id: int):
Verify the user with the Person API. Verify the user with the Person API.
:param user_id: The ID of the user to verify. :param user_id: The ID of the user to verify.
""" """
if not user_id:
logger.error("User ID is not provided.")
return None
user = get_object_or_404(User, id=user_id) user = get_object_or_404(User, id=user_id)
if not user:
logger.error(f"User with ID {user_id} not found.")
return None
# Call the Person API to verify the user # Call the Person API to verify the user
verification_failed_message = f""" verification_failed_message = f"""
@ -91,7 +89,7 @@ def verify_user_with_person_api_task(user_id: int):
Visit [SAR Link Portal](https://portal.sarlink.net) to manually verify this user. Visit [SAR Link Portal](https://portal.sarlink.net) to manually verify this user.
""" """
logger.info(verification_failed_message) # logger.info(verification_failed_message)
PERSON_VERIFY_BASE_URL = env.str("PERSON_VERIFY_BASE_URL", default="") # type: ignore PERSON_VERIFY_BASE_URL = env.str("PERSON_VERIFY_BASE_URL", default="") # type: ignore
if not PERSON_VERIFY_BASE_URL: if not PERSON_VERIFY_BASE_URL:
@ -174,5 +172,7 @@ def verify_user_with_person_api_task(user_id: int):
return False return False
else: else:
# Handle the error case # Handle the error case
print(f"Error verifying user: {response.status_code} - {response.text}") print(
f"Error verifying user with api: {response.status_code} - {response.text}"
)
return return

View File

@ -61,8 +61,6 @@ class ErrorMessages:
@api_view(["GET"]) @api_view(["GET"])
def healthcheck(request): def healthcheck(request):
add.delay(1, 2) add.delay(1, 2)
# devices = Device.objects.filter(is_active=False).values()
# add_new_devices_to_omada.delay(new_devices=list(devices))
return Response({"status": "Good"}, status=status.HTTP_200_OK) return Response({"status": "Good"}, status=status.HTTP_200_OK)

View File

@ -11,6 +11,7 @@ from .serializers import (
BlockDeviceSerializer, BlockDeviceSerializer,
) )
from api.mixins import StaffEditorPermissionMixin from api.mixins import StaffEditorPermissionMixin
from api.omada import Omada
from .filters import DeviceFilter from .filters import DeviceFilter
import re import re
import requests import requests
@ -127,6 +128,10 @@ class DeviceBlockAPIView(StaffEditorPermissionMixin, generics.UpdateAPIView):
if not isinstance(blocked, bool): if not isinstance(blocked, bool):
return Response({"message": "Blocked field must be a boolean."}, status=400) return Response({"message": "Blocked field must be a boolean."}, status=400)
instance.blocked = blocked instance.blocked = blocked
omada_client = Omada()
omada_client.block_device(
instance.mac, operation="block" if blocked else "unblock"
)
instance.save() instance.save()
serializer = self.get_serializer(instance, data=request.data, partial=False) serializer = self.get_serializer(instance, data=request.data, partial=False)
serializer.is_valid(raise_exception=True) serializer.is_valid(raise_exception=True)