from django.shortcuts import redirect
from django.conf import settings
from django.urls import reverse

EXEMPT_URLS = [
    reverse('login'),
    reverse('logout'),
]

class LoginRequiredMiddleware:
    """
    Redirect users to login page if they're not authenticated,
    unless the URL is exempt.
    """
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        path = request.path_info

        if not request.user.is_authenticated and not any(path.startswith(url) for url in EXEMPT_URLS):
            if not path.startswith(settings.STATIC_URL):
                return redirect(settings.LOGIN_URL)

        return self.get_response(request)
