from collections.abc import Callable from django.contrib.auth import logout from django.http import HttpRequest, HttpResponse from django.shortcuts import redirect from django.urls import reverse from apps.users.container import check_login_allowed class EnsureAccountIsUsable: """Ends the session at once when the user is deactivated or the internship has ended. The reason travels in the URL (``?access=ended``) so the login page can explain it. """ def __init__(self, get_response: Callable[[HttpRequest], HttpResponse]) -> None: self.get_response = get_response def __call__(self, request: HttpRequest) -> HttpResponse: user = request.user if user.is_authenticated and not check_login_allowed().execute(user.pk): logout(request) url = f"{reverse('users:login')}?access=ended" if request.headers.get("HX-Request") == "true": response = HttpResponse(status=204) response["HX-Redirect"] = url return response return redirect(url) return self.get_response(request)