A9: operations console, three pause commands, admin and player reports (WEB-30..32, WEB-40..44, WEB-55, AUD-48)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 15:03:22 +01:00
1 parent 3d1e820564
commit eab141f467
24 files changed
+928 -11

No files matched your search

+54 -1
View File
@@ -1,6 +1,59 @@
"""Users in the admin (WEB-32). Staff can deactivate or promote an account but never delete one: a user's
ledger rows are PROTECTed (DAT-76), and a deactivation is an audited action. A user's game records are shown
read-only on the same page."""
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from apps.lottery import audit
from apps.lottery.models import Movement, Participation
from .models import User
admin.site.register(User, UserAdmin)
class ReadOnlyInline(admin.TabularInline):
extra = 0
can_delete = False
show_change_link = False
def has_add_permission(self, request, obj=None):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
class ParticipationInline(ReadOnlyInline):
model = Participation
fields = ("round", "status", "bet_amount_sats", "created_at")
readonly_fields = fields
ordering = ("-id",)
max_num = 0
verbose_name_plural = "Participations (read-only)"
class MovementInline(ReadOnlyInline):
model = Movement
fields = ("kind", "status", "amount_sats", "round", "created_at")
readonly_fields = fields
ordering = ("-id",)
max_num = 0
verbose_name_plural = "Movements (read-only)"
@admin.register(User)
class AccountAdmin(UserAdmin):
inlines = [ParticipationInline, MovementInline]
def has_delete_permission(self, request, obj=None):
return False
def save_model(self, request, obj, form, change):
super().save_model(request, obj, form, change)
if change and {"is_active", "is_staff", "is_superuser"} & set(form.changed_data):
audit.record("user_changed", actor=request.user, subject_type="user", subject_id=obj.pk,
payload={name: getattr(obj, name) for name in ("is_active", "is_staff", "is_superuser")
if name in form.changed_data})
+7
View File
@@ -68,3 +68,10 @@ class PasswordChangeForm(forms.Form):
cleaned["new_password"] != cleaned["new_password_confirm"]:
self.add_error("new_password_confirm", "Le due password non coincidono.")
return cleaned
class ReportForm(forms.Form):
"""WEB-55: a problem report from the profile."""
text = forms.CharField(label="Descrivi il problema", min_length=5, max_length=1000, strip=True,
widget=forms.Textarea(attrs={"rows": 4, "maxlength": 1000}))
@@ -18,6 +18,23 @@
<button class="button" type="submit">Aggiorna la password</button>
</form>
</section>
<section class="card narrow" aria-labelledby="segnalazioni">
<h2 id="segnalazioni">Segnala un problema</h2>
<form method="post" action="{% url 'accounts:report' %}" novalidate>
{% csrf_token %}
{% include "accounts/_form_errors.html" with form=report_form %}
{% for field in report_form %}{% include "accounts/_field.html" %}{% endfor %}
<button class="button" type="submit">Invia la segnalazione</button>
</form>
{% if reports %}
<h3>Le tue segnalazioni</h3>
<ul class="plain">
{% for report in reports %}
<li><strong>{{ report.get_status_display }}</strong> · {{ report.created_at|date:"j F Y H:i" }} UTC<br>{{ report.text|linebreaksbr }}</li>
{% endfor %}
</ul>
{% endif %}
</section>
<section class="card narrow">
<h2>Esci</h2>
<form method="post" action="{% url 'accounts:logout' %}">
+1
View File
@@ -36,6 +36,7 @@ LOGIN = Backoff("login", threshold=5, base_delay=2.0, max_delay=300.0, decay_sec
LOGIN_IP = Backoff("login_ip", threshold=20, base_delay=2.0, max_delay=300.0, decay_seconds=900.0)
CHANGE_PASSWORD = Backoff("chpwd", threshold=5, base_delay=2.0, max_delay=300.0, decay_seconds=900.0)
REGISTER = Quota("register", limit=5, window_seconds=3600.0)
REPORT = Quota("report", limit=10, window_seconds=3600.0) # WEB-55: per user
_KEY_MAX = 150
+1
View File
@@ -8,4 +8,5 @@ urlpatterns = [
path("registrati/", views.register_view, name="register"),
path("esci/", views.logout_view, name="logout"),
path("app/profilo/", views.profile_view, name="profile"),
path("app/profilo/segnalazioni/", views.report_view, name="report"),
]
+33 -3
View File
@@ -11,10 +11,11 @@ from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods, require_POST
from apps.lottery import audit
from apps.lottery.models import Report
from . import throttle
from .client_ip import client_ip
from .forms import LoginForm, PasswordChangeForm, RegisterForm
from .forms import LoginForm, PasswordChangeForm, RegisterForm, ReportForm
from .models import User
BACKEND = "apps.accounts.backends.CaseInsensitiveBackend"
@@ -107,6 +108,35 @@ def logout_view(request):
return redirect(settings.LOGOUT_REDIRECT_URL)
def _profile_context(request, *, form=None, report_form=None) -> dict:
"""Only the signed-in user's own data and reports (WEB-03)."""
return {
"form": form or PasswordChangeForm(request.user),
"report_form": report_form or ReportForm(),
"reports": Report.objects.filter(user=request.user).order_by("-created_at", "-id"),
}
@never_cache
@login_required
@require_POST
def report_view(request):
"""WEB-55: send a problem report. A rejected form does not use the quota; a sent one does."""
key = str(request.user.pk)
wait = throttle.retry_after(throttle.REPORT, key)
form = ReportForm(request.POST)
if wait > 0:
return _too_many(request, "accounts/profile.html", _profile_context(request, report_form=form), wait)
if not form.is_valid():
return render(request, "accounts/profile.html", _profile_context(request, report_form=form), status=400)
with transaction.atomic():
report = Report.objects.create(user=request.user, text=form.cleaned_data["text"])
audit.record("report_submitted", actor=request.user, subject_type="report", subject_id=report.pk)
throttle.record(throttle.REPORT, key)
messages.success(request, "Segnalazione inviata. Ne vedrai lo stato qui sotto.")
return redirect("accounts:profile")
@never_cache
@login_required
@require_http_methods(["GET", "POST"])
@@ -116,7 +146,7 @@ def profile_view(request):
key = str(request.user.pk)
wait = throttle.retry_after(throttle.CHANGE_PASSWORD, key)
if wait > 0:
return _too_many(request, "accounts/profile.html", {"form": form}, wait)
return _too_many(request, "accounts/profile.html", _profile_context(request, form=form), wait)
if form.is_valid():
if not request.user.check_password(form.cleaned_data["current_password"]):
# SEC-54: a stolen session must not be able to guess the password and lock the owner out.
@@ -133,4 +163,4 @@ def profile_view(request):
update_session_auth_hash(request, request.user)
messages.success(request, "Password aggiornata. Le altre sessioni sono state chiuse.")
return redirect("accounts:profile")
return render(request, "accounts/profile.html", {"form": form})
return render(request, "accounts/profile.html", _profile_context(request, form=form))
+77
View File
@@ -0,0 +1,77 @@
"""Admin for the lottery tables (WEB-32): closed rounds, transactions, movements and the audit are read-only;
reports are managed by changing their status, which is audited."""
from django.contrib import admin
from django.db import transaction
from . import audit
from .models import AuditEntry, ChainTransaction, Movement, Participation, Report, Round
class ReadOnlyAdmin(admin.ModelAdmin):
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
@admin.register(Round)
class RoundAdmin(ReadOnlyAdmin):
list_display = ("id", "status", "opened_at", "closed_at", "pool_amount_sats")
list_filter = ("status",)
@admin.register(Participation)
class ParticipationAdmin(ReadOnlyAdmin):
list_display = ("id", "round", "user", "status", "bet_amount_sats")
list_filter = ("status",)
@admin.register(Movement)
class MovementAdmin(ReadOnlyAdmin):
list_display = ("id", "user", "kind", "status", "amount_sats", "created_at")
list_filter = ("kind", "status")
@admin.register(ChainTransaction)
class ChainTransactionAdmin(ReadOnlyAdmin):
list_display = ("id", "kind", "status", "current_txid", "created_at")
list_filter = ("kind", "status")
exclude = ("raw_hex",)
@admin.register(AuditEntry)
class AuditEntryAdmin(ReadOnlyAdmin):
list_display = ("created_at", "actor_label", "action", "outcome", "subject_type", "subject_id")
list_filter = ("action", "outcome")
search_fields = ("actor_label", "reason")
@admin.register(Report)
class ReportAdmin(admin.ModelAdmin):
list_display = ("id", "user", "status", "created_at")
list_filter = ("status",)
fields = ("user", "text", "created_at", "status", "status_changed_at")
readonly_fields = ("user", "text", "created_at", "status_changed_at")
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
def save_model(self, request, obj, form, change):
if not (change and "status" in form.changed_data):
return
from django.utils import timezone
before = form.initial.get("status")
with transaction.atomic():
obj.status_changed_at = timezone.now()
obj.save(update_fields=["status", "status_changed_at"])
audit.record("report_status_changed", actor=request.user, subject_type="report", subject_id=obj.pk,
payload={"from": before, "to": obj.status})
+170
View File
@@ -0,0 +1,170 @@
"""What the operations console shows and does (WEB-31, WEB-40..44, ADR-57).
The three pause switches are three distinct commands, each with its own permission. A command is
refused for anyone without that permission whatever the view did before (WEB-44), needs a reason
(WEB-43), and writes its audit row in the same transaction as the change (ADR-53). A refusal is
audited too, with outcome `denied`.
"""
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any
from django.conf import settings
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.utils import timezone
from . import audit
from .lifecycle import get_active_round
from .models import AuditEntry, ChainTransaction, LotteryConfig, Movement, Participation, Round
from .rules import round_deadline
MIN_REASON = 5
MAX_REASON = 500
WORKER_STALE_AFTER = timedelta(seconds=30) # the worker ticks every 5 s: six missed ticks is a dead worker
LATE_AFTER = timedelta(minutes=10) # a pending operation older than this needs a look
@dataclass(frozen=True)
class Command:
key: str # the URL segment
field: str # the LotteryConfig switch
permission: str # codename in the `lottery` app
title_on: str
title_off: str
action_on: str # audit actions
action_off: str
continues: tuple[str, ...] # what keeps running while the switch is on (WEB-43)
before_resume: tuple[str, ...] # what to check before switching it off (WEB-43)
COMMANDS: dict[str, Command] = {
c.key: c
for c in (
Command(
"pausa-dopo-round", "pause_after_round", "pause_after_round",
"Pausa dopo il round in corso", "Riprendi i round",
"pause_after_round_enabled", "pause_after_round_disabled",
continues=("Il round attivo prosegue fino al pagamento del vincitore.",
"Le puntate di quel round restano aperte fino alla scadenza.",
"Il round successivo non si apre."),
before_resume=("Il worker è attivo.", "Nessuna operazione in ritardo."),
),
Command(
"sospendi-puntate", "new_bets_suspended", "suspend_new_bets",
"Sospendi nuove puntate", "Riprendi le puntate",
"new_bets_suspended", "new_bets_resumed",
continues=("Le puntate già inviate restano monitorate e si confermano o si rifiutano come prima.",
"L'estrazione e il pagamento del round in corso non si fermano."),
before_resume=("Il worker è attivo.", "Nessuna operazione in ritardo.",
"La causa dell'incidente è chiusa."),
),
Command(
"sospendi-prelievi", "withdrawals_suspended", "suspend_withdrawals",
"Sospendi i prelievi", "Riprendi i prelievi",
"withdrawals_suspended", "withdrawals_resumed",
continues=("Le puntate e i round non cambiano.",
"I prelievi già inviati restano monitorati."),
before_resume=("Il saldo del portafoglio è riconciliato.", "Nessuna operazione in ritardo."),
),
)
}
def is_on(command: Command, config: LotteryConfig | None = None) -> bool:
return bool(getattr(config or LotteryConfig.get(), command.field))
def title(command: Command, config: LotteryConfig | None = None) -> str:
return command.title_off if is_on(command, config) else command.title_on
def can_view(user) -> bool:
return user.is_authenticated and user.is_active and user.is_staff and user.has_perm("lottery.view_console")
def can_run(user, command: Command) -> bool:
return user.is_authenticated and user.is_active and user.is_staff and user.has_perm(f"lottery.{command.permission}")
def clean_reason(reason: str) -> str:
reason = " ".join((reason or "").split())
if len(reason) < MIN_REASON:
raise ValidationError(f"Indica il motivo (almeno {MIN_REASON} caratteri).")
if len(reason) > MAX_REASON:
raise ValidationError(f"Il motivo è troppo lungo (al massimo {MAX_REASON} caratteri).")
return reason
def run_command(user, command: Command, enable: bool, reason: str) -> bool:
"""Set the command's switch to `enable` (explicit, so a double submit cannot flip it back). Returns False
when it was already in the wanted state (nothing changes, nothing is audited). Raises PermissionDenied (audited) or ValidationError (no reason)."""
if not can_run(user, command):
audit.record(command.action_on if enable else command.action_off,
actor=user if user.is_authenticated else None,
actor_label=user.get_username() if user.is_authenticated else "anonymous",
outcome=AuditEntry.Outcome.DENIED, subject_type="config", subject_id=1,
payload={"command": command.key})
raise PermissionDenied(command.key)
reason = clean_reason(reason)
with transaction.atomic():
config = LotteryConfig.get()
if getattr(config, command.field) == enable:
return False
setattr(config, command.field, enable)
config.save(update_fields=[command.field, "updated_at"])
audit.record(command.action_on if enable else command.action_off, actor=user, reason=reason,
subject_type="config", subject_id=1, payload={"command": command.key})
return True
def worker_alive(config: LotteryConfig, now: datetime) -> bool:
return config.worker_seen_at is not None and now - config.worker_seen_at <= WORKER_STALE_AFTER
def beat(now: datetime | None = None) -> None:
"""Called by the worker at every tick (WEB-31)."""
LotteryConfig.get()
LotteryConfig.objects.filter(pk=1).update(worker_seen_at=now or timezone.now())
def late_operations(now: datetime) -> dict[str, int]:
"""Operations that should have moved on by now (WEB-31)."""
limit = now - LATE_AFTER
overdue = 0
active = get_active_round()
if active is not None and now > round_deadline(active) + LATE_AFTER:
overdue = 1
return {
"pending_bets": Participation.objects.filter(status=Participation.Status.PENDING, created_at__lt=limit).count(),
"pending_movements": Movement.objects.filter(status=Movement.Status.PENDING, created_at__lt=limit).count(),
"pending_transactions": ChainTransaction.objects.filter(
status__in=[ChainTransaction.Status.BUILDING, ChainTransaction.Status.PENDING], created_at__lt=limit).count(),
"overdue_rounds": overdue,
}
def console_state(now: datetime | None = None) -> dict[str, Any]:
now = now or timezone.now()
config = LotteryConfig.get()
active = get_active_round()
late = late_operations(now)
reasons: dict[str, AuditEntry | None] = {}
for command in COMMANDS.values():
reasons[command.key] = (
AuditEntry.objects.filter(action=command.action_on, outcome=AuditEntry.Outcome.OK).order_by("-id").first()
if is_on(command, config) else None
)
return {
"now": now,
"config": config,
"round": active,
"deadline": round_deadline(active) if active is not None else None,
"worker_alive": worker_alive(config, now),
"worker_seen_at": config.worker_seen_at,
"backend": settings.LEDGER_BACKEND,
"late": late,
"late_total": sum(late.values()),
"pause_reasons": reasons,
}
@@ -19,8 +19,9 @@ def tick() -> None:
"""One pass over everything the worker is responsible for."""
from django.conf import settings
from apps.lottery import lifecycle, simulation
from apps.lottery import console, lifecycle, simulation
console.beat() # WEB-31: proof of life, before the work that might fail
if settings.LEDGER_BACKEND == "simulated":
simulation.settle()
lifecycle.tick()
@@ -0,0 +1,41 @@
# Generated by Django 5.2.19 on 2026-11-16 13:55
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lottery', '0002_audit_append_only_triggers'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AlterModelOptions(
name='lotteryconfig',
options={'permissions': [('view_console', 'Can open the operations console'), ('pause_after_round', 'Can pause the lottery after the round in progress'), ('suspend_new_bets', 'Can suspend new bets'), ('suspend_withdrawals', 'Can suspend withdrawals')]},
),
migrations.AddField(
model_name='lotteryconfig',
name='worker_seen_at',
field=models.DateTimeField(blank=True, null=True),
),
migrations.CreateModel(
name='Report',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.TextField(max_length=1000)),
('status', models.CharField(choices=[('open', 'Aperta'), ('read', 'Letta'), ('resolved', 'Risolta')], default='open', max_length=16)),
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
('status_changed_at', models.DateTimeField(blank=True, null=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='reports', to=settings.AUTH_USER_MODEL)),
],
options={
'indexes': [models.Index(fields=['user', '-created_at'], name='lottery_rep_user_id_2851c0_idx'), models.Index(fields=['status'], name='lottery_rep_status_badbe2_idx')],
'constraints': [models.CheckConstraint(condition=models.Q(('status__in', ['open', 'read', 'resolved'])), name='lottery_report_status_valid')],
},
),
]
+37
View File
@@ -36,9 +36,19 @@ class LotteryConfig(models.Model):
new_bets_suspended = models.BooleanField(default=False)
withdrawals_suspended = models.BooleanField(default=False)
# WEB-31: written by the worker at every tick; the console reads it to tell a live worker from a dead one.
worker_seen_at = models.DateTimeField(null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
# WEB-30, WEB-44: one explicit permission per operational command, checked in the view and again in the service.
permissions = [
("view_console", "Can open the operations console"),
("pause_after_round", "Can pause the lottery after the round in progress"),
("suspend_new_bets", "Can suspend new bets"),
("suspend_withdrawals", "Can suspend withdrawals"),
]
constraints = [
models.CheckConstraint(condition=Q(id=1), name="lottery_config_single_row"),
models.CheckConstraint(condition=Q(bet_amount_sats__gt=0), name="lottery_config_bet_positive"),
@@ -383,3 +393,30 @@ class AuditEntry(models.Model):
def __str__(self) -> str:
return f"{self.created_at:%Y-%m-%d %H:%M} {self.actor_label} {self.action}"
class Report(models.Model):
"""A problem report written by a player from the profile (WEB-55). Staff reads it and changes its
status from the admin; each status change is in the audit."""
class Status(models.TextChoices):
OPEN = "open", "Aperta"
READ = "read", "Letta"
RESOLVED = "resolved", "Risolta"
MAX_LENGTH = 1000
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="reports")
text = models.TextField(max_length=MAX_LENGTH)
status = models.CharField(max_length=16, choices=Status.choices, default=Status.OPEN)
created_at = models.DateTimeField(default=timezone.now)
status_changed_at = models.DateTimeField(null=True, blank=True)
class Meta:
indexes = [models.Index(fields=["user", "-created_at"]), models.Index(fields=["status"])]
constraints = [
models.CheckConstraint(condition=Q(status__in=["open", "read", "resolved"]), name="lottery_report_status_valid"),
]
def __str__(self) -> str:
return f"Report {self.pk} ({self.status})"
+27
View File
@@ -0,0 +1,27 @@
{% extends "web/base.html" %}
{% block title %}{{ title }} · PLM Lottery{% endblock %}
{% block content %}
<h1>{{ title }}</h1>
<section class="card narrow">
<h2>Cosa continua</h2>
<ul>{% for line in cmd.continues %}<li>{{ line }}</li>{% endfor %}</ul>
{% if not enable %}
<h2>Verifiche prima della ripresa</h2>
<ul>{% for line in cmd.before_resume %}<li>{{ line }}</li>{% endfor %}</ul>
<p class="hint">
Stato ora: worker {% if worker_alive %}attivo{% else %}<strong>fermo</strong>{% endif %},
operazioni in ritardo: {{ late_total }}.
</p>
{% endif %}
<form method="post" novalidate>
{% csrf_token %}
<input type="hidden" name="enable" value="{% if enable %}1{% else %}0{% endif %}">
{% if error %}<p class="message error" role="alert">{{ error }}</p>{% endif %}
<label for="reason">Motivo (resta nell'audit)</label>
<textarea id="reason" name="reason" rows="3" maxlength="500" required>{{ reason_text }}</textarea>
<p><label><input type="checkbox" name="confirm" value="1"> Ho letto cosa comporta e confermo.</label></p>
<button class="button" type="submit">{{ title }}</button>
<a class="button secondary" href="{% url 'ops:dashboard' %}">Annulla</a>
</form>
</section>
{% endblock %}
+56
View File
@@ -0,0 +1,56 @@
{% extends "web/base.html" %}
{% block title %}Console operativa · PLM Lottery{% endblock %}
{% block content %}
<h1>Console operativa</h1>
<section class="card" aria-labelledby="stato">
<h2 id="stato">Stato</h2>
<dl class="facts">
<dt>Round in corso</dt>
<dd>{% if round %}n. {{ round.pk }} · {{ round.get_status_display }}{% else %}nessuno{% endif %}</dd>
<dt>Prossima scadenza</dt>
<dd>{% if round and round.status == "open" %}{{ deadline|date:"H:i:s" }} UTC{% else %}—{% endif %}</dd>
<dt>Worker</dt>
<dd>
{% if worker_alive %}attivo · ultimo battito {{ worker_seen_at|time:"H:i:s" }} UTC
{% elif worker_seen_at %}<strong>fermo</strong> · ultimo battito {{ worker_seen_at|date:"j F H:i:s" }} UTC
{% else %}<strong>mai avviato</strong>{% endif %}
</dd>
<dt>Catena</dt>
<dd>{% if backend == "simulated" %}simulata (fase A): nessun nodo Electrum da controllare{% else %}Electrum: controllo non ancora disponibile{% endif %}</dd>
<dt>Ultima riconciliazione</dt>
<dd>non ancora disponibile (arriva con la fase B)</dd>
<dt>Operazioni in ritardo</dt>
<dd>
{% if late_total %}
<strong>{{ late_total }}</strong>:
{{ late.pending_bets }} puntate in attesa, {{ late.pending_movements }} movimenti in attesa,
{{ late.pending_transactions }} transazioni in attesa{% if late.overdue_rounds %}, il round oltre la scadenza{% endif %}
{% else %}nessuna{% endif %}
</dd>
</dl>
</section>
<section class="card" aria-labelledby="comandi">
<h2 id="comandi">Pause</h2>
<ul class="plain">
{% for item in commands %}
<li>
<strong>{{ item.command.title_on }}</strong> — {% if item.on %}<strong>attiva</strong>{% else %}non attiva{% endif %}
{% if item.reason %}<br><span class="hint">Dal {{ item.reason.created_at|date:"j F H:i" }} UTC, {{ item.reason.actor_label }}: {{ item.reason.reason }}</span>{% endif %}
<br>
{% if item.allowed %}
<a class="button small{% if item.on %} secondary{% endif %}" href="{% url 'ops:command' item.command.key %}">{{ item.title }}…</a>
{% else %}
<span class="hint">Non hai il permesso per questo comando.</span>
{% endif %}
</li>
{% endfor %}
</ul>
</section>
<section class="card">
<h2>Altri strumenti</h2>
<p><a href="/admin/">Amministrazione: utenti, segnalazioni, audit</a></p>
</section>
{% endblock %}
+9
View File
@@ -0,0 +1,9 @@
from django.urls import path
from . import views
app_name = "ops"
urlpatterns = [
path("ops/", views.dashboard, name="dashboard"),
path("ops/<slug:key>/", views.command, name="command"),
]
+76
View File
@@ -0,0 +1,76 @@
"""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)
+1
View File
@@ -23,6 +23,7 @@
<a href="{% url 'web:app-home' %}"{% if current == 'web:app-home' or current == 'web:bet' %} aria-current="page"{% endif %}>Gioca</a>
<a href="{% url 'web:wallet' %}"{% if current == 'web:wallet' %} aria-current="page"{% endif %}>Portafoglio</a>
<a href="{% url 'web:movements' %}"{% if current == 'web:movements' %} aria-current="page"{% endif %}>Movimenti</a>
{% if user.is_staff and perms.lottery.view_console %}<a href="{% url 'ops:dashboard' %}">Console</a>{% endif %}
<a href="{% url 'accounts:profile' %}"{% if current == 'accounts:profile' %} aria-current="page"{% endif %}>Profilo</a>
{% endwith %}
<form class="inline" method="post" action="{% url 'accounts:logout' %}">