import logging

from django.shortcuts import redirect, render
from django.utils.deprecation import MiddlewareMixin
from django.utils.cache import add_never_cache_headers

logger = logging.getLogger(__name__)


class AuthMiddleware(MiddlewareMixin):
    exempted_urls = [
        '/', '/logout', '/favicon.ico','/contact-us','/welfare-scheme','/photo-gallery','/video-gallery','/about', '/news', '/site-map','/screen-reader','/reset_password/','/login'
    ]

    def process_request(self, request):
        if request.path.startswith('/captcha') or request.path.startswith('/admin') or request.path.startswith('/media'):
            return
        if request.path in self.exempted_urls:
            return
        if request.user.is_authenticated:
            return
        
        logger.error(f'Requested Path: {request.path}')
        return redirect('login')

    @staticmethod
    def process_response(request, response):
        add_never_cache_headers(response)
        response.headers['Server'] = ''
        if response.status_code == 404:
            logger.error(f'Requested Path: {request.path}')
            return render(request, '404.html')
        if response.status_code == 500:
            logger.error(f'Requested Path: {request.path}')
            return render(request, '500.html')
        return response
