"""Session security middleware for Section 11.

Updates SessionEvent.last_seen_at on authenticated requests.
Zero Trust: every authenticated request re-verifies the session
(NIST SP 800-207). Never blocks requests; a failure here is silent
in the request path but must not break the site.

Standards: NIST SP 800-63B 7.1; NIST SP 800-207;
OWASP ASVS 5.0 3.2.3 (session bound to client properties).
"""
from django.utils import timezone


class SessionActivityMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        try:
            user = getattr(request, "user", None)
            if user is not None and user.is_authenticated:
                ev_id = request.session.get("session_event_id") if hasattr(request, "session") else None
                if ev_id:
                    from .models import SessionEvent
                    SessionEvent.objects.filter(id=ev_id, active=True).update(
                        last_seen_at=timezone.now(),
                    )
        except Exception:
            # Fail-open on the request path (Section 13.2 L6).
            pass
        return response
