authentik.core.signals

authentik core signals

 1"""authentik core signals"""
 2
 3from asgiref.sync import async_to_sync
 4from channels.layers import get_channel_layer
 5from django.contrib.auth.signals import user_logged_in
 6from django.core.cache import cache
 7from django.db.models import Model
 8from django.db.models.signals import post_delete, post_save, pre_save
 9from django.dispatch import Signal, receiver
10from django.http.request import HttpRequest
11from structlog.stdlib import get_logger
12
13from authentik.core.models import (
14    Application,
15    AuthenticatedSession,
16    BackchannelProvider,
17    ExpiringModel,
18    Session,
19    User,
20    default_token_duration,
21)
22from authentik.flows.apps import RefreshOtherFlowsAfterAuthentication
23from authentik.root.ws.consumer import build_device_group
24
25# Arguments: user: User, password: str
26password_changed = Signal()
27# Arguments: credentials: dict[str, any], request: HttpRequest,
28#            stage: Stage, context: dict[str, any]
29login_failed = Signal()
30
31LOGGER = get_logger()
32
33
34@receiver(post_save, sender=Application)
35def post_save_application(sender: type[Model], instance, created: bool, **_):
36    """Clear user's application cache upon application creation"""
37    from authentik.core.api.applications import user_app_cache_key
38
39    if not created:  # pragma: no cover
40        return
41
42    # Also delete user application cache
43    keys = cache.keys(user_app_cache_key("*"))
44    cache.delete_many(keys)
45
46
47@receiver(user_logged_in)
48def user_logged_in_session(sender, request: HttpRequest, user: User, **_):
49    """Create an AuthenticatedSession from request"""
50
51    session = AuthenticatedSession.from_request(request, user)
52    if session:
53        session.save()
54
55    if not RefreshOtherFlowsAfterAuthentication.get():
56        return
57    layer = get_channel_layer()
58    device_cookie = request.COOKIES.get("authentik_device")
59    if device_cookie:
60        async_to_sync(layer.group_send)(
61            build_device_group(device_cookie),
62            {"type": "event.session.authenticated"},
63        )
64
65
66@receiver(post_delete, sender=AuthenticatedSession)
67def authenticated_session_delete(sender: type[Model], instance: AuthenticatedSession, **_):
68    """Delete session when authenticated session is deleted"""
69    Session.objects.filter(session_key=instance.pk).delete()
70
71
72@receiver(pre_save)
73def backchannel_provider_pre_save(sender: type[Model], instance: Model, **_):
74    """Ensure backchannel providers have is_backchannel set to true"""
75    if not isinstance(instance, BackchannelProvider):
76        return
77    instance.is_backchannel = True
78
79
80@receiver(pre_save)
81def expiring_model_pre_save(sender: type[Model], instance: Model, **_):
82    """Ensure expires is set on ExpiringModels that are set to expire"""
83    if not issubclass(sender, ExpiringModel):
84        return
85    if instance.expiring and instance.expires is None:
86        instance.expires = default_token_duration()
password_changed = <django.dispatch.dispatcher.Signal object>
login_failed = <django.dispatch.dispatcher.Signal object>
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
@receiver(post_save, sender=Application)
def post_save_application( sender: type[django.db.models.base.Model], instance, created: bool, **_):
35@receiver(post_save, sender=Application)
36def post_save_application(sender: type[Model], instance, created: bool, **_):
37    """Clear user's application cache upon application creation"""
38    from authentik.core.api.applications import user_app_cache_key
39
40    if not created:  # pragma: no cover
41        return
42
43    # Also delete user application cache
44    keys = cache.keys(user_app_cache_key("*"))
45    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, **_):
48@receiver(user_logged_in)
49def user_logged_in_session(sender, request: HttpRequest, user: User, **_):
50    """Create an AuthenticatedSession from request"""
51
52    session = AuthenticatedSession.from_request(request, user)
53    if session:
54        session.save()
55
56    if not RefreshOtherFlowsAfterAuthentication.get():
57        return
58    layer = get_channel_layer()
59    device_cookie = request.COOKIES.get("authentik_device")
60    if device_cookie:
61        async_to_sync(layer.group_send)(
62            build_device_group(device_cookie),
63            {"type": "event.session.authenticated"},
64        )

Create an AuthenticatedSession from request

@receiver(post_delete, sender=AuthenticatedSession)
def authenticated_session_delete( sender: type[django.db.models.base.Model], instance: authentik.core.models.AuthenticatedSession, **_):
67@receiver(post_delete, sender=AuthenticatedSession)
68def authenticated_session_delete(sender: type[Model], instance: AuthenticatedSession, **_):
69    """Delete session when authenticated session is deleted"""
70    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, **_):
73@receiver(pre_save)
74def backchannel_provider_pre_save(sender: type[Model], instance: Model, **_):
75    """Ensure backchannel providers have is_backchannel set to true"""
76    if not isinstance(instance, BackchannelProvider):
77        return
78    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, **_):
81@receiver(pre_save)
82def expiring_model_pre_save(sender: type[Model], instance: Model, **_):
83    """Ensure expires is set on ExpiringModels that are set to expire"""
84    if not issubclass(sender, ExpiringModel):
85        return
86    if instance.expiring and instance.expires is None:
87        instance.expires = default_token_duration()

Ensure expires is set on ExpiringModels that are set to expire