"""The operations console (WEB-30..33, WEB-40..44, roadmap A9). Every view and every action checks the specific permission; being logged in, or being staff, is not enough.""" from django.contrib import messages from django.contrib.auth.views import redirect_to_login from django.core.exceptions import PermissionDenied, ValidationError from django.http import Http404 from django.shortcuts import redirect, render from django.views.decorators.cache import never_cache from django.views.decorators.http import require_http_methods from apps.lottery import console from apps.lottery.models import LotteryConfig def _gate(request, allowed: bool): """Anonymous visitors go to sign-in; anyone signed in without the permission gets 403.""" if not request.user.is_authenticated: return redirect_to_login(request.get_full_path(), "/accedi/") if not allowed: raise PermissionDenied return None @never_cache @require_http_methods(["GET"]) def dashboard(request): if (denied := _gate(request, console.can_view(request.user))) is not None: return denied state = console.console_state() commands = [ {"command": c, "on": console.is_on(c, state["config"]), "title": console.title(c, state["config"]), "allowed": console.can_run(request.user, c), "reason": state["pause_reasons"][c.key]} for c in console.COMMANDS.values() ] return render(request, "ops/dashboard.html", {**state, "commands": commands}) @never_cache @require_http_methods(["GET", "POST"]) def command(request, key: str): cmd = console.COMMANDS.get(key) if cmd is None: raise Http404 if request.user.is_authenticated and not (console.can_view(request.user) and console.can_run(request.user, cmd)): if request.method == "POST": try: console.run_command(request.user, cmd, True, "") # refuses, and records the refusal in the audit except PermissionDenied: pass raise PermissionDenied if (denied := _gate(request, True)) is not None: return denied config = LotteryConfig.get() enable = not console.is_on(cmd, config) state = console.console_state() context = {"cmd": cmd, "enable": enable, "title": console.title(cmd, config), **state, "reason_text": ""} if request.method == "POST": # The page was rendered for one direction; a stale form must not flip the switch back. wanted = request.POST.get("enable") == "1" reason = request.POST.get("reason", "") context["reason_text"] = reason if request.POST.get("confirm") != "1": context["error"] = "Conferma di aver letto cosa comporta." else: try: changed = console.run_command(request.user, cmd, wanted, reason) except ValidationError as error: context["error"] = error.messages[0] else: if changed: messages.success(request, f"Comando eseguito: {cmd.title_on if wanted else cmd.title_off}.") else: messages.info(request, "Il comando era già nello stato richiesto: nulla è cambiato.") return redirect("ops:dashboard") return render(request, "ops/command.html", context)