import logging from django.http import Http404, HttpResponseForbidden from django.shortcuts import redirect from inventory import models from django.utils import timezone from inventory.utils import get_user_type logger = logging.getLogger("user_activity") # class LogUserActivityMiddleware: # """ # Middleware for logging user activity. # This middleware logs the activity of authenticated users each time they make a # request. It creates an entry in the UserActivityLog model capturing the user's # ID, the action performed, and the timestamp. It is intended to assist in # tracking user actions across the application for analytics or auditing purposes. # :ivar get_response: The next middleware or view in the WSGI request-response # chain. # :type get_response: Callable # """ # def __init__(self, get_response): # self.get_response = get_response # def __call__(self, request): # response = self.get_response(request) # if request.user.is_authenticated: # action = f"{request.method} {request.path}" # models.UserActivityLog.objects.create( # user=request.user, action=action, timestamp=timezone.now() # ) # return response # def get_client_ip(self, request): # x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") # if x_forwarded_for: # return x_forwarded_for.split(",")[0] # return request.META.get("REMOTE_ADDR") class InjectParamsMiddleware: """ Middleware to add processed user-related parameters to the request object. This middleware processes incoming requests to extract and enhance user information, specifically linking user context such as `dealer` to the request. It allows subsequent views and middlewares to access these enriched request parameters with ease. :ivar get_response: The callable to get the next middleware or view response. :type get_response: Callable """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: if request.user.is_authenticated: request.dealer = get_user_type(request) request.entity = request.dealer.entity else: request.dealer = None except Exception: pass response = self.get_response(request) return response class InjectDealerMiddleware: """ Middleware to inject user role attributes into the request object. This middleware assigns boolean attributes to the request object to indicate whether the user is a dealer or a staff member. It checks for the presence of specific user attributes (`dealer` and `staffmember`) and sets corresponding flags accordingly. The middleware is designed to support role-based processing in requests. :ivar get_response: The callable provided by the Django framework to process the next middleware or the view in the request-response cycle. :type get_response: Callable """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: if request.user.is_authenticated: request.is_dealer = False request.is_staff = False if hasattr(request.user, "dealer"): request.is_dealer = True elif hasattr(request.user, "staffmember"): request.is_staff = True except Exception: pass response = self.get_response(request) return response # class OTPVerificationMiddleware: # def __init__(self, get_response): # self.get_response = get_response # # def __call__(self, request): # if request.user.is_authenticated and not request.session.get('otp_verified', False): # return redirect(reverse('verify_otp')) # return self.get_response(request) class DealerSlugMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): if request.path_info.startswith('/ar/signup/') or \ request.path_info.startswith('/en/signup/') or \ request.path_info.startswith('/ar/login/') or \ request.path_info.startswith('/en/login/') or \ request.path_info.startswith('/ar/logout/') or \ request.path_info.startswith('/en/logout/') or \ request.path_info.startswith('/en/ledger/') or \ request.path_info.startswith('/ar/ledger/') or \ request.path_info.startswith('/en/notifications/') or \ request.path_info.startswith('/ar/notifications/') or \ request.path_info.startswith('/en/appointment/') or \ request.path_info.startswith('/ar/appointment/'): return None if not request.user.is_authenticated: return None dealer_slug = view_kwargs.get("dealer_slug") if not dealer_slug: return None if not hasattr(request, 'dealer') or not request.dealer: logger.warning("No dealer associated with request") return None if dealer_slug.lower() != request.dealer.slug.lower(): logger.warning(f"Dealer slug mismatch: {dealer_slug} != {request.dealer.slug}") raise Http404("Dealer slug mismatch") return None