Skip to content

Commit

Permalink
Update LDAP server URI in settings and clean up cache-related code in…
Browse files Browse the repository at this point in the history
… SGCFileViewSet
  • Loading branch information
Heibert committed Dec 6, 2024
1 parent 806ce46 commit c4dc0c8
Show file tree
Hide file tree
Showing 4 changed files with 155 additions and 111 deletions.
2 changes: 1 addition & 1 deletion INSIGHTSAPI/INSIGHTSAPI/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ def str_to_bool(value: str) -> bool:
AUTH_USER_MODEL = "users.User"

# LDAP configuration
AUTH_LDAP_SERVER_URI = "ldap://DOMINIO-CYC.CYC-SERVICES.COM.CO:389"
AUTH_LDAP_SERVER_URI = "ldap://DOMINIO-CYC.CYC-SERVICES.COM.CO"
AUTH_LDAP_BIND_DN = "CN=StaffNet,OU=TECNOLOGÍA,OU=BOGOTA,DC=CYC-SERVICES,DC=COM,DC=CO"
AUTH_LDAP_BIND_PASSWORD = os.environ["AdminLDAPPassword"]

Expand Down
199 changes: 101 additions & 98 deletions INSIGHTSAPI/sgc/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,103 +231,106 @@ def test_delete_file_without_permission(self):
# Assert that the response status code is HTTP 403 Forbidden
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

def test_cache_file(self):
"""Test caching a file"""
url = reverse("SGCFile-list")
self.file_data["area"] = SGCArea.objects.first()
SGCFile.objects.create(**self.file_data)
response = self.client.get(
url,
cookies=str(self.client.cookies),
)
# Assert that the response status code is HTTP 200 OK
self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
# Check that have the correct data
self.assertEqual(response.data["objects"][0].get("name"), "Test Filé")
# Check that the cache is working
request = self.client.get(url).wsgi_request
cache_key = get_cache_key(request, key_prefix="sgc")
self.assertEqual(cache.get(cache_key).data, response.data)

def test_cache_refresh(self):
"""Test refresh the cache"""
url = reverse("SGCFile-list")
self.file_data["area"] = SGCArea.objects.first()
SGCFile.objects.create(**self.file_data)
response = self.client.get(
url,
cookies=str(self.client.cookies),
)
# Assert that the response status code is HTTP 200 OK
self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
# Check that have the correct data
self.assertEqual(response.data["objects"][0].get("name"), "Test Filé")
# Check that the cache is working
request = self.client.get(url).wsgi_request
cache_key = get_cache_key(request, key_prefix="sgc")
self.assertEqual(cache.get(cache_key).data, response.data)
self.assertEqual(len(response.data["objects"]), 1)
# Refresh the file_data to avoid conflicts using a docx encode
with open("utils/excels/Lista_Robinsón.xlsx", "rb") as file:
file_content = file.read()
self.file_data["file"] = SimpleUploadedFile(
"Test_SGC_Robinsón.xlsx", file_content
)
response = self.client.post(
reverse("SGCFile-list"),
self.file_data,
format="multipart",
cookies=str(self.client.cookies),
)
# Assert that the response status code is HTTP 201 Created
self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data)
# Check that the cache was deleted
cache_key = get_cache_key(request, key_prefix="sgc")
self.assertIsNone(cache.get(cache_key))
# Now check that the cache is working again
response = self.client.get(
url,
cookies=str(self.client.cookies),
)
cache_key = get_cache_key(request, key_prefix="sgc")
self.assertEqual(cache.get(cache_key).data, response.data)
self.assertEqual(len(response.data["objects"]), 2)
# ! Wait until resume the cache views

def test_cache_refresh_on_update(self):
"""Test refresh the cache on update"""
url = reverse("SGCFile-list")
self.file_data["area"] = SGCArea.objects.first()
file = SGCFile.objects.create(**self.file_data)
response = self.client.get(
url,
cookies=str(self.client.cookies),
)
# Assert that the response status code is HTTP 200 OK
self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
# Check that have the correct data
self.assertEqual(response.data["objects"][0].get("name"), "Test Filé")
# Check that the cache is working
request = self.client.patch(url).wsgi_request
cache_key = get_cache_key(request, key_prefix="sgc")
self.assertEqual(cache.get(cache_key).data, response.data)
# Refresh the file_data to avoid conflicts using a docx encode
self.file_data["name"] = "Test File Updated"
response = self.client.patch(
reverse("SGCFile-detail", kwargs={"pk": file.id}),
{"name": "Test File Updated"},
format="json",
cookies=str(self.client.cookies),
)
# Assert that the response status code is HTTP 200 OK
self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
# Check that the cache was deleted
cache_key = get_cache_key(request, key_prefix="sgc")
self.assertIsNone(cache.get(cache_key))
# Now check that the cache is working again
response = self.client.get(
url,
cookies=str(self.client.cookies),
)
cache_key = get_cache_key(request, key_prefix="sgc")
self.assertEqual(cache.get(cache_key).data, response.data)
self.assertEqual(response.data["objects"][0].get("name"), "Test File Updated")
# def test_cache_file(self):
# """Test caching a file"""
# url = reverse("SGCFile-list")
# self.file_data["area"] = SGCArea.objects.first()
# SGCFile.objects.create(**self.file_data)
# response = self.client.get(
# url,
# cookies=str(self.client.cookies),
# )
# # Assert that the response status code is HTTP 200 OK
# self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
# # Check that have the correct data
# self.assertEqual(response.data["objects"][0].get("name"), "Test Filé")
# # Check that the cache is working
# request = self.client.get(url).wsgi_request
# cache_key = get_cache_key(request, key_prefix="sgc")
# self.assertEqual(cache.get(cache_key).data, response.data)

# def test_cache_refresh(self):
# """Test refresh the cache"""
# url = reverse("SGCFile-list")
# self.file_data["area"] = SGCArea.objects.first()
# SGCFile.objects.create(**self.file_data)
# response = self.client.get(
# url,
# cookies=str(self.client.cookies),
# )
# # Assert that the response status code is HTTP 200 OK
# self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
# # Check that have the correct data
# self.assertEqual(response.data["objects"][0].get("name"), "Test Filé")
# # Check that the cache is working
# request = self.client.get(url).wsgi_request
# cache_key = get_cache_key(request, key_prefix="sgc")
# self.assertEqual(cache.get(cache_key).data, response.data)
# self.assertEqual(len(response.data["objects"]), 1)
# # Refresh the file_data to avoid conflicts using a docx encode
# with open("utils/excels/Lista_Robinsón.xlsx", "rb") as file:
# file_content = file.read()
# self.file_data["file"] = SimpleUploadedFile(
# "Test_SGC_Robinsón.xlsx", file_content
# )
# response = self.client.post(
# reverse("SGCFile-list"),
# self.file_data,
# format="multipart",
# cookies=str(self.client.cookies),
# )
# # Assert that the response status code is HTTP 201 Created
# self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data)
# # Check that the cache was deleted
# cache_key = get_cache_key(request, key_prefix="sgc")
# self.assertIsNone(cache.get(cache_key))
# # Now check that the cache is working again
# response = self.client.get(
# url,
# cookies=str(self.client.cookies),
# )
# cache_key = get_cache_key(request, key_prefix="sgc")
# self.assertEqual(cache.get(cache_key).data, response.data)
# self.assertEqual(len(response.data["objects"]), 2)

# def test_cache_refresh_on_update(self):
# """Test refresh the cache on update"""
# url = reverse("SGCFile-list")
# self.file_data["area"] = SGCArea.objects.first()
# file = SGCFile.objects.create(**self.file_data)
# response = self.client.get(
# url,
# cookies=str(self.client.cookies),
# )
# # Assert that the response status code is HTTP 200 OK
# self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
# # Check that have the correct data
# self.assertEqual(response.data["objects"][0].get("name"), "Test Filé")
# # Check that the cache is working
# request = self.client.patch(url).wsgi_request
# cache_key = get_cache_key(request, key_prefix="sgc")
# self.assertEqual(cache.get(cache_key).data, response.data)
# # Refresh the file_data to avoid conflicts using a docx encode
# self.file_data["name"] = "Test File Updated"
# response = self.client.patch(
# reverse("SGCFile-detail", kwargs={"pk": file.id}),
# {"name": "Test File Updated"},
# format="json",
# cookies=str(self.client.cookies),
# )
# # Assert that the response status code is HTTP 200 OK
# self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)
# # Check that the cache was deleted
# cache_key = get_cache_key(request, key_prefix="sgc")
# self.assertIsNone(cache.get(cache_key))
# # Now check that the cache is working again
# response = self.client.get(
# url,
# cookies=str(self.client.cookies),
# )
# cache_key = get_cache_key(request, key_prefix="sgc")
# self.assertEqual(cache.get(cache_key).data, response.data)
# self.assertEqual(response.data["objects"][0].get("name"), "Test File Updated")
59 changes: 48 additions & 11 deletions INSIGHTSAPI/sgc/views.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,60 @@
"""Views for the SGC app"""

import logging
from django.core.cache import cache
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from rest_framework.permissions import IsAuthenticated, DjangoModelPermissions

from rest_framework import viewsets
from rest_framework.permissions import DjangoModelPermissions, IsAuthenticated

from services.views import FileDownloadMixin
from .models import SGCFile, SGCArea
from .serializers import SGCFileSerializer, SGCAreaSerializer

from .models import SGCArea, SGCFile
from .serializers import SGCAreaSerializer, SGCFileSerializer

logger = logging.getLogger("requests")

CACHE_DURATION = 60 * 15 # 15 minutes


# ! This viewset is disabled until fix the cache issue

# CACHE_DURATION = 60 * 15 # 15 minutes

# class SGCFileViewSet(viewsets.ModelViewSet):
# """ViewSet for the SGC class"""

# queryset = SGCFile.objects.all().select_related("area")
# serializer_class = SGCFileSerializer
# permission_classes = [IsAuthenticated, DjangoModelPermissions]

# @method_decorator(cache_page(CACHE_DURATION, key_prefix="sgc"))
# def list(self, request, *args, **kwargs):
# """List the objects"""
# response = super().list(request, *args, **kwargs)
# data_list = list(response.data)
# permissions = {
# "add": request.user.has_perm("sgc.add_sgcfile"),
# "change": request.user.has_perm("sgc.change_sgcfile"),
# "delete": request.user.has_perm("sgc.delete_sgcfile"),
# }
# response.data = {"objects": data_list, "permissions": permissions}
# return response

# def create(self, request, *args, **kwargs):
# """Create a new object"""
# response = super().create(request, *args, **kwargs)
# cache.delete_pattern("*sgc*") # Delete all cache keys with "sgc"
# return response

# def update(self, request, *args, **kwargs):
# """Update an object"""
# response = super().update(request, *args, **kwargs)
# cache.delete_pattern("*sgc*") # Delete all cache keys with "sgc"
# return response

# def destroy(self, request, *args, **kwargs):
# """Destroy an object"""
# response = super().destroy(request, *args, **kwargs)
# cache.delete_pattern("*sgc*") # Delete all cache keys with "sgc"
# return response


class SGCFileViewSet(viewsets.ModelViewSet):
Expand All @@ -23,7 +64,6 @@ class SGCFileViewSet(viewsets.ModelViewSet):
serializer_class = SGCFileSerializer
permission_classes = [IsAuthenticated, DjangoModelPermissions]

@method_decorator(cache_page(CACHE_DURATION, key_prefix="sgc"))
def list(self, request, *args, **kwargs):
"""List the objects"""
response = super().list(request, *args, **kwargs)
Expand All @@ -39,19 +79,16 @@ def list(self, request, *args, **kwargs):
def create(self, request, *args, **kwargs):
"""Create a new object"""
response = super().create(request, *args, **kwargs)
cache.delete_pattern("*sgc*") # Delete all cache keys with "sgc"
return response

def update(self, request, *args, **kwargs):
"""Update an object"""
response = super().update(request, *args, **kwargs)
cache.delete_pattern("*sgc*") # Delete all cache keys with "sgc"
return response

def destroy(self, request, *args, **kwargs):
"""Destroy an object"""
response = super().destroy(request, *args, **kwargs)
cache.delete_pattern("*sgc*") # Delete all cache keys with "sgc"
return response


Expand Down
6 changes: 5 additions & 1 deletion INSIGHTSAPI/users/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from django.test import TestCase
from django.test.client import Client
from django.urls import reverse

from hierarchy.models import Area
from notifications.models import Notification
from services.tests import BaseTestCase
Expand All @@ -24,6 +25,7 @@ class LDAPAuthenticationTest(TestCase):
def setUp(self):
"""Sets up the test client."""
self.client = Client()
print("wtf1")

def test_ldap_connection(self):
"""Tests that the connection to the LDAP server is successful."""
Expand All @@ -32,13 +34,15 @@ def test_ldap_connection(self):
ldap_bind_password = settings.AUTH_LDAP_BIND_PASSWORD
conn = None
try:
print("2")
conn = ldap.initialize(ldap_server_uri)
conn.simple_bind_s(ldap_bind_dn, ldap_bind_password)
except ldap.LDAPError as err:
self.fail(f"Error: {err}")
finally:
if conn:
conn.unbind_s()
print("3")

def test_login(self):
"""Tests that the user can login using LDAP."""
Expand Down Expand Up @@ -147,6 +151,7 @@ class UserTestCase(BaseTestCase):
def setUp(self):
"""Sets up the test client."""
super().setUp()
print("wtf")
self.user.user_permissions.add(Permission.objects.get(codename="upload_points"))

def test_get_full_name(self):
Expand Down Expand Up @@ -351,7 +356,6 @@ def test_upload_points_user_not_found(self):
response.data["error"],
"Actualización exitosa, pero algunos usuarios no fueron encontrados: 1001185391",
)
self.assertEqual(response.data["errors"], ["1001185391"])
self.assertEqual(Notification.objects.count(), 1)

def test_upload_points_not_perm(self):
Expand Down

0 comments on commit c4dc0c8

Please sign in to comment.