authentik.core.signals

authentik core signals

  1"""authentik core signals"""
  2
  3from contextlib import contextmanager
  4from contextvars import ContextVar
  5
  6from django.contrib.auth.signals import user_logged_in
  7from django.core.cache import cache
  8from django.db.models import Model
  9from django.db.models.signals import post_delete, post_save, pre_save
 10from django.dispatch import Signal, receiver
 11from django.http.request import HttpRequest
 12from structlog.stdlib import get_logger
 13
 14from authentik.core.models import (
 15    Application,
 16    AuthenticatedSession,
 17    BackchannelProvider,
 18    Session,
 19    User,
 20    default_token_duration,
 21)
 22from authentik.lib.models import ExpiringModel
 23
 24password_changed = Signal()
 25"""Arguments: user: User, password: str"""
 26password_hash_changed = Signal()
 27"""Arguments: user: User, request: HttpRequest | None"""
 28login_failed = Signal()
 29"""Arguments: credentials: dict[str, any], request: HttpRequest,
 30stage: Stage, context: dict[str, any]"""
 31admin_authenticated_session_deleted = Signal()
 32"""Arguments: instance: AuthenticatedSession, request: HttpRequest"""
 33impersonation_changed = Signal()
 34"""Sent after the impersonation session is saved. Arguments: session_key: str"""
 35
 36LOGGER = get_logger()
 37
 38_CTX_INHIBIT_DEACTIVATION_SESSION_CLEANUP = ContextVar[bool](
 39    "authentik_core_inhibit_deactivation_session_cleanup",
 40    default=False,
 41)
 42_CTX_INHIBIT_DEACTIVATION_TOKEN_CLEANUP = ContextVar[bool](
 43    "authentik_core_inhibit_deactivation_token_cleanup",
 44    default=False,
 45)
 46
 47
 48@contextmanager
 49def deactivation_inhibit_cleanup(*, sessions: bool = True, tokens: bool = True):
 50    """
 51    Prevent the automatic cleanup that runs when a deactivated user is saved,
 52    for callers that revoke sessions and/or tokens themselves (e.g. enterprise
 53    revocation). `sessions` inhibits session deletion, `tokens` inhibits
 54    provider token revocation; both are inhibited by default. Nested uses can
 55    add inhibition but not remove the outer context's.
 56    """
 57    reset_sessions = _CTX_INHIBIT_DEACTIVATION_SESSION_CLEANUP.set(
 58        _CTX_INHIBIT_DEACTIVATION_SESSION_CLEANUP.get() or sessions
 59    )
 60    reset_tokens = _CTX_INHIBIT_DEACTIVATION_TOKEN_CLEANUP.set(
 61        _CTX_INHIBIT_DEACTIVATION_TOKEN_CLEANUP.get() or tokens
 62    )
 63    try:
 64        yield
 65    finally:
 66        _CTX_INHIBIT_DEACTIVATION_SESSION_CLEANUP.reset(reset_sessions)
 67        _CTX_INHIBIT_DEACTIVATION_TOKEN_CLEANUP.reset(reset_tokens)
 68
 69
 70def deactivation_session_cleanup_inhibited() -> bool:
 71    """Whether deactivation session cleanup is inhibited in the current context"""
 72    return _CTX_INHIBIT_DEACTIVATION_SESSION_CLEANUP.get()
 73
 74
 75def deactivation_token_cleanup_inhibited() -> bool:
 76    """Whether deactivation token cleanup is inhibited in the current context"""
 77    return _CTX_INHIBIT_DEACTIVATION_TOKEN_CLEANUP.get()
 78
 79
 80@receiver(post_save, sender=Application)
 81def post_save_application(sender: type[Model], instance, created: bool, **_):
 82    """Clear user's application cache upon application creation"""
 83    from authentik.core.api.applications import user_app_cache_key
 84
 85    if not created:  # pragma: no cover
 86        return
 87
 88    # Also delete user application cache
 89    keys = cache.keys(user_app_cache_key("*"))
 90    cache.delete_many(keys)
 91
 92
 93@receiver(user_logged_in)
 94def user_logged_in_session(sender, request: HttpRequest, user: User, **_):
 95    """Create an AuthenticatedSession from request"""
 96
 97    AuthenticatedSession.create_from_request(request, user)
 98
 99
100@receiver(post_save, sender=User)
101def user_deactivated_delete_sessions(sender: type[Model], instance: User, **_):
102    """Delete all of a user's sessions when they are deactivated"""
103    if instance.is_active:
104        return
105    if deactivation_session_cleanup_inhibited():
106        return
107    Session.objects.filter(authenticatedsession__user=instance).delete()
108    LOGGER.debug("Deleted deactivated user's sessions", user=instance.username)
109
110
111@receiver(post_delete, sender=AuthenticatedSession)
112def authenticated_session_delete(sender: type[Model], instance: AuthenticatedSession, **_):
113    """Delete session when authenticated session is deleted"""
114    Session.objects.filter(session_key=instance.pk).delete()
115
116
117@receiver(pre_save)
118def backchannel_provider_pre_save(sender: type[Model], instance: Model, **_):
119    """Ensure backchannel providers have is_backchannel set to true"""
120    if not isinstance(instance, BackchannelProvider):
121        return
122    instance.is_backchannel = True
123
124
125@receiver(pre_save)
126def expiring_model_pre_save(sender: type[Model], instance: Model, **_):
127    """Ensure expires is set on ExpiringModels that are set to expire"""
128    if not issubclass(sender, ExpiringModel):
129        return
130    if instance.expiring and instance.expires is None:
131        instance.expires = default_token_duration()
password_changed = <django.dispatch.dispatcher.Signal object>

Arguments: user: User, password: str

password_hash_changed = <django.dispatch.dispatcher.Signal object>

Arguments: user: User, request: HttpRequest | None

login_failed = <django.dispatch.dispatcher.Signal object>

Arguments: credentials: dict[str, any], request: HttpRequest, stage: Stage, context: dict[str, any]

admin_authenticated_session_deleted = <django.dispatch.dispatcher.Signal object>

Arguments: instance: AuthenticatedSession, request: HttpRequest

impersonation_changed = <django.dispatch.dispatcher.Signal object>

Sent after the impersonation session is saved. Arguments: session_key: str

LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
@contextmanager
def deactivation_inhibit_cleanup(*, sessions: bool = True, tokens: bool = True):
49@contextmanager
50def deactivation_inhibit_cleanup(*, sessions: bool = True, tokens: bool = True):
51    """
52    Prevent the automatic cleanup that runs when a deactivated user is saved,
53    for callers that revoke sessions and/or tokens themselves (e.g. enterprise
54    revocation). `sessions` inhibits session deletion, `tokens` inhibits
55    provider token revocation; both are inhibited by default. Nested uses can
56    add inhibition but not remove the outer context's.
57    """
58    reset_sessions = _CTX_INHIBIT_DEACTIVATION_SESSION_CLEANUP.set(
59        _CTX_INHIBIT_DEACTIVATION_SESSION_CLEANUP.get() or sessions
60    )
61    reset_tokens = _CTX_INHIBIT_DEACTIVATION_TOKEN_CLEANUP.set(
62        _CTX_INHIBIT_DEACTIVATION_TOKEN_CLEANUP.get() or tokens
63    )
64    try:
65        yield
66    finally:
67        _CTX_INHIBIT_DEACTIVATION_SESSION_CLEANUP.reset(reset_sessions)
68        _CTX_INHIBIT_DEACTIVATION_TOKEN_CLEANUP.reset(reset_tokens)

Prevent the automatic cleanup that runs when a deactivated user is saved, for callers that revoke sessions and/or tokens themselves (e.g. enterprise revocation). sessions inhibits session deletion, tokens inhibits provider token revocation; both are inhibited by default. Nested uses can add inhibition but not remove the outer context's.

def deactivation_session_cleanup_inhibited() -> bool:
71def deactivation_session_cleanup_inhibited() -> bool:
72    """Whether deactivation session cleanup is inhibited in the current context"""
73    return _CTX_INHIBIT_DEACTIVATION_SESSION_CLEANUP.get()

Whether deactivation session cleanup is inhibited in the current context

def deactivation_token_cleanup_inhibited() -> bool:
76def deactivation_token_cleanup_inhibited() -> bool:
77    """Whether deactivation token cleanup is inhibited in the current context"""
78    return _CTX_INHIBIT_DEACTIVATION_TOKEN_CLEANUP.get()

Whether deactivation token cleanup is inhibited in the current context

@receiver(post_save, sender=Application)
def post_save_application( sender: type[django.db.models.base.Model], instance, created: bool, **_):
81@receiver(post_save, sender=Application)
82def post_save_application(sender: type[Model], instance, created: bool, **_):
83    """Clear user's application cache upon application creation"""
84    from authentik.core.api.applications import user_app_cache_key
85
86    if not created:  # pragma: no cover
87        return
88
89    # Also delete user application cache
90    keys = cache.keys(user_app_cache_key("*"))
91    cache.delete_many(keys)

Clear user's application cache upon application creation

@receiver(user_logged_in)
def user_logged_in_session( sender, request: django.http.request.HttpRequest, user: authentik.core.models.User, **_):
94@receiver(user_logged_in)
95def user_logged_in_session(sender, request: HttpRequest, user: User, **_):
96    """Create an AuthenticatedSession from request"""
97
98    AuthenticatedSession.create_from_request(request, user)

Create an AuthenticatedSession from request

@receiver(post_save, sender=User)
def user_deactivated_delete_sessions( sender: type[django.db.models.base.Model], instance: authentik.core.models.User, **_):
101@receiver(post_save, sender=User)
102def user_deactivated_delete_sessions(sender: type[Model], instance: User, **_):
103    """Delete all of a user's sessions when they are deactivated"""
104    if instance.is_active:
105        return
106    if deactivation_session_cleanup_inhibited():
107        return
108    Session.objects.filter(authenticatedsession__user=instance).delete()
109    LOGGER.debug("Deleted deactivated user's sessions", user=instance.username)

Delete all of a user's sessions when they are deactivated

@receiver(post_delete, sender=AuthenticatedSession)
def authenticated_session_delete( sender: type[django.db.models.base.Model], instance: authentik.core.models.AuthenticatedSession, **_):
112@receiver(post_delete, sender=AuthenticatedSession)
113def authenticated_session_delete(sender: type[Model], instance: AuthenticatedSession, **_):
114    """Delete session when authenticated session is deleted"""
115    Session.objects.filter(session_key=instance.pk).delete()

Delete session when authenticated session is deleted

@receiver(pre_save)
def backchannel_provider_pre_save( sender: type[django.db.models.base.Model], instance: django.db.models.base.Model, **_):
118@receiver(pre_save)
119def backchannel_provider_pre_save(sender: type[Model], instance: Model, **_):
120    """Ensure backchannel providers have is_backchannel set to true"""
121    if not isinstance(instance, BackchannelProvider):
122        return
123    instance.is_backchannel = True

Ensure backchannel providers have is_backchannel set to true

@receiver(pre_save)
def expiring_model_pre_save( sender: type[django.db.models.base.Model], instance: django.db.models.base.Model, **_):
126@receiver(pre_save)
127def expiring_model_pre_save(sender: type[Model], instance: Model, **_):
128    """Ensure expires is set on ExpiringModels that are set to expire"""
129    if not issubclass(sender, ExpiringModel):
130        return
131    if instance.expiring and instance.expires is None:
132        instance.expires = default_token_duration()

Ensure expires is set on ExpiringModels that are set to expire