expalert/frontend/views/panic.py
2023-12-04 16:09:40 +01:00

85 lines
2.7 KiB
Python

from django.views.generic import TemplateView
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.http.response import JsonResponse
from django.utils import timezone
from ..models import Panic
@method_decorator(login_required, name='dispatch')
@method_decorator(csrf_exempt, name='dispatch') # TODO: Fix this
class PanicView(TemplateView):
"""A view that enables or disables panic mode
"""
def post(self, request, *args, **kwargs) -> JsonResponse:
"""Enable or disable panic mode
Args:
request (HttpRequest): The request
*args: Additional arguments
**kwargs: Additional keyword arguments
Returns:
JsonResponse: The response
"""
try:
data = request.POST
enable = data["panic"] in (True, "true")
if enable:
if Panic.active():
return JsonResponse({"success": False, "error": "Panic mode is already active"})
panic = Panic.objects.create(created_by_user=request.user, create_reason=data["reason"])
panic.save()
return JsonResponse({"success": True})
else:
if not (panic := Panic.active()):
return JsonResponse({"success": False, "error": "Panic mode is not active"})
panic.resolved_by_user = request.user
panic.resolve_reason = data["reason"]
panic.resolved_at = timezone.now()
panic.save()
return JsonResponse({"success": True})
except KeyError:
return JsonResponse({"success": False, "error": "Missing panic mode parameter"})
except:
return JsonResponse({"success": False, "error": "Unknown error"})
def get(self, request, *args, **kwargs) -> JsonResponse:
"""Return information about panic mode
Args:
request (HttpRequest): The request
*args: Additional arguments
**kwargs: Additional keyword arguments
Returns:
JsonResponse: The response
"""
panic = Panic.active()
if panic:
return JsonResponse({
"success": True,
"active": True,
"created_by": panic.created_by_user.username,
"created_at": panic.created_at,
"create_reason": panic.create_reason,
})
else:
return JsonResponse({
"success": True,
"active": False,
})