authentik.events.signals
authentik events signal listener
1"""authentik events signal listener""" 2 3from importlib import import_module 4from typing import Any 5 6from django.conf import settings 7from django.contrib.auth.signals import user_logged_in, user_logged_out 8from django.db.models.signals import post_save, pre_delete 9from django.dispatch import receiver 10from django.http import HttpRequest 11from rest_framework.request import Request 12 13from authentik.admin.utils import get_system_settings 14from authentik.core.models import AuthenticatedSession, User, UserActivity 15from authentik.core.signals import login_failed, password_changed, password_hash_changed 16from authentik.events.models import Event, EventAction 17from authentik.flows.models import Stage 18from authentik.flows.planner import ( 19 PLAN_CONTEXT_DEVICE, 20 PLAN_CONTEXT_OUTPOST, 21 PLAN_CONTEXT_SOURCE, 22 PLAN_CONTEXT_USER_SWITCH_FROM_USER, 23 FlowPlan, 24) 25from authentik.flows.views.executor import SESSION_KEY_PLAN 26from authentik.stages.invitation.models import Invitation 27from authentik.stages.invitation.signals import invitation_used 28from authentik.stages.password.stage import PLAN_CONTEXT_METHOD, PLAN_CONTEXT_METHOD_ARGS 29from authentik.stages.user_write.signals import user_write 30 31SESSION_LOGIN_EVENT = "login_event" 32_session_engine = import_module(settings.SESSION_ENGINE) 33 34 35@receiver(user_logged_in) 36def on_user_logged_in(sender, request: HttpRequest, user: User, **_): 37 """Log successful login""" 38 kwargs = {} 39 if SESSION_KEY_PLAN in request.session: 40 flow_plan: FlowPlan = request.session[SESSION_KEY_PLAN] 41 if PLAN_CONTEXT_SOURCE in flow_plan.context: 42 # Login request came from an external source, save it in the context 43 kwargs[PLAN_CONTEXT_SOURCE] = flow_plan.context[PLAN_CONTEXT_SOURCE] 44 if PLAN_CONTEXT_METHOD in flow_plan.context: 45 # Save the login method used 46 kwargs[PLAN_CONTEXT_METHOD] = flow_plan.context[PLAN_CONTEXT_METHOD] 47 kwargs[PLAN_CONTEXT_METHOD_ARGS] = flow_plan.context.get(PLAN_CONTEXT_METHOD_ARGS, {}) 48 if PLAN_CONTEXT_OUTPOST in flow_plan.context: 49 # Save outpost context 50 kwargs[PLAN_CONTEXT_OUTPOST] = flow_plan.context[PLAN_CONTEXT_OUTPOST] 51 if PLAN_CONTEXT_DEVICE in flow_plan.context: 52 # Save device 53 kwargs[PLAN_CONTEXT_DEVICE] = flow_plan.context[PLAN_CONTEXT_DEVICE] 54 if from_user := flow_plan.context.get(PLAN_CONTEXT_USER_SWITCH_FROM_USER): 55 # Record that this login came from a user switch. 56 kwargs["is_user_switch"] = True 57 kwargs[PLAN_CONTEXT_USER_SWITCH_FROM_USER] = from_user 58 event = Event.new(EventAction.LOGIN, **kwargs).from_http(request, user=user) 59 request.session[SESSION_LOGIN_EVENT] = event 60 request.session.save() 61 62 63def get_login_event(request_or_session: HttpRequest | AuthenticatedSession | None) -> Event | None: 64 """Wrapper to get login event that can be mocked in tests""" 65 session = None 66 if not request_or_session: 67 return None 68 if isinstance(request_or_session, HttpRequest | Request): 69 session = request_or_session.session 70 if isinstance(request_or_session, AuthenticatedSession): 71 SessionStore = _session_engine.SessionStore 72 session = SessionStore(request_or_session.session.session_key) 73 return session.get(SESSION_LOGIN_EVENT, None) 74 75 76@receiver(user_logged_out) 77def on_user_logged_out(sender, request: HttpRequest, user: User, **kwargs): 78 """Log successfully logout""" 79 # Check if this even comes from the user_login stage's middleware, which will set an extra 80 # argument 81 event = Event.new(EventAction.LOGOUT) 82 if "event_extra" in kwargs: 83 event.context.update(kwargs["event_extra"]) 84 event.from_http(request, user=user) 85 86 87@receiver(user_write) 88def on_user_write(sender, request: HttpRequest, user: User, data: dict[str, Any], **kwargs): 89 """Log User write""" 90 data["created"] = kwargs.get("created", False) 91 Event.new(EventAction.USER_WRITE, **data).from_http(request, user=user) 92 93 94@receiver(login_failed) 95def on_login_failed( 96 signal, 97 sender, 98 credentials: dict[str, str], 99 request: HttpRequest, 100 stage: Stage | None = None, 101 context: dict[str, Any] | None = None, 102 **kwargs, 103): 104 """Failed Login, authentik custom event""" 105 user = User.objects.filter(username=credentials.get("username")).first() 106 context = context or {} 107 Event.new(EventAction.LOGIN_FAILED, **credentials, stage=stage, **context).from_http( 108 request, user 109 ) 110 111 112@receiver(invitation_used) 113def on_invitation_used(sender, request: HttpRequest, invitation: Invitation, **_): 114 """Log Invitation usage""" 115 Event.new(EventAction.INVITE_USED, invitation_uuid=invitation.invite_uuid.hex).from_http( 116 request 117 ) 118 119 120@receiver(password_hash_changed) 121@receiver(password_changed) 122def on_password_changed( 123 sender, 124 user: User, 125 password: str | None = None, 126 request: HttpRequest | None = None, 127 hasher_defaults_overridden: bool = False, 128 **_, 129): 130 """Log password change""" 131 context = {} 132 if hasher_defaults_overridden: 133 context["hasher_defaults_overridden"] = hasher_defaults_overridden 134 Event.new(EventAction.PASSWORD_SET, **context).from_http(request, user=user) 135 136 137@receiver(post_save, sender=Event) 138def event_post_save_notification(sender, instance: Event, **_): 139 """Start task to check if any policies trigger an notification on this event""" 140 from authentik.events.tasks import event_trigger_dispatch 141 142 event_trigger_dispatch.send(instance.event_uuid) 143 144 145@receiver(pre_delete, sender=User) 146def event_user_pre_delete_cleanup(sender, instance: User, **_): 147 """If gdpr_compliance is enabled, remove all the user's events""" 148 from authentik.events.tasks import gdpr_cleanup 149 150 if get_system_settings().gdpr_compliance: 151 gdpr_cleanup.send(instance.pk) 152 153 154@receiver(post_save, sender=Event) 155def event_post_save_activity(sender, instance: Event, created: bool, raw: bool = False, **_): 156 """Credit the finalized event identity, never nested impersonation identities.""" 157 if ( 158 raw 159 or not created 160 or instance.action not in (EventAction.LOGIN, EventAction.AUTHORIZE_APPLICATION) 161 ): 162 return 163 if isinstance(instance.user, dict): 164 UserActivity.objects.record(instance.user.get("pk"), instance.created)
SESSION_LOGIN_EVENT =
'login_event'
@receiver(user_logged_in)
def
on_user_logged_in( sender, request: django.http.request.HttpRequest, user: authentik.core.models.User, **_):
36@receiver(user_logged_in) 37def on_user_logged_in(sender, request: HttpRequest, user: User, **_): 38 """Log successful login""" 39 kwargs = {} 40 if SESSION_KEY_PLAN in request.session: 41 flow_plan: FlowPlan = request.session[SESSION_KEY_PLAN] 42 if PLAN_CONTEXT_SOURCE in flow_plan.context: 43 # Login request came from an external source, save it in the context 44 kwargs[PLAN_CONTEXT_SOURCE] = flow_plan.context[PLAN_CONTEXT_SOURCE] 45 if PLAN_CONTEXT_METHOD in flow_plan.context: 46 # Save the login method used 47 kwargs[PLAN_CONTEXT_METHOD] = flow_plan.context[PLAN_CONTEXT_METHOD] 48 kwargs[PLAN_CONTEXT_METHOD_ARGS] = flow_plan.context.get(PLAN_CONTEXT_METHOD_ARGS, {}) 49 if PLAN_CONTEXT_OUTPOST in flow_plan.context: 50 # Save outpost context 51 kwargs[PLAN_CONTEXT_OUTPOST] = flow_plan.context[PLAN_CONTEXT_OUTPOST] 52 if PLAN_CONTEXT_DEVICE in flow_plan.context: 53 # Save device 54 kwargs[PLAN_CONTEXT_DEVICE] = flow_plan.context[PLAN_CONTEXT_DEVICE] 55 if from_user := flow_plan.context.get(PLAN_CONTEXT_USER_SWITCH_FROM_USER): 56 # Record that this login came from a user switch. 57 kwargs["is_user_switch"] = True 58 kwargs[PLAN_CONTEXT_USER_SWITCH_FROM_USER] = from_user 59 event = Event.new(EventAction.LOGIN, **kwargs).from_http(request, user=user) 60 request.session[SESSION_LOGIN_EVENT] = event 61 request.session.save()
Log successful login
def
get_login_event( request_or_session: django.http.request.HttpRequest | authentik.core.models.AuthenticatedSession | None) -> authentik.events.models.Event | None:
64def get_login_event(request_or_session: HttpRequest | AuthenticatedSession | None) -> Event | None: 65 """Wrapper to get login event that can be mocked in tests""" 66 session = None 67 if not request_or_session: 68 return None 69 if isinstance(request_or_session, HttpRequest | Request): 70 session = request_or_session.session 71 if isinstance(request_or_session, AuthenticatedSession): 72 SessionStore = _session_engine.SessionStore 73 session = SessionStore(request_or_session.session.session_key) 74 return session.get(SESSION_LOGIN_EVENT, None)
Wrapper to get login event that can be mocked in tests
@receiver(user_logged_out)
def
on_user_logged_out( sender, request: django.http.request.HttpRequest, user: authentik.core.models.User, **kwargs):
77@receiver(user_logged_out) 78def on_user_logged_out(sender, request: HttpRequest, user: User, **kwargs): 79 """Log successfully logout""" 80 # Check if this even comes from the user_login stage's middleware, which will set an extra 81 # argument 82 event = Event.new(EventAction.LOGOUT) 83 if "event_extra" in kwargs: 84 event.context.update(kwargs["event_extra"]) 85 event.from_http(request, user=user)
Log successfully logout
@receiver(user_write)
def
on_user_write( sender, request: django.http.request.HttpRequest, user: authentik.core.models.User, data: dict[str, typing.Any], **kwargs):
88@receiver(user_write) 89def on_user_write(sender, request: HttpRequest, user: User, data: dict[str, Any], **kwargs): 90 """Log User write""" 91 data["created"] = kwargs.get("created", False) 92 Event.new(EventAction.USER_WRITE, **data).from_http(request, user=user)
Log User write
@receiver(login_failed)
def
on_login_failed( signal, sender, credentials: dict[str, str], request: django.http.request.HttpRequest, stage: authentik.flows.models.Stage | None = None, context: dict[str, Any] | None = None, **kwargs):
95@receiver(login_failed) 96def on_login_failed( 97 signal, 98 sender, 99 credentials: dict[str, str], 100 request: HttpRequest, 101 stage: Stage | None = None, 102 context: dict[str, Any] | None = None, 103 **kwargs, 104): 105 """Failed Login, authentik custom event""" 106 user = User.objects.filter(username=credentials.get("username")).first() 107 context = context or {} 108 Event.new(EventAction.LOGIN_FAILED, **credentials, stage=stage, **context).from_http( 109 request, user 110 )
Failed Login, authentik custom event
@receiver(invitation_used)
def
on_invitation_used( sender, request: django.http.request.HttpRequest, invitation: authentik.stages.invitation.models.Invitation, **_):
113@receiver(invitation_used) 114def on_invitation_used(sender, request: HttpRequest, invitation: Invitation, **_): 115 """Log Invitation usage""" 116 Event.new(EventAction.INVITE_USED, invitation_uuid=invitation.invite_uuid.hex).from_http( 117 request 118 )
Log Invitation usage
@receiver(password_hash_changed)
@receiver(password_changed)
def
on_password_changed( sender, user: authentik.core.models.User, password: str | None = None, request: django.http.request.HttpRequest | None = None, hasher_defaults_overridden: bool = False, **_):
121@receiver(password_hash_changed) 122@receiver(password_changed) 123def on_password_changed( 124 sender, 125 user: User, 126 password: str | None = None, 127 request: HttpRequest | None = None, 128 hasher_defaults_overridden: bool = False, 129 **_, 130): 131 """Log password change""" 132 context = {} 133 if hasher_defaults_overridden: 134 context["hasher_defaults_overridden"] = hasher_defaults_overridden 135 Event.new(EventAction.PASSWORD_SET, **context).from_http(request, user=user)
Log password change
@receiver(post_save, sender=Event)
def
event_post_save_notification(sender, instance: authentik.events.models.Event, **_):
138@receiver(post_save, sender=Event) 139def event_post_save_notification(sender, instance: Event, **_): 140 """Start task to check if any policies trigger an notification on this event""" 141 from authentik.events.tasks import event_trigger_dispatch 142 143 event_trigger_dispatch.send(instance.event_uuid)
Start task to check if any policies trigger an notification on this event
@receiver(pre_delete, sender=User)
def
event_user_pre_delete_cleanup(sender, instance: authentik.core.models.User, **_):
146@receiver(pre_delete, sender=User) 147def event_user_pre_delete_cleanup(sender, instance: User, **_): 148 """If gdpr_compliance is enabled, remove all the user's events""" 149 from authentik.events.tasks import gdpr_cleanup 150 151 if get_system_settings().gdpr_compliance: 152 gdpr_cleanup.send(instance.pk)
If gdpr_compliance is enabled, remove all the user's events
@receiver(post_save, sender=Event)
def
event_post_save_activity( sender, instance: authentik.events.models.Event, created: bool, raw: bool = False, **_):
155@receiver(post_save, sender=Event) 156def event_post_save_activity(sender, instance: Event, created: bool, raw: bool = False, **_): 157 """Credit the finalized event identity, never nested impersonation identities.""" 158 if ( 159 raw 160 or not created 161 or instance.action not in (EventAction.LOGIN, EventAction.AUTHORIZE_APPLICATION) 162 ): 163 return 164 if isinstance(instance.user, dict): 165 UserActivity.objects.record(instance.user.get("pk"), instance.created)
Credit the finalized event identity, never nested impersonation identities.