From 4c15d90a6a68308f42a917d8d90ac0593122d9f2 Mon Sep 17 00:00:00 2001 From: Iliyan Angelov Date: Sat, 29 Nov 2025 14:49:53 +0200 Subject: [PATCH] updates --- backEnd/contact/views.py | 9 +++++++ backEnd/gnx/middleware/csrf_exempt.py | 37 +++++++++++++++++++++++++++ backEnd/gnx/settings.py | 1 + 3 files changed, 47 insertions(+) create mode 100644 backEnd/gnx/middleware/csrf_exempt.py diff --git a/backEnd/contact/views.py b/backEnd/contact/views.py index 976ce0e6..ee9b7182 100644 --- a/backEnd/contact/views.py +++ b/backEnd/contact/views.py @@ -62,6 +62,15 @@ class ContactSubmissionViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] return [permission() for permission in permission_classes] + def get_authenticators(self): + """ + Override authentication for create action to bypass CSRF. + By returning an empty list, DRF won't enforce CSRF for this action. + """ + if hasattr(self, 'action') and self.action == 'create': + return [] + return super().get_authenticators() + def create(self, request, *args, **kwargs): """ Create a new contact submission. diff --git a/backEnd/gnx/middleware/csrf_exempt.py b/backEnd/gnx/middleware/csrf_exempt.py new file mode 100644 index 00000000..a05b0d96 --- /dev/null +++ b/backEnd/gnx/middleware/csrf_exempt.py @@ -0,0 +1,37 @@ +""" +CSRF Exemption Middleware +Exempts CSRF checks for specific public API endpoints that don't require authentication. +""" + +from django.utils.deprecation import MiddlewareMixin +import re + + +class CSRFExemptMiddleware(MiddlewareMixin): + """ + Middleware to exempt CSRF for public API endpoints. + Runs before CSRF middleware to set the exemption flag. + """ + + # Paths that should be exempt from CSRF (public endpoints) + # Patterns match both with and without trailing slashes + EXEMPT_PATHS = [ + r'^/api/contact/submissions/?$', # Contact form submission + r'^/api/career/applications/?$', # Job application submission (if needed) + r'^/api/support/tickets/?$', # Support ticket creation (if needed) + ] + + def process_request(self, request): + """ + Set CSRF exemption flag for matching paths. + """ + if request.method == 'POST': + path = request.path + for pattern in self.EXEMPT_PATHS: + if re.match(pattern, path): + # Set flag to bypass CSRF check + setattr(request, '_dont_enforce_csrf_checks', True) + break + + return None + diff --git a/backEnd/gnx/settings.py b/backEnd/gnx/settings.py index 00db7acd..3327973c 100644 --- a/backEnd/gnx/settings.py +++ b/backEnd/gnx/settings.py @@ -68,6 +68,7 @@ MIDDLEWARE = [ 'gnx.middleware.api_security.FrontendAPIProxyMiddleware', # Validate requests from frontend/nginx 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', + 'gnx.middleware.csrf_exempt.CSRFExemptMiddleware', # Exempt CSRF for public API endpoints 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',