Corp/backend/api/auth/realtime.py

39 lines
1.2 KiB
Python

"""Realtime propagation of authentication-session revocation."""
from __future__ import annotations
import logging
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.db import transaction
logger = logging.getLogger(__name__)
def schedule_auth_session_revoked(*, user_id: int, session_id: str) -> None:
def _send() -> None:
channel_layer = get_channel_layer()
if channel_layer is None:
return
try:
async_to_sync(channel_layer.group_send)(
f"user_{user_id}",
{
"type": "auth_session_revoked",
"session_id": str(session_id),
},
)
except Exception as error:
logger.exception(
"Auth session revocation realtime update failed",
extra={
"event": "authentication.session.realtime_revocation_failed",
"user_id": user_id,
"auth_session_id": str(session_id),
"error_type": type(error).__name__,
},
)
transaction.on_commit(_send)