from django.conf import settings
from django.shortcuts import redirect
from django.urls import reverse
from urllib.parse import quote


class LoginRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.exempt_urls = [
            reverse("login"),
            reverse("logout"),
            reverse("admin:login"),
            reverse("admin:index"),
        ] + getattr(settings, "LOGIN_EXEMPT_URLS", [])

    def __call__(self, request):
        if not request.user.is_authenticated:
            path = request.path_info
            if not any(path.startswith(url) for url in self.exempt_urls):
                if request.method == "GET":
                    if request.get_full_path() and request.get_full_path() != "/":
                        return redirect(
                            f"{settings.LOGIN_URL}?next={quote(request.get_full_path())}"
                        )
                return redirect(settings.LOGIN_URL)
        return self.get_response(request)
