from django.urls import reverse from django.utils import timezone import datetime class ReferrerMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Check if the user is anonymous and going to the login page if not request.user.is_authenticated and request.path == reverse('login'): # Get the referring URL from the HTTP_REFERER header referrer = request.META.get('HTTP_REFERER') # Only store referrer if it exists and is not the login page itself if referrer and 'login' not in referrer: request.session['login_referrer'] = referrer response = self.get_response(request) return response class RegistrationCartCleanupMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): self._check_and_clean_expired_cart(request) response = self.get_response(request) return response def _check_and_clean_expired_cart(self, request): if 'registration_cart_expiry' in request.session: try: expiry_str = request.session['registration_cart_expiry'] expiry = datetime.datetime.fromisoformat(expiry_str) if timezone.now() > expiry: # Clear expired cart keys_to_delete = [ 'registration_cart_id', 'registration_tournament_id', 'registration_cart_players', 'registration_cart_expiry', 'registration_mobile_number' ] for key in keys_to_delete: if key in request.session: del request.session[key] request.session.modified = True except (ValueError, TypeError): # Invalid expiry format, clear it if 'registration_cart_expiry' in request.session: del request.session['registration_cart_expiry'] request.session.modified = True