1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-11-08 19:26:48 +00:00
webvirtcloud/accounts/middleware.py
catborise 0610c23a34 fix(api): an error's status says what it is, and its body is always {"detail"}
- libvirt errors all answered 400. A VM, pool or volume the host does not
  have now answers 404, a volume in use 409 (vrtManager.util.InUse) and a
  host that cannot be reached 503, which a client may retry.
- A template's power on or cycle and a stopped pool answered
  {"status": ...} with 409; they answer {"detail": ...}, as every other
  refusal. The schema documents these 409s (ErrorSerializer).
- The volume list and a volume of a stopped pool answered 200 with an
  empty list or a made-up volume; they answer 409.
- An API URL that names nothing answered the HTML error page; it answers
  a JSON 404 after the API's authentication.
- A session that must change its password was redirected to the HTML
  form; an API request of it gets the JSON 403 a token gets.
2026-11-07 13:29:46 +03:00

30 lines
1.2 KiB
Python

from django.http import JsonResponse
from django.shortcuts import redirect
from django.utils.translation import gettext as _
from django.urls import Resolver404, resolve
from accounts.models import UserAttributes
ALLOWED_VIEWS = {"accounts:change_password", "accounts:logout", "accounts:login"}
class ForcePasswordChangeMiddleware:
"""Send users who must change their password (the generated admin one, or one
an administrator set) to the change form."""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.user.is_authenticated and UserAttributes.objects.filter(
user=request.user, must_change_password=True
).exists():
try:
view_name = resolve(request.path_info).view_name
except Resolver404:
view_name = None
if view_name not in ALLOWED_VIEWS:
if request.path_info.startswith("/api/"): # as for a token (accounts.auth)
return JsonResponse({"detail": _("Change your password before using the API.")}, status=403)
return redirect("accounts:change_password")
return self.get_response(request)