authentik.events.models

authentik events models

  1"""authentik events models"""
  2
  3from collections.abc import Generator
  4from datetime import timedelta
  5from difflib import get_close_matches
  6from functools import lru_cache
  7from inspect import currentframe
  8from typing import Any
  9from uuid import uuid4
 10
 11from channels.layers import get_channel_layer
 12from django.apps import apps
 13from django.db import models
 14from django.db.models import Q
 15from django.db.models.lookups import IsNull
 16from django.http import HttpRequest
 17from django.http.request import QueryDict
 18from django.utils.timezone import now
 19from django.utils.translation import gettext_lazy as _
 20from requests import RequestException
 21from rest_framework.serializers import Serializer
 22from structlog.stdlib import get_logger
 23
 24from authentik import authentik_full_version
 25from authentik.admin.models import SystemSettings
 26from authentik.admin.utils import get_system_settings
 27from authentik.brands.models import Brand
 28from authentik.brands.utils import DEFAULT_BRAND
 29from authentik.core.middleware import (
 30    SESSION_KEY_IMPERSONATE_ORIGINAL_USER,
 31    SESSION_KEY_IMPERSONATE_USER,
 32)
 33from authentik.core.models import Group, PropertyMapping, User
 34from authentik.crypto.models import CertificateKeyPair
 35from authentik.events.consumer import build_user_group
 36from authentik.events.context_processors.base import get_context_processors
 37from authentik.events.utils import (
 38    cleanse_dict,
 39    get_user,
 40    model_to_dict,
 41    sanitize_dict,
 42    sanitize_item,
 43)
 44from authentik.lib.models import (
 45    DomainlessURLValidator,
 46    ExpiringModel,
 47    SerializerModel,
 48    SimpleThroughModel,
 49)
 50from authentik.lib.tracing.exceptions import TracingIgnoredException
 51from authentik.lib.utils.errors import exception_to_dict
 52from authentik.lib.utils.http import get_http_session
 53from authentik.lib.utils.time import timedelta_from_string
 54from authentik.policies.models import PolicyBindingModel
 55from authentik.root.middleware import ClientIPMiddleware
 56from authentik.stages.email.models import EmailTemplates
 57from authentik.stages.email.utils import TemplateEmailMessage
 58from authentik.tasks.models import TasksModel
 59
 60LOGGER = get_logger()
 61DISCORD_FIELD_LIMIT = 25
 62NOTIFICATION_SUMMARY_LENGTH = 75
 63
 64
 65def default_event_duration():
 66    """Default duration an Event is saved.
 67    This is used as a fallback when no brand is available"""
 68    try:
 69        settings = get_system_settings()
 70        return now() + timedelta_from_string(settings.event_retention)
 71    except SystemSettings.DoesNotExist:
 72        return now() + timedelta(days=365)
 73
 74
 75def default_brand():
 76    """Get a default value for brand"""
 77    return sanitize_dict(model_to_dict(DEFAULT_BRAND))
 78
 79
 80@lru_cache
 81def django_app_names() -> list[str]:
 82    """Get a cached list of all django apps' names (not labels)"""
 83    return [x.name for x in apps.app_configs.values()]
 84
 85
 86@lru_cache
 87def app_for_module(module: str) -> str:
 88    """Match a module to the django app it belongs to, or keep the module name"""
 89    django_apps: list[str] = get_close_matches(module, django_app_names(), n=1)
 90    # Also ensure that closest django app has the correct prefix
 91    if len(django_apps) > 0 and django_apps[0].startswith(module):
 92        return django_apps[0]
 93    return module
 94
 95
 96class NotificationTransportError(TracingIgnoredException):
 97    """Error raised when a notification fails to be delivered"""
 98
 99
100class EventAction(models.TextChoices):
101    """All possible actions to save into the events log"""
102
103    LOGIN = "login"
104    LOGIN_FAILED = "login_failed"
105    LOGOUT = "logout"
106
107    USER_WRITE = "user_write"
108    USER_OFFBOARDED = "user_offboarded"
109    USER_EXPIRATION_WARNING = "user_expiration_warning"
110    SUSPICIOUS_REQUEST = "suspicious_request"
111    PASSWORD_SET = "password_set"  # noqa # nosec
112    AUTHENTICATOR_LOCKED = "authenticator_locked"  # noqa # nosec
113    AUTHENTICATOR_UNLOCKED = "authenticator_unlocked"  # noqa # nosec
114
115    REQUIRED_ACTION_COMPLETED = "required_action_completed"
116
117    SECRET_VIEW = "secret_view"  # noqa # nosec
118    SECRET_ROTATE = "secret_rotate"  # noqa # nosec
119
120    INVITE_USED = "invitation_used"
121
122    AUTHORIZE_APPLICATION = "authorize_application"
123    SOURCE_LINKED = "source_linked"
124
125    IMPERSONATION_STARTED = "impersonation_started"
126    IMPERSONATION_ENDED = "impersonation_ended"
127
128    FLOW_EXECUTION = "flow_execution"
129    POLICY_EXECUTION = "policy_execution"
130    POLICY_EXCEPTION = "policy_exception"
131    PROPERTY_MAPPING_EXCEPTION = "property_mapping_exception"
132
133    SYSTEM_TASK_EXECUTION = "system_task_execution"
134    SYSTEM_TASK_EXCEPTION = "system_task_exception"
135    SYSTEM_EXCEPTION = "system_exception"
136
137    CONFIGURATION_ERROR = "configuration_error"
138    CONFIGURATION_WARNING = "configuration_warning"
139
140    MODEL_CREATED = "model_created"
141    MODEL_UPDATED = "model_updated"
142    MODEL_DELETED = "model_deleted"
143    EMAIL_SENT = "email_sent"
144
145    UPDATE_AVAILABLE = "update_available"
146
147    EXPORT_READY = "export_ready"
148
149    REVIEW_INITIATED = "review_initiated"
150    REVIEW_OVERDUE = "review_overdue"
151    REVIEW_ATTESTED = "review_attested"
152    REVIEW_COMPLETED = "review_completed"
153
154    ACCESS_REQUEST_CREATED = "access_request_created"
155    ACCESS_REQUEST_APPROVED = "access_request_approved"
156    ACCESS_REQUEST_DENIED = "access_request_denied"
157    ACCESS_REQUEST_REVOKED = "access_request_revoked"
158
159    CUSTOM_PREFIX = "custom_"
160
161
162def event_actions():
163    # Wrapper used in models to prevent migrations constantly changing when actions are added
164    return EventAction.choices
165
166
167class Event(SerializerModel, ExpiringModel):
168    """An individual Audit/Metrics/Notification/Error Event"""
169
170    event_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
171    user = models.JSONField(default=dict)
172    action = models.TextField(choices=event_actions)
173    app = models.TextField()
174    context = models.JSONField(default=dict, blank=True)
175    client_ip = models.GenericIPAddressField(null=True)
176    created = models.DateTimeField(auto_now_add=True)
177    brand = models.JSONField(default=default_brand, blank=True)
178
179    # Shadow the expires attribute from ExpiringModel to override the default duration
180    expires = models.DateTimeField(default=default_event_duration)
181
182    @staticmethod
183    def _get_app_from_request(request: HttpRequest) -> str:
184        if not isinstance(request, HttpRequest):
185            return ""
186        return request.resolver_match.app_name
187
188    @staticmethod
189    def new(
190        action: str | EventAction,
191        app: str | None = None,
192        **kwargs,
193    ) -> Event:
194        """Create new Event instance from arguments. Instance is NOT saved."""
195        if not isinstance(action, EventAction):
196            action = EventAction.CUSTOM_PREFIX + action
197        if not app:
198            current = currentframe()
199            parent = current.f_back
200            app = app_for_module(parent.f_globals["__name__"])
201        cleaned_kwargs = cleanse_dict(sanitize_dict(kwargs))
202        event = Event(action=action, app=app, context=cleaned_kwargs)
203        return event
204
205    def with_exception(self, exc: Exception) -> Event:
206        """Add data from 'exc' to the event in a database-saveable format"""
207        self.context.setdefault("message", str(exc))
208        self.context["exception"] = exception_to_dict(exc)
209        return self
210
211    def set_user(self, user: User) -> Event:
212        """Set `.user` based on user, ensuring the correct attributes are copied.
213        This should only be used when self.from_http is *not* used."""
214        self.user = get_user(user)
215        return self
216
217    def from_http(self, request: HttpRequest, user: User | None = None) -> Event:
218        """Add data from a Django-HttpRequest, allowing the creation of
219        Events independently from requests.
220        `user` arguments optionally overrides user from requests."""
221        if request:
222            from authentik.flows.views.executor import QS_QUERY
223
224            self.context["http_request"] = {
225                "path": request.path,
226                "method": request.method,
227                "args": cleanse_dict(QueryDict(request.META.get("QUERY_STRING", ""))),
228                "user_agent": request.META.get("HTTP_USER_AGENT", ""),
229            }
230            if hasattr(request, "request_id"):
231                self.context["http_request"]["request_id"] = request.request_id
232            # Special case for events created during flow execution
233            # since they keep the http query within a wrapped query
234            if QS_QUERY in self.context["http_request"]["args"]:
235                wrapped = self.context["http_request"]["args"][QS_QUERY]
236                self.context["http_request"]["args"] = cleanse_dict(QueryDict(wrapped))
237        if hasattr(request, "brand"):
238            brand: Brand = request.brand
239            self.brand = sanitize_dict(model_to_dict(brand))
240        if user:
241            self.user = get_user(user)
242        elif hasattr(request, "user"):
243            self.user = get_user(request.user)
244        if hasattr(request, "session"):
245            from authentik.flows.views.executor import SESSION_KEY_PLAN
246
247            # Check if we're currently impersonating, and add that user
248            if SESSION_KEY_IMPERSONATE_ORIGINAL_USER in request.session:
249                self.user = get_user(request.session[SESSION_KEY_IMPERSONATE_ORIGINAL_USER])
250                self.user["on_behalf_of"] = get_user(request.session[SESSION_KEY_IMPERSONATE_USER])
251            # Special case for events that happen during a flow, the user might not be authenticated
252            # yet but is a pending user instead
253            if SESSION_KEY_PLAN in request.session:
254                from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlan
255
256                plan: FlowPlan = request.session[SESSION_KEY_PLAN]
257                pending_user = plan.context.get(PLAN_CONTEXT_PENDING_USER, None)
258                # Only save `authenticated_as` if there's a different pending user in the flow
259                # than the user that is authenticated
260                if pending_user and (
261                    (pending_user.pk and pending_user.pk != self.user.get("pk"))
262                    or (not pending_user.pk)
263                ):
264                    orig_user = self.user.copy()
265
266                    self.user = {"authenticated_as": orig_user, **get_user(pending_user)}
267        # User 255.255.255.255 as fallback if IP cannot be determined
268        self.client_ip = ClientIPMiddleware.get_client_ip(request)
269        # Enrich event data
270        for processor in get_context_processors():
271            processor.enrich_event(self)
272        # If there's no app set, we get it from the requests too
273        if not self.app:
274            self.app = Event._get_app_from_request(request)
275        self.save()
276        return self
277
278    @staticmethod
279    def log_deprecation(
280        identifier: str, message: str, cause: str | None = None, expiry_days=30, **kwargs
281    ):
282        query = Q(
283            action=EventAction.CONFIGURATION_WARNING,
284            context__deprecation=identifier,
285        )
286        cause = str(cause)
287        if cause:
288            query &= Q(context__cause=cause)
289        if Event.objects.filter(query).exists():
290            return
291        event = Event.new(
292            EventAction.CONFIGURATION_WARNING,
293            deprecation=identifier,
294            message=message,
295            cause=cause,
296            **kwargs,
297        )
298        event.expires = now() + timedelta(days=expiry_days)
299        event.save()
300
301    def save(self, *args, **kwargs):
302        if self._state.adding:
303            LOGGER.info(
304                "Created Event",
305                action=self.action,
306                context=self.context,
307                client_ip=self.client_ip,
308                user=self.user,
309            )
310        super().save(*args, **kwargs)
311
312    @property
313    def serializer(self) -> type[Serializer]:
314        from authentik.events.api.events import EventSerializer
315
316        return EventSerializer
317
318    @property
319    def summary(self) -> str:
320        """Return a summary of this event."""
321        if "message" in self.context:
322            return self.context["message"]
323        return f"{self.action}: {self.context}"
324
325    @property
326    def hyperlink(self) -> str | None:
327        return self.context.get("hyperlink")
328
329    @property
330    def hyperlink_label(self) -> str | None:
331        return self.context.get("hyperlink_label")
332
333    def __str__(self) -> str:
334        return f"Event action={self.action} user={self.user} context={self.context}"
335
336    class Meta:
337        verbose_name = _("Event")
338        verbose_name_plural = _("Events")
339        indexes = ExpiringModel.Meta.indexes + [
340            models.Index(fields=["action"]),
341            models.Index(fields=["app"]),
342            # Event volume charts count events by time and action. Including the other columns
343            # they read lets Postgres count from the index without reading the events.
344            models.Index(
345                fields=["created"],
346                include=["action", "expires", "expiring"],
347                name="authentik_e_created_cov_idx",
348            ),
349            models.Index(fields=["client_ip"]),
350            # The context keys the API filters by. Few events have them, so the indexes skip
351            # the others: Postgres cannot merge equal jsonb entries, so they would cost one
352            # entry per event. A filter on a key implies it is not null, so these still apply.
353            models.Index(
354                models.F("context__authorized_application__pk"),
355                "created",
356                condition=Q(IsNull(models.F("context__authorized_application__pk"), False)),
357                name="authentik_e_ctx_app_pk_idx",
358            ),
359            models.Index(
360                models.F("context__username"),
361                condition=Q(IsNull(models.F("context__username"), False)),
362                name="authentik_e_ctx_username_idx",
363            ),
364            # Object changelogs filter by model and action. Postgres assumes the two are unrelated
365            # and would combine an index on the model with the much larger action index, so this
366            # index has both. It is not partial: Postgres only keeps statistics for the
367            # expressions of indexes that cover every row.
368            models.Index(
369                models.F("context__model__pk"), "action", name="authentik_e_ctx_model_pk_idx"
370            ),
371            models.Index(
372                models.F("user__pk"),
373                name="authentik_e_user_pk__idx",
374            ),
375            models.Index(models.F("user__username"), name="authentik_e_user_username_idx"),
376        ]
377
378
379class TransportMode(models.TextChoices):
380    """Modes that a notification transport can send a notification"""
381
382    LOCAL = "local", _("authentik inbuilt notifications")
383    WEBHOOK = "webhook", _("Generic Webhook")
384    WEBHOOK_SLACK = "webhook_slack", _("Slack Webhook (Slack/Discord)")
385    EMAIL = "email", _("Email")
386
387
388class NotificationTransport(TasksModel, SerializerModel):
389    """Action which is executed when a Rule matches"""
390
391    uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
392
393    name = models.TextField(unique=True)
394    mode = models.TextField(choices=TransportMode.choices, default=TransportMode.LOCAL)
395    send_once = models.BooleanField(
396        default=False,
397        help_text=_(
398            "Only send notification once, for example when sending a webhook into a chat channel."
399        ),
400    )
401
402    email_subject_prefix = models.TextField(default="authentik Notification: ", blank=True)
403    email_template = models.TextField(default=EmailTemplates.EVENT_NOTIFICATION)
404
405    webhook_url = models.TextField(blank=True, validators=[DomainlessURLValidator()])
406    webhook_ca = models.ForeignKey(
407        CertificateKeyPair,
408        null=True,
409        default=None,
410        on_delete=models.SET_DEFAULT,
411        help_text=_(
412            "When set, the selected certificate is used to "
413            "validate the certificate of the webhook server."
414        ),
415    )
416    webhook_mapping_body = models.ForeignKey(
417        "NotificationWebhookMapping",
418        on_delete=models.SET_DEFAULT,
419        null=True,
420        default=None,
421        related_name="+",
422        help_text=_(
423            "Customize the body of the request. "
424            "Mapping should return data that is JSON-serializable."
425        ),
426    )
427    webhook_mapping_headers = models.ForeignKey(
428        "NotificationWebhookMapping",
429        on_delete=models.SET_DEFAULT,
430        null=True,
431        default=None,
432        related_name="+",
433        help_text=_(
434            "Configure additional headers to be sent. "
435            "Mapping should return a dictionary of key-value pairs"
436        ),
437    )
438
439    def send(self, notification: Notification) -> list[str]:
440        """Send notification to user, called from async task"""
441        if self.mode == TransportMode.LOCAL:
442            return self.send_local(notification)
443        if self.mode == TransportMode.WEBHOOK:
444            return self.send_webhook(notification)
445        if self.mode == TransportMode.WEBHOOK_SLACK:
446            return self.send_webhook_slack(notification)
447        if self.mode == TransportMode.EMAIL:
448            return self.send_email(notification)
449        raise ValueError(f"Invalid mode {self.mode} set")
450
451    def send_local(self, notification: Notification) -> list[str]:
452        """Local notification delivery"""
453        if self.webhook_mapping_body:
454            self.webhook_mapping_body.evaluate(
455                user=notification.user,
456                request=None,
457                notification=notification,
458            )
459        notification.save()
460        layer = get_channel_layer()
461        layer.group_send_blocking(
462            build_user_group(notification.user),
463            {
464                "type": "event.notification",
465                "id": str(notification.pk),
466                "data": notification.serializer(notification).data,
467            },
468        )
469        return []
470
471    def send_webhook(self, notification: Notification) -> list[str]:
472        """Send notification to generic webhook"""
473        default_body = {
474            "body": notification.body,
475            "severity": notification.severity,
476            "user_email": notification.user.email,
477            "user_username": notification.user.username,
478        }
479        if notification.event and notification.event.user:
480            default_body["event_user_email"] = notification.event.user.get("email", None)
481            default_body["event_user_username"] = notification.event.user.get("username", None)
482        headers = {}
483        if self.webhook_mapping_body:
484            default_body = sanitize_item(
485                self.webhook_mapping_body.evaluate(
486                    user=notification.user,
487                    request=None,
488                    notification=notification,
489                )
490            )
491        if self.webhook_mapping_headers:
492            headers = sanitize_item(
493                self.webhook_mapping_headers.evaluate(
494                    user=notification.user,
495                    request=None,
496                    notification=notification,
497                )
498            )
499
500        def send(**kwargs):
501            try:
502                response = get_http_session().post(
503                    self.webhook_url,
504                    json=default_body,
505                    headers=headers,
506                    allow_redirects=False,
507                    **kwargs,
508                )
509                response.raise_for_status()
510            except RequestException as exc:
511                raise NotificationTransportError(
512                    exc.response.text if exc.response is not None else str(exc)
513                ) from exc
514            return [
515                response.status_code,
516            ]
517
518        if self.webhook_ca:
519            # Imports the docker client, only load it when a custom CA is set
520            from authentik.outposts.docker_tls import DockerInlineTLS
521
522            with DockerInlineTLS(self.webhook_ca, authentication_kp=None) as tls:
523                return send(verify=tls.ca_cert)
524        return send()
525
526    def send_webhook_slack(self, notification: Notification) -> list[str]:
527        """Send notification to slack or slack-compatible endpoints"""
528        fields = [
529            {
530                "title": str(_("Severity")),
531                "value": notification.severity,
532                "short": True,
533            },
534            {
535                "title": str(_("Dispatched for user")),
536                "value": str(notification.user),
537                "short": True,
538            },
539        ]
540        if notification.event:
541            if notification.event.user:
542                fields.append(
543                    {
544                        "title": str(_("Event user")),
545                        "value": str(notification.event.user.get("username")),
546                        "short": True,
547                    },
548                )
549            for key, value in notification.event.context.items():
550                if not isinstance(value, str):
551                    continue
552                # https://birdie0.github.io/discord-webhooks-guide/other/field_limits.html
553                if len(fields) >= DISCORD_FIELD_LIMIT:
554                    continue
555                fields.append({"title": key[:256], "value": value[:1024]})
556        body = {
557            "username": "authentik",
558            "icon_url": "https://goauthentik.io/img/icon.png",
559            "attachments": [
560                {
561                    "author_name": "authentik",
562                    "author_link": "https://goauthentik.io",
563                    "author_icon": "https://goauthentik.io/img/icon.png",
564                    "title": notification.body,
565                    "color": "#fd4b2d",
566                    "fields": fields,
567                    "footer": f"authentik {authentik_full_version()}",
568                }
569            ],
570        }
571        if notification.event:
572            body["attachments"][0]["title"] = notification.event.action
573        headers = {}
574        if self.webhook_mapping_body:
575            body = sanitize_item(
576                self.webhook_mapping_body.evaluate(
577                    user=notification.user,
578                    request=None,
579                    notification=notification,
580                    original_body=body,
581                )
582            )
583        if self.webhook_mapping_headers:
584            headers = sanitize_item(
585                self.webhook_mapping_headers.evaluate(
586                    user=notification.user,
587                    request=None,
588                    notification=notification,
589                )
590            )
591        try:
592            response = get_http_session().post(
593                self.webhook_url,
594                json=body,
595                headers=headers,
596                allow_redirects=False,
597            )
598            response.raise_for_status()
599        except RequestException as exc:
600            text = exc.response.text if exc.response is not None else str(exc)
601            raise NotificationTransportError(text) from exc
602        return [
603            response.status_code,
604        ]
605
606    def send_email(self, notification: Notification) -> list[str]:
607        """Send notification via global email configuration"""
608        from authentik.stages.email.tasks import send_mail
609
610        if notification.user.email.strip() == "":
611            LOGGER.info(
612                "Discarding notification as user has no email address",
613                user=notification.user,
614                notification=notification,
615            )
616            return None
617        context = {
618            "key_value": {
619                "user_email": notification.user.email,
620                "user_username": notification.user.username,
621            },
622            "body": notification.body,
623            "title": "",
624        }
625        if notification.event and notification.event.user:
626            context["key_value"]["event_user_email"] = notification.event.user.get("email", None)
627            context["key_value"]["event_user_username"] = notification.event.user.get(
628                "username", None
629            )
630        if notification.hyperlink:
631            context["link"] = {
632                "target": notification.hyperlink,
633                "label": notification.hyperlink_label,
634            }
635        if notification.event:
636            context["title"] += notification.event.action
637            for key, value in notification.event.context.items():
638                if not isinstance(value, str):
639                    continue
640                context["key_value"][key] = value
641        else:
642            context["title"] += notification.body[:NOTIFICATION_SUMMARY_LENGTH]
643        # TODO: improve permission check
644        if notification.user.is_superuser:
645            context["source"] = {
646                "from": self.name,
647            }
648        mail = TemplateEmailMessage(
649            subject=self.email_subject_prefix + context["title"],
650            to=[(notification.user.name, notification.user.email)],
651            language=notification.user.locale(),
652            template_name=self.email_template,
653            template_context=context,
654        )
655        send_mail.send_with_options(args=(mail.__dict__,), rel_obj=self)
656        return []
657
658    @property
659    def serializer(self) -> type[Serializer]:
660        from authentik.events.api.notification_transports import (
661            NotificationTransportSerializer,
662        )
663
664        return NotificationTransportSerializer
665
666    def __str__(self) -> str:
667        return f"Notification Transport {self.name}"
668
669    class Meta:
670        verbose_name = _("Notification Transport")
671        verbose_name_plural = _("Notification Transports")
672
673
674class NotificationSeverity(models.TextChoices):
675    """Severity images that a notification can have"""
676
677    NOTICE = "notice", _("Notice")
678    WARNING = "warning", _("Warning")
679    ALERT = "alert", _("Alert")
680
681
682class Notification(SerializerModel):
683    """Event Notification"""
684
685    uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
686    severity = models.TextField(choices=NotificationSeverity.choices)
687    body = models.TextField()
688    hyperlink = models.TextField(blank=True, null=True, max_length=4096)
689    hyperlink_label = models.TextField(blank=True, null=True)
690    created = models.DateTimeField(auto_now_add=True)
691    event = models.ForeignKey(Event, on_delete=models.SET_NULL, null=True, blank=True)
692    seen = models.BooleanField(default=False)
693    user = models.ForeignKey(User, on_delete=models.CASCADE)
694
695    @property
696    def serializer(self) -> type[Serializer]:
697        from authentik.events.api.notifications import NotificationSerializer
698
699        return NotificationSerializer
700
701    def __str__(self) -> str:
702        body_trunc = (
703            (self.body[:NOTIFICATION_SUMMARY_LENGTH] + "..")
704            if len(self.body) > NOTIFICATION_SUMMARY_LENGTH
705            else self.body
706        )
707        return f"Notification for user {self.user_id}: {body_trunc}"
708
709    class Meta:
710        verbose_name = _("Notification")
711        verbose_name_plural = _("Notifications")
712        indexes = [
713            # The notification drawer lists a user's unseen notifications, newest first
714            models.Index(
715                fields=["user", "created"],
716                condition=Q(seen=False),
717                name="authentik_e_notif_unseen_idx",
718            ),
719        ]
720
721
722class NotificationRule(TasksModel, SerializerModel, PolicyBindingModel):
723    """Decide when to create a Notification based on policies attached to this object."""
724
725    name = models.TextField(unique=True)
726    transports = models.ManyToManyField(
727        NotificationTransport,
728        help_text=_(
729            "Select which transports should be used to notify the user. Select a transport "
730            "in Local mode to show the notification in the authentik UI. If none are selected, "
731            "no notification is created."
732        ),
733        blank=True,
734        through="NotificationRuleNotificationTransport",
735    )
736    severity = models.TextField(
737        choices=NotificationSeverity.choices,
738        default=NotificationSeverity.NOTICE,
739        help_text=_("Controls which severity level the created notifications will have."),
740    )
741    destination_group = models.ForeignKey(
742        Group,
743        help_text=_(
744            "Define which group of users this notification should be sent and shown to. "
745            "If left empty, Notification won't ben sent."
746        ),
747        null=True,
748        blank=True,
749        on_delete=models.SET_NULL,
750    )
751    destination_event_user = models.BooleanField(
752        default=False,
753        help_text=_(
754            "When enabled, notification will be sent to user the user that triggered the event."
755            "When destination_group is configured, notification is sent to both."
756        ),
757    )
758
759    def destination_users(self, event: Event) -> Generator[User, Any]:
760        if self.destination_event_user and event.user.get("pk"):
761            yield User(pk=event.user.get("pk"))
762        if self.destination_group:
763            yield from self.destination_group.users.all()
764
765    @property
766    def serializer(self) -> type[Serializer]:
767        from authentik.events.api.notification_rules import NotificationRuleSerializer
768
769        return NotificationRuleSerializer
770
771    def __str__(self) -> str:
772        return f"Notification Rule {self.name}"
773
774    class Meta:
775        verbose_name = _("Notification Rule")
776        verbose_name_plural = _("Notification Rules")
777
778
779class NotificationRuleNotificationTransport(SimpleThroughModel):
780    notification_rule = models.ForeignKey(
781        NotificationRule, on_delete=models.CASCADE, db_column="notificationrule_id"
782    )
783    notification_transport = models.ForeignKey(
784        NotificationTransport,
785        on_delete=models.CASCADE,
786        db_column="notificationtransport_id",
787    )
788
789    class Meta:
790        db_table = "authentik_events_notificationrule_transports"
791        unique_together = (("notification_rule", "notification_transport"),)
792        verbose_name = _("Notification Rule Notification Transport")
793        verbose_name_plural = _("Notification Rule Notification Transports")
794
795    def __str__(self):
796        return (
797            "NotificationRuleNotificationTransport for NotificationRule "
798            f"{self.notification_rule_id} "
799            f"and NotificationTransport {self.notification_transport_id}."
800        )
801
802
803class NotificationWebhookMapping(PropertyMapping):
804    """Modify the payload of outgoing webhook requests"""
805
806    @property
807    def component(self) -> str:
808        return "ak-property-mapping-notification-form"
809
810    @property
811    def serializer(self) -> type[type[Serializer]]:
812        from authentik.events.api.notification_mappings import (
813            NotificationWebhookMappingSerializer,
814        )
815
816        return NotificationWebhookMappingSerializer
817
818    def __str__(self):
819        return f"Webhook Mapping {self.name}"
820
821    class Meta:
822        verbose_name = _("Webhook Mapping")
823        verbose_name_plural = _("Webhook Mappings")
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
DISCORD_FIELD_LIMIT = 25
NOTIFICATION_SUMMARY_LENGTH = 75
def default_event_duration():
66def default_event_duration():
67    """Default duration an Event is saved.
68    This is used as a fallback when no brand is available"""
69    try:
70        settings = get_system_settings()
71        return now() + timedelta_from_string(settings.event_retention)
72    except SystemSettings.DoesNotExist:
73        return now() + timedelta(days=365)

Default duration an Event is saved. This is used as a fallback when no brand is available

def default_brand():
76def default_brand():
77    """Get a default value for brand"""
78    return sanitize_dict(model_to_dict(DEFAULT_BRAND))

Get a default value for brand

@lru_cache
def django_app_names() -> list[str]:
81@lru_cache
82def django_app_names() -> list[str]:
83    """Get a cached list of all django apps' names (not labels)"""
84    return [x.name for x in apps.app_configs.values()]

Get a cached list of all django apps' names (not labels)

@lru_cache
def app_for_module(module: str) -> str:
87@lru_cache
88def app_for_module(module: str) -> str:
89    """Match a module to the django app it belongs to, or keep the module name"""
90    django_apps: list[str] = get_close_matches(module, django_app_names(), n=1)
91    # Also ensure that closest django app has the correct prefix
92    if len(django_apps) > 0 and django_apps[0].startswith(module):
93        return django_apps[0]
94    return module

Match a module to the django app it belongs to, or keep the module name

class NotificationTransportError(authentik.lib.tracing.exceptions.TracingIgnoredException):
97class NotificationTransportError(TracingIgnoredException):
98    """Error raised when a notification fails to be delivered"""

Error raised when a notification fails to be delivered

class EventAction(django.db.models.enums.TextChoices):
101class EventAction(models.TextChoices):
102    """All possible actions to save into the events log"""
103
104    LOGIN = "login"
105    LOGIN_FAILED = "login_failed"
106    LOGOUT = "logout"
107
108    USER_WRITE = "user_write"
109    USER_OFFBOARDED = "user_offboarded"
110    USER_EXPIRATION_WARNING = "user_expiration_warning"
111    SUSPICIOUS_REQUEST = "suspicious_request"
112    PASSWORD_SET = "password_set"  # noqa # nosec
113    AUTHENTICATOR_LOCKED = "authenticator_locked"  # noqa # nosec
114    AUTHENTICATOR_UNLOCKED = "authenticator_unlocked"  # noqa # nosec
115
116    REQUIRED_ACTION_COMPLETED = "required_action_completed"
117
118    SECRET_VIEW = "secret_view"  # noqa # nosec
119    SECRET_ROTATE = "secret_rotate"  # noqa # nosec
120
121    INVITE_USED = "invitation_used"
122
123    AUTHORIZE_APPLICATION = "authorize_application"
124    SOURCE_LINKED = "source_linked"
125
126    IMPERSONATION_STARTED = "impersonation_started"
127    IMPERSONATION_ENDED = "impersonation_ended"
128
129    FLOW_EXECUTION = "flow_execution"
130    POLICY_EXECUTION = "policy_execution"
131    POLICY_EXCEPTION = "policy_exception"
132    PROPERTY_MAPPING_EXCEPTION = "property_mapping_exception"
133
134    SYSTEM_TASK_EXECUTION = "system_task_execution"
135    SYSTEM_TASK_EXCEPTION = "system_task_exception"
136    SYSTEM_EXCEPTION = "system_exception"
137
138    CONFIGURATION_ERROR = "configuration_error"
139    CONFIGURATION_WARNING = "configuration_warning"
140
141    MODEL_CREATED = "model_created"
142    MODEL_UPDATED = "model_updated"
143    MODEL_DELETED = "model_deleted"
144    EMAIL_SENT = "email_sent"
145
146    UPDATE_AVAILABLE = "update_available"
147
148    EXPORT_READY = "export_ready"
149
150    REVIEW_INITIATED = "review_initiated"
151    REVIEW_OVERDUE = "review_overdue"
152    REVIEW_ATTESTED = "review_attested"
153    REVIEW_COMPLETED = "review_completed"
154
155    ACCESS_REQUEST_CREATED = "access_request_created"
156    ACCESS_REQUEST_APPROVED = "access_request_approved"
157    ACCESS_REQUEST_DENIED = "access_request_denied"
158    ACCESS_REQUEST_REVOKED = "access_request_revoked"
159
160    CUSTOM_PREFIX = "custom_"

All possible actions to save into the events log

LOGIN_FAILED = EventAction.LOGIN_FAILED
USER_WRITE = EventAction.USER_WRITE
USER_OFFBOARDED = EventAction.USER_OFFBOARDED
USER_EXPIRATION_WARNING = EventAction.USER_EXPIRATION_WARNING
SUSPICIOUS_REQUEST = EventAction.SUSPICIOUS_REQUEST
PASSWORD_SET = EventAction.PASSWORD_SET
AUTHENTICATOR_LOCKED = EventAction.AUTHENTICATOR_LOCKED
AUTHENTICATOR_UNLOCKED = EventAction.AUTHENTICATOR_UNLOCKED
REQUIRED_ACTION_COMPLETED = EventAction.REQUIRED_ACTION_COMPLETED
SECRET_VIEW = EventAction.SECRET_VIEW
SECRET_ROTATE = EventAction.SECRET_ROTATE
INVITE_USED = EventAction.INVITE_USED
AUTHORIZE_APPLICATION = EventAction.AUTHORIZE_APPLICATION
SOURCE_LINKED = EventAction.SOURCE_LINKED
IMPERSONATION_STARTED = EventAction.IMPERSONATION_STARTED
IMPERSONATION_ENDED = EventAction.IMPERSONATION_ENDED
FLOW_EXECUTION = EventAction.FLOW_EXECUTION
POLICY_EXECUTION = EventAction.POLICY_EXECUTION
POLICY_EXCEPTION = EventAction.POLICY_EXCEPTION
PROPERTY_MAPPING_EXCEPTION = EventAction.PROPERTY_MAPPING_EXCEPTION
SYSTEM_TASK_EXECUTION = EventAction.SYSTEM_TASK_EXECUTION
SYSTEM_TASK_EXCEPTION = EventAction.SYSTEM_TASK_EXCEPTION
SYSTEM_EXCEPTION = EventAction.SYSTEM_EXCEPTION
CONFIGURATION_ERROR = EventAction.CONFIGURATION_ERROR
CONFIGURATION_WARNING = EventAction.CONFIGURATION_WARNING
MODEL_CREATED = EventAction.MODEL_CREATED
MODEL_UPDATED = EventAction.MODEL_UPDATED
MODEL_DELETED = EventAction.MODEL_DELETED
EMAIL_SENT = EventAction.EMAIL_SENT
UPDATE_AVAILABLE = EventAction.UPDATE_AVAILABLE
EXPORT_READY = EventAction.EXPORT_READY
REVIEW_INITIATED = EventAction.REVIEW_INITIATED
REVIEW_OVERDUE = EventAction.REVIEW_OVERDUE
REVIEW_ATTESTED = EventAction.REVIEW_ATTESTED
REVIEW_COMPLETED = EventAction.REVIEW_COMPLETED
ACCESS_REQUEST_CREATED = EventAction.ACCESS_REQUEST_CREATED
ACCESS_REQUEST_APPROVED = EventAction.ACCESS_REQUEST_APPROVED
ACCESS_REQUEST_DENIED = EventAction.ACCESS_REQUEST_DENIED
ACCESS_REQUEST_REVOKED = EventAction.ACCESS_REQUEST_REVOKED
CUSTOM_PREFIX = EventAction.CUSTOM_PREFIX
def event_actions():
163def event_actions():
164    # Wrapper used in models to prevent migrations constantly changing when actions are added
165    return EventAction.choices
168class Event(SerializerModel, ExpiringModel):
169    """An individual Audit/Metrics/Notification/Error Event"""
170
171    event_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
172    user = models.JSONField(default=dict)
173    action = models.TextField(choices=event_actions)
174    app = models.TextField()
175    context = models.JSONField(default=dict, blank=True)
176    client_ip = models.GenericIPAddressField(null=True)
177    created = models.DateTimeField(auto_now_add=True)
178    brand = models.JSONField(default=default_brand, blank=True)
179
180    # Shadow the expires attribute from ExpiringModel to override the default duration
181    expires = models.DateTimeField(default=default_event_duration)
182
183    @staticmethod
184    def _get_app_from_request(request: HttpRequest) -> str:
185        if not isinstance(request, HttpRequest):
186            return ""
187        return request.resolver_match.app_name
188
189    @staticmethod
190    def new(
191        action: str | EventAction,
192        app: str | None = None,
193        **kwargs,
194    ) -> Event:
195        """Create new Event instance from arguments. Instance is NOT saved."""
196        if not isinstance(action, EventAction):
197            action = EventAction.CUSTOM_PREFIX + action
198        if not app:
199            current = currentframe()
200            parent = current.f_back
201            app = app_for_module(parent.f_globals["__name__"])
202        cleaned_kwargs = cleanse_dict(sanitize_dict(kwargs))
203        event = Event(action=action, app=app, context=cleaned_kwargs)
204        return event
205
206    def with_exception(self, exc: Exception) -> Event:
207        """Add data from 'exc' to the event in a database-saveable format"""
208        self.context.setdefault("message", str(exc))
209        self.context["exception"] = exception_to_dict(exc)
210        return self
211
212    def set_user(self, user: User) -> Event:
213        """Set `.user` based on user, ensuring the correct attributes are copied.
214        This should only be used when self.from_http is *not* used."""
215        self.user = get_user(user)
216        return self
217
218    def from_http(self, request: HttpRequest, user: User | None = None) -> Event:
219        """Add data from a Django-HttpRequest, allowing the creation of
220        Events independently from requests.
221        `user` arguments optionally overrides user from requests."""
222        if request:
223            from authentik.flows.views.executor import QS_QUERY
224
225            self.context["http_request"] = {
226                "path": request.path,
227                "method": request.method,
228                "args": cleanse_dict(QueryDict(request.META.get("QUERY_STRING", ""))),
229                "user_agent": request.META.get("HTTP_USER_AGENT", ""),
230            }
231            if hasattr(request, "request_id"):
232                self.context["http_request"]["request_id"] = request.request_id
233            # Special case for events created during flow execution
234            # since they keep the http query within a wrapped query
235            if QS_QUERY in self.context["http_request"]["args"]:
236                wrapped = self.context["http_request"]["args"][QS_QUERY]
237                self.context["http_request"]["args"] = cleanse_dict(QueryDict(wrapped))
238        if hasattr(request, "brand"):
239            brand: Brand = request.brand
240            self.brand = sanitize_dict(model_to_dict(brand))
241        if user:
242            self.user = get_user(user)
243        elif hasattr(request, "user"):
244            self.user = get_user(request.user)
245        if hasattr(request, "session"):
246            from authentik.flows.views.executor import SESSION_KEY_PLAN
247
248            # Check if we're currently impersonating, and add that user
249            if SESSION_KEY_IMPERSONATE_ORIGINAL_USER in request.session:
250                self.user = get_user(request.session[SESSION_KEY_IMPERSONATE_ORIGINAL_USER])
251                self.user["on_behalf_of"] = get_user(request.session[SESSION_KEY_IMPERSONATE_USER])
252            # Special case for events that happen during a flow, the user might not be authenticated
253            # yet but is a pending user instead
254            if SESSION_KEY_PLAN in request.session:
255                from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlan
256
257                plan: FlowPlan = request.session[SESSION_KEY_PLAN]
258                pending_user = plan.context.get(PLAN_CONTEXT_PENDING_USER, None)
259                # Only save `authenticated_as` if there's a different pending user in the flow
260                # than the user that is authenticated
261                if pending_user and (
262                    (pending_user.pk and pending_user.pk != self.user.get("pk"))
263                    or (not pending_user.pk)
264                ):
265                    orig_user = self.user.copy()
266
267                    self.user = {"authenticated_as": orig_user, **get_user(pending_user)}
268        # User 255.255.255.255 as fallback if IP cannot be determined
269        self.client_ip = ClientIPMiddleware.get_client_ip(request)
270        # Enrich event data
271        for processor in get_context_processors():
272            processor.enrich_event(self)
273        # If there's no app set, we get it from the requests too
274        if not self.app:
275            self.app = Event._get_app_from_request(request)
276        self.save()
277        return self
278
279    @staticmethod
280    def log_deprecation(
281        identifier: str, message: str, cause: str | None = None, expiry_days=30, **kwargs
282    ):
283        query = Q(
284            action=EventAction.CONFIGURATION_WARNING,
285            context__deprecation=identifier,
286        )
287        cause = str(cause)
288        if cause:
289            query &= Q(context__cause=cause)
290        if Event.objects.filter(query).exists():
291            return
292        event = Event.new(
293            EventAction.CONFIGURATION_WARNING,
294            deprecation=identifier,
295            message=message,
296            cause=cause,
297            **kwargs,
298        )
299        event.expires = now() + timedelta(days=expiry_days)
300        event.save()
301
302    def save(self, *args, **kwargs):
303        if self._state.adding:
304            LOGGER.info(
305                "Created Event",
306                action=self.action,
307                context=self.context,
308                client_ip=self.client_ip,
309                user=self.user,
310            )
311        super().save(*args, **kwargs)
312
313    @property
314    def serializer(self) -> type[Serializer]:
315        from authentik.events.api.events import EventSerializer
316
317        return EventSerializer
318
319    @property
320    def summary(self) -> str:
321        """Return a summary of this event."""
322        if "message" in self.context:
323            return self.context["message"]
324        return f"{self.action}: {self.context}"
325
326    @property
327    def hyperlink(self) -> str | None:
328        return self.context.get("hyperlink")
329
330    @property
331    def hyperlink_label(self) -> str | None:
332        return self.context.get("hyperlink_label")
333
334    def __str__(self) -> str:
335        return f"Event action={self.action} user={self.user} context={self.context}"
336
337    class Meta:
338        verbose_name = _("Event")
339        verbose_name_plural = _("Events")
340        indexes = ExpiringModel.Meta.indexes + [
341            models.Index(fields=["action"]),
342            models.Index(fields=["app"]),
343            # Event volume charts count events by time and action. Including the other columns
344            # they read lets Postgres count from the index without reading the events.
345            models.Index(
346                fields=["created"],
347                include=["action", "expires", "expiring"],
348                name="authentik_e_created_cov_idx",
349            ),
350            models.Index(fields=["client_ip"]),
351            # The context keys the API filters by. Few events have them, so the indexes skip
352            # the others: Postgres cannot merge equal jsonb entries, so they would cost one
353            # entry per event. A filter on a key implies it is not null, so these still apply.
354            models.Index(
355                models.F("context__authorized_application__pk"),
356                "created",
357                condition=Q(IsNull(models.F("context__authorized_application__pk"), False)),
358                name="authentik_e_ctx_app_pk_idx",
359            ),
360            models.Index(
361                models.F("context__username"),
362                condition=Q(IsNull(models.F("context__username"), False)),
363                name="authentik_e_ctx_username_idx",
364            ),
365            # Object changelogs filter by model and action. Postgres assumes the two are unrelated
366            # and would combine an index on the model with the much larger action index, so this
367            # index has both. It is not partial: Postgres only keeps statistics for the
368            # expressions of indexes that cover every row.
369            models.Index(
370                models.F("context__model__pk"), "action", name="authentik_e_ctx_model_pk_idx"
371            ),
372            models.Index(
373                models.F("user__pk"),
374                name="authentik_e_user_pk__idx",
375            ),
376            models.Index(models.F("user__username"), name="authentik_e_user_username_idx"),
377        ]

An individual Audit/Metrics/Notification/Error Event

def event_uuid(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def user(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def action(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def app(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def context(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def client_ip(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def created(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def brand(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def expires(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

@staticmethod
def new( action: str | EventAction, app: str | None = None, **kwargs) -> Event:
189    @staticmethod
190    def new(
191        action: str | EventAction,
192        app: str | None = None,
193        **kwargs,
194    ) -> Event:
195        """Create new Event instance from arguments. Instance is NOT saved."""
196        if not isinstance(action, EventAction):
197            action = EventAction.CUSTOM_PREFIX + action
198        if not app:
199            current = currentframe()
200            parent = current.f_back
201            app = app_for_module(parent.f_globals["__name__"])
202        cleaned_kwargs = cleanse_dict(sanitize_dict(kwargs))
203        event = Event(action=action, app=app, context=cleaned_kwargs)
204        return event

Create new Event instance from arguments. Instance is NOT saved.

def with_exception(self, exc: Exception) -> Event:
206    def with_exception(self, exc: Exception) -> Event:
207        """Add data from 'exc' to the event in a database-saveable format"""
208        self.context.setdefault("message", str(exc))
209        self.context["exception"] = exception_to_dict(exc)
210        return self

Add data from 'exc' to the event in a database-saveable format

def set_user(self, user: authentik.core.models.User) -> Event:
212    def set_user(self, user: User) -> Event:
213        """Set `.user` based on user, ensuring the correct attributes are copied.
214        This should only be used when self.from_http is *not* used."""
215        self.user = get_user(user)
216        return self

Set .user based on user, ensuring the correct attributes are copied. This should only be used when self.from_http is not used.

def from_http( self, request: django.http.request.HttpRequest, user: authentik.core.models.User | None = None) -> Event:
218    def from_http(self, request: HttpRequest, user: User | None = None) -> Event:
219        """Add data from a Django-HttpRequest, allowing the creation of
220        Events independently from requests.
221        `user` arguments optionally overrides user from requests."""
222        if request:
223            from authentik.flows.views.executor import QS_QUERY
224
225            self.context["http_request"] = {
226                "path": request.path,
227                "method": request.method,
228                "args": cleanse_dict(QueryDict(request.META.get("QUERY_STRING", ""))),
229                "user_agent": request.META.get("HTTP_USER_AGENT", ""),
230            }
231            if hasattr(request, "request_id"):
232                self.context["http_request"]["request_id"] = request.request_id
233            # Special case for events created during flow execution
234            # since they keep the http query within a wrapped query
235            if QS_QUERY in self.context["http_request"]["args"]:
236                wrapped = self.context["http_request"]["args"][QS_QUERY]
237                self.context["http_request"]["args"] = cleanse_dict(QueryDict(wrapped))
238        if hasattr(request, "brand"):
239            brand: Brand = request.brand
240            self.brand = sanitize_dict(model_to_dict(brand))
241        if user:
242            self.user = get_user(user)
243        elif hasattr(request, "user"):
244            self.user = get_user(request.user)
245        if hasattr(request, "session"):
246            from authentik.flows.views.executor import SESSION_KEY_PLAN
247
248            # Check if we're currently impersonating, and add that user
249            if SESSION_KEY_IMPERSONATE_ORIGINAL_USER in request.session:
250                self.user = get_user(request.session[SESSION_KEY_IMPERSONATE_ORIGINAL_USER])
251                self.user["on_behalf_of"] = get_user(request.session[SESSION_KEY_IMPERSONATE_USER])
252            # Special case for events that happen during a flow, the user might not be authenticated
253            # yet but is a pending user instead
254            if SESSION_KEY_PLAN in request.session:
255                from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlan
256
257                plan: FlowPlan = request.session[SESSION_KEY_PLAN]
258                pending_user = plan.context.get(PLAN_CONTEXT_PENDING_USER, None)
259                # Only save `authenticated_as` if there's a different pending user in the flow
260                # than the user that is authenticated
261                if pending_user and (
262                    (pending_user.pk and pending_user.pk != self.user.get("pk"))
263                    or (not pending_user.pk)
264                ):
265                    orig_user = self.user.copy()
266
267                    self.user = {"authenticated_as": orig_user, **get_user(pending_user)}
268        # User 255.255.255.255 as fallback if IP cannot be determined
269        self.client_ip = ClientIPMiddleware.get_client_ip(request)
270        # Enrich event data
271        for processor in get_context_processors():
272            processor.enrich_event(self)
273        # If there's no app set, we get it from the requests too
274        if not self.app:
275            self.app = Event._get_app_from_request(request)
276        self.save()
277        return self

Add data from a Django-HttpRequest, allowing the creation of Events independently from requests. user arguments optionally overrides user from requests.

@staticmethod
def log_deprecation( identifier: str, message: str, cause: str | None = None, expiry_days=30, **kwargs):
279    @staticmethod
280    def log_deprecation(
281        identifier: str, message: str, cause: str | None = None, expiry_days=30, **kwargs
282    ):
283        query = Q(
284            action=EventAction.CONFIGURATION_WARNING,
285            context__deprecation=identifier,
286        )
287        cause = str(cause)
288        if cause:
289            query &= Q(context__cause=cause)
290        if Event.objects.filter(query).exists():
291            return
292        event = Event.new(
293            EventAction.CONFIGURATION_WARNING,
294            deprecation=identifier,
295            message=message,
296            cause=cause,
297            **kwargs,
298        )
299        event.expires = now() + timedelta(days=expiry_days)
300        event.save()
def save(self, *args, **kwargs):
302    def save(self, *args, **kwargs):
303        if self._state.adding:
304            LOGGER.info(
305                "Created Event",
306                action=self.action,
307                context=self.context,
308                client_ip=self.client_ip,
309                user=self.user,
310            )
311        super().save(*args, **kwargs)

Save the current instance. Override this in a subclass if you want to control the saving process.

The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set.

serializer: type[rest_framework.serializers.Serializer]
313    @property
314    def serializer(self) -> type[Serializer]:
315        from authentik.events.api.events import EventSerializer
316
317        return EventSerializer

Get serializer for this model

summary: str
319    @property
320    def summary(self) -> str:
321        """Return a summary of this event."""
322        if "message" in self.context:
323            return self.context["message"]
324        return f"{self.action}: {self.context}"

Return a summary of this event.

def expiring(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def get_action_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_next_by_created(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_created(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_next_by_expires(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_expires(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

notification_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class Event.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class Event.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class TransportMode(django.db.models.enums.TextChoices):
380class TransportMode(models.TextChoices):
381    """Modes that a notification transport can send a notification"""
382
383    LOCAL = "local", _("authentik inbuilt notifications")
384    WEBHOOK = "webhook", _("Generic Webhook")
385    WEBHOOK_SLACK = "webhook_slack", _("Slack Webhook (Slack/Discord)")
386    EMAIL = "email", _("Email")

Modes that a notification transport can send a notification

WEBHOOK_SLACK = TransportMode.WEBHOOK_SLACK
class NotificationTransport(authentik.tasks.models.TasksModel, authentik.lib.models.SerializerModel):
389class NotificationTransport(TasksModel, SerializerModel):
390    """Action which is executed when a Rule matches"""
391
392    uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
393
394    name = models.TextField(unique=True)
395    mode = models.TextField(choices=TransportMode.choices, default=TransportMode.LOCAL)
396    send_once = models.BooleanField(
397        default=False,
398        help_text=_(
399            "Only send notification once, for example when sending a webhook into a chat channel."
400        ),
401    )
402
403    email_subject_prefix = models.TextField(default="authentik Notification: ", blank=True)
404    email_template = models.TextField(default=EmailTemplates.EVENT_NOTIFICATION)
405
406    webhook_url = models.TextField(blank=True, validators=[DomainlessURLValidator()])
407    webhook_ca = models.ForeignKey(
408        CertificateKeyPair,
409        null=True,
410        default=None,
411        on_delete=models.SET_DEFAULT,
412        help_text=_(
413            "When set, the selected certificate is used to "
414            "validate the certificate of the webhook server."
415        ),
416    )
417    webhook_mapping_body = models.ForeignKey(
418        "NotificationWebhookMapping",
419        on_delete=models.SET_DEFAULT,
420        null=True,
421        default=None,
422        related_name="+",
423        help_text=_(
424            "Customize the body of the request. "
425            "Mapping should return data that is JSON-serializable."
426        ),
427    )
428    webhook_mapping_headers = models.ForeignKey(
429        "NotificationWebhookMapping",
430        on_delete=models.SET_DEFAULT,
431        null=True,
432        default=None,
433        related_name="+",
434        help_text=_(
435            "Configure additional headers to be sent. "
436            "Mapping should return a dictionary of key-value pairs"
437        ),
438    )
439
440    def send(self, notification: Notification) -> list[str]:
441        """Send notification to user, called from async task"""
442        if self.mode == TransportMode.LOCAL:
443            return self.send_local(notification)
444        if self.mode == TransportMode.WEBHOOK:
445            return self.send_webhook(notification)
446        if self.mode == TransportMode.WEBHOOK_SLACK:
447            return self.send_webhook_slack(notification)
448        if self.mode == TransportMode.EMAIL:
449            return self.send_email(notification)
450        raise ValueError(f"Invalid mode {self.mode} set")
451
452    def send_local(self, notification: Notification) -> list[str]:
453        """Local notification delivery"""
454        if self.webhook_mapping_body:
455            self.webhook_mapping_body.evaluate(
456                user=notification.user,
457                request=None,
458                notification=notification,
459            )
460        notification.save()
461        layer = get_channel_layer()
462        layer.group_send_blocking(
463            build_user_group(notification.user),
464            {
465                "type": "event.notification",
466                "id": str(notification.pk),
467                "data": notification.serializer(notification).data,
468            },
469        )
470        return []
471
472    def send_webhook(self, notification: Notification) -> list[str]:
473        """Send notification to generic webhook"""
474        default_body = {
475            "body": notification.body,
476            "severity": notification.severity,
477            "user_email": notification.user.email,
478            "user_username": notification.user.username,
479        }
480        if notification.event and notification.event.user:
481            default_body["event_user_email"] = notification.event.user.get("email", None)
482            default_body["event_user_username"] = notification.event.user.get("username", None)
483        headers = {}
484        if self.webhook_mapping_body:
485            default_body = sanitize_item(
486                self.webhook_mapping_body.evaluate(
487                    user=notification.user,
488                    request=None,
489                    notification=notification,
490                )
491            )
492        if self.webhook_mapping_headers:
493            headers = sanitize_item(
494                self.webhook_mapping_headers.evaluate(
495                    user=notification.user,
496                    request=None,
497                    notification=notification,
498                )
499            )
500
501        def send(**kwargs):
502            try:
503                response = get_http_session().post(
504                    self.webhook_url,
505                    json=default_body,
506                    headers=headers,
507                    allow_redirects=False,
508                    **kwargs,
509                )
510                response.raise_for_status()
511            except RequestException as exc:
512                raise NotificationTransportError(
513                    exc.response.text if exc.response is not None else str(exc)
514                ) from exc
515            return [
516                response.status_code,
517            ]
518
519        if self.webhook_ca:
520            # Imports the docker client, only load it when a custom CA is set
521            from authentik.outposts.docker_tls import DockerInlineTLS
522
523            with DockerInlineTLS(self.webhook_ca, authentication_kp=None) as tls:
524                return send(verify=tls.ca_cert)
525        return send()
526
527    def send_webhook_slack(self, notification: Notification) -> list[str]:
528        """Send notification to slack or slack-compatible endpoints"""
529        fields = [
530            {
531                "title": str(_("Severity")),
532                "value": notification.severity,
533                "short": True,
534            },
535            {
536                "title": str(_("Dispatched for user")),
537                "value": str(notification.user),
538                "short": True,
539            },
540        ]
541        if notification.event:
542            if notification.event.user:
543                fields.append(
544                    {
545                        "title": str(_("Event user")),
546                        "value": str(notification.event.user.get("username")),
547                        "short": True,
548                    },
549                )
550            for key, value in notification.event.context.items():
551                if not isinstance(value, str):
552                    continue
553                # https://birdie0.github.io/discord-webhooks-guide/other/field_limits.html
554                if len(fields) >= DISCORD_FIELD_LIMIT:
555                    continue
556                fields.append({"title": key[:256], "value": value[:1024]})
557        body = {
558            "username": "authentik",
559            "icon_url": "https://goauthentik.io/img/icon.png",
560            "attachments": [
561                {
562                    "author_name": "authentik",
563                    "author_link": "https://goauthentik.io",
564                    "author_icon": "https://goauthentik.io/img/icon.png",
565                    "title": notification.body,
566                    "color": "#fd4b2d",
567                    "fields": fields,
568                    "footer": f"authentik {authentik_full_version()}",
569                }
570            ],
571        }
572        if notification.event:
573            body["attachments"][0]["title"] = notification.event.action
574        headers = {}
575        if self.webhook_mapping_body:
576            body = sanitize_item(
577                self.webhook_mapping_body.evaluate(
578                    user=notification.user,
579                    request=None,
580                    notification=notification,
581                    original_body=body,
582                )
583            )
584        if self.webhook_mapping_headers:
585            headers = sanitize_item(
586                self.webhook_mapping_headers.evaluate(
587                    user=notification.user,
588                    request=None,
589                    notification=notification,
590                )
591            )
592        try:
593            response = get_http_session().post(
594                self.webhook_url,
595                json=body,
596                headers=headers,
597                allow_redirects=False,
598            )
599            response.raise_for_status()
600        except RequestException as exc:
601            text = exc.response.text if exc.response is not None else str(exc)
602            raise NotificationTransportError(text) from exc
603        return [
604            response.status_code,
605        ]
606
607    def send_email(self, notification: Notification) -> list[str]:
608        """Send notification via global email configuration"""
609        from authentik.stages.email.tasks import send_mail
610
611        if notification.user.email.strip() == "":
612            LOGGER.info(
613                "Discarding notification as user has no email address",
614                user=notification.user,
615                notification=notification,
616            )
617            return None
618        context = {
619            "key_value": {
620                "user_email": notification.user.email,
621                "user_username": notification.user.username,
622            },
623            "body": notification.body,
624            "title": "",
625        }
626        if notification.event and notification.event.user:
627            context["key_value"]["event_user_email"] = notification.event.user.get("email", None)
628            context["key_value"]["event_user_username"] = notification.event.user.get(
629                "username", None
630            )
631        if notification.hyperlink:
632            context["link"] = {
633                "target": notification.hyperlink,
634                "label": notification.hyperlink_label,
635            }
636        if notification.event:
637            context["title"] += notification.event.action
638            for key, value in notification.event.context.items():
639                if not isinstance(value, str):
640                    continue
641                context["key_value"][key] = value
642        else:
643            context["title"] += notification.body[:NOTIFICATION_SUMMARY_LENGTH]
644        # TODO: improve permission check
645        if notification.user.is_superuser:
646            context["source"] = {
647                "from": self.name,
648            }
649        mail = TemplateEmailMessage(
650            subject=self.email_subject_prefix + context["title"],
651            to=[(notification.user.name, notification.user.email)],
652            language=notification.user.locale(),
653            template_name=self.email_template,
654            template_context=context,
655        )
656        send_mail.send_with_options(args=(mail.__dict__,), rel_obj=self)
657        return []
658
659    @property
660    def serializer(self) -> type[Serializer]:
661        from authentik.events.api.notification_transports import (
662            NotificationTransportSerializer,
663        )
664
665        return NotificationTransportSerializer
666
667    def __str__(self) -> str:
668        return f"Notification Transport {self.name}"
669
670    class Meta:
671        verbose_name = _("Notification Transport")
672        verbose_name_plural = _("Notification Transports")

Action which is executed when a Rule matches

def uuid(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def name(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def mode(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def send_once(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def email_subject_prefix(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def email_template(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def webhook_url(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

webhook_ca

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

webhook_mapping_body

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

webhook_mapping_headers

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def send(self, notification: Notification) -> list[str]:
440    def send(self, notification: Notification) -> list[str]:
441        """Send notification to user, called from async task"""
442        if self.mode == TransportMode.LOCAL:
443            return self.send_local(notification)
444        if self.mode == TransportMode.WEBHOOK:
445            return self.send_webhook(notification)
446        if self.mode == TransportMode.WEBHOOK_SLACK:
447            return self.send_webhook_slack(notification)
448        if self.mode == TransportMode.EMAIL:
449            return self.send_email(notification)
450        raise ValueError(f"Invalid mode {self.mode} set")

Send notification to user, called from async task

def send_local(self, notification: Notification) -> list[str]:
452    def send_local(self, notification: Notification) -> list[str]:
453        """Local notification delivery"""
454        if self.webhook_mapping_body:
455            self.webhook_mapping_body.evaluate(
456                user=notification.user,
457                request=None,
458                notification=notification,
459            )
460        notification.save()
461        layer = get_channel_layer()
462        layer.group_send_blocking(
463            build_user_group(notification.user),
464            {
465                "type": "event.notification",
466                "id": str(notification.pk),
467                "data": notification.serializer(notification).data,
468            },
469        )
470        return []

Local notification delivery

def send_webhook(self, notification: Notification) -> list[str]:
472    def send_webhook(self, notification: Notification) -> list[str]:
473        """Send notification to generic webhook"""
474        default_body = {
475            "body": notification.body,
476            "severity": notification.severity,
477            "user_email": notification.user.email,
478            "user_username": notification.user.username,
479        }
480        if notification.event and notification.event.user:
481            default_body["event_user_email"] = notification.event.user.get("email", None)
482            default_body["event_user_username"] = notification.event.user.get("username", None)
483        headers = {}
484        if self.webhook_mapping_body:
485            default_body = sanitize_item(
486                self.webhook_mapping_body.evaluate(
487                    user=notification.user,
488                    request=None,
489                    notification=notification,
490                )
491            )
492        if self.webhook_mapping_headers:
493            headers = sanitize_item(
494                self.webhook_mapping_headers.evaluate(
495                    user=notification.user,
496                    request=None,
497                    notification=notification,
498                )
499            )
500
501        def send(**kwargs):
502            try:
503                response = get_http_session().post(
504                    self.webhook_url,
505                    json=default_body,
506                    headers=headers,
507                    allow_redirects=False,
508                    **kwargs,
509                )
510                response.raise_for_status()
511            except RequestException as exc:
512                raise NotificationTransportError(
513                    exc.response.text if exc.response is not None else str(exc)
514                ) from exc
515            return [
516                response.status_code,
517            ]
518
519        if self.webhook_ca:
520            # Imports the docker client, only load it when a custom CA is set
521            from authentik.outposts.docker_tls import DockerInlineTLS
522
523            with DockerInlineTLS(self.webhook_ca, authentication_kp=None) as tls:
524                return send(verify=tls.ca_cert)
525        return send()

Send notification to generic webhook

def send_webhook_slack(self, notification: Notification) -> list[str]:
527    def send_webhook_slack(self, notification: Notification) -> list[str]:
528        """Send notification to slack or slack-compatible endpoints"""
529        fields = [
530            {
531                "title": str(_("Severity")),
532                "value": notification.severity,
533                "short": True,
534            },
535            {
536                "title": str(_("Dispatched for user")),
537                "value": str(notification.user),
538                "short": True,
539            },
540        ]
541        if notification.event:
542            if notification.event.user:
543                fields.append(
544                    {
545                        "title": str(_("Event user")),
546                        "value": str(notification.event.user.get("username")),
547                        "short": True,
548                    },
549                )
550            for key, value in notification.event.context.items():
551                if not isinstance(value, str):
552                    continue
553                # https://birdie0.github.io/discord-webhooks-guide/other/field_limits.html
554                if len(fields) >= DISCORD_FIELD_LIMIT:
555                    continue
556                fields.append({"title": key[:256], "value": value[:1024]})
557        body = {
558            "username": "authentik",
559            "icon_url": "https://goauthentik.io/img/icon.png",
560            "attachments": [
561                {
562                    "author_name": "authentik",
563                    "author_link": "https://goauthentik.io",
564                    "author_icon": "https://goauthentik.io/img/icon.png",
565                    "title": notification.body,
566                    "color": "#fd4b2d",
567                    "fields": fields,
568                    "footer": f"authentik {authentik_full_version()}",
569                }
570            ],
571        }
572        if notification.event:
573            body["attachments"][0]["title"] = notification.event.action
574        headers = {}
575        if self.webhook_mapping_body:
576            body = sanitize_item(
577                self.webhook_mapping_body.evaluate(
578                    user=notification.user,
579                    request=None,
580                    notification=notification,
581                    original_body=body,
582                )
583            )
584        if self.webhook_mapping_headers:
585            headers = sanitize_item(
586                self.webhook_mapping_headers.evaluate(
587                    user=notification.user,
588                    request=None,
589                    notification=notification,
590                )
591            )
592        try:
593            response = get_http_session().post(
594                self.webhook_url,
595                json=body,
596                headers=headers,
597                allow_redirects=False,
598            )
599            response.raise_for_status()
600        except RequestException as exc:
601            text = exc.response.text if exc.response is not None else str(exc)
602            raise NotificationTransportError(text) from exc
603        return [
604            response.status_code,
605        ]

Send notification to slack or slack-compatible endpoints

def send_email(self, notification: Notification) -> list[str]:
607    def send_email(self, notification: Notification) -> list[str]:
608        """Send notification via global email configuration"""
609        from authentik.stages.email.tasks import send_mail
610
611        if notification.user.email.strip() == "":
612            LOGGER.info(
613                "Discarding notification as user has no email address",
614                user=notification.user,
615                notification=notification,
616            )
617            return None
618        context = {
619            "key_value": {
620                "user_email": notification.user.email,
621                "user_username": notification.user.username,
622            },
623            "body": notification.body,
624            "title": "",
625        }
626        if notification.event and notification.event.user:
627            context["key_value"]["event_user_email"] = notification.event.user.get("email", None)
628            context["key_value"]["event_user_username"] = notification.event.user.get(
629                "username", None
630            )
631        if notification.hyperlink:
632            context["link"] = {
633                "target": notification.hyperlink,
634                "label": notification.hyperlink_label,
635            }
636        if notification.event:
637            context["title"] += notification.event.action
638            for key, value in notification.event.context.items():
639                if not isinstance(value, str):
640                    continue
641                context["key_value"][key] = value
642        else:
643            context["title"] += notification.body[:NOTIFICATION_SUMMARY_LENGTH]
644        # TODO: improve permission check
645        if notification.user.is_superuser:
646            context["source"] = {
647                "from": self.name,
648            }
649        mail = TemplateEmailMessage(
650            subject=self.email_subject_prefix + context["title"],
651            to=[(notification.user.name, notification.user.email)],
652            language=notification.user.locale(),
653            template_name=self.email_template,
654            template_context=context,
655        )
656        send_mail.send_with_options(args=(mail.__dict__,), rel_obj=self)
657        return []

Send notification via global email configuration

serializer: type[rest_framework.serializers.Serializer]
659    @property
660    def serializer(self) -> type[Serializer]:
661        from authentik.events.api.notification_transports import (
662            NotificationTransportSerializer,
663        )
664
665        return NotificationTransportSerializer

Get serializer for this model

tasks

Accessor to the related objects manager on the one-to-many relation created by GenericRelation.

In the example::

class Post(Model):
    comments = GenericRelation(Comment)

post.comments is a ReverseGenericManyToOneDescriptor instance.

def get_mode_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

webhook_ca_id
webhook_mapping_body_id
webhook_mapping_headers_id
def objects(unknown):

The type of the None singleton.

notificationrule_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

notificationrulenotificationtransport_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

lifecyclerule_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

lifecyclerulenotificationtransport_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

userexpirationrule_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

userexpirationrulenotificationtransport_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

requestrule_set

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

requestrulenotificationtransport_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class NotificationTransport.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class NotificationTransport.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class NotificationSeverity(django.db.models.enums.TextChoices):
675class NotificationSeverity(models.TextChoices):
676    """Severity images that a notification can have"""
677
678    NOTICE = "notice", _("Notice")
679    WARNING = "warning", _("Warning")
680    ALERT = "alert", _("Alert")

Severity images that a notification can have

class Notification(authentik.lib.models.SerializerModel):
683class Notification(SerializerModel):
684    """Event Notification"""
685
686    uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
687    severity = models.TextField(choices=NotificationSeverity.choices)
688    body = models.TextField()
689    hyperlink = models.TextField(blank=True, null=True, max_length=4096)
690    hyperlink_label = models.TextField(blank=True, null=True)
691    created = models.DateTimeField(auto_now_add=True)
692    event = models.ForeignKey(Event, on_delete=models.SET_NULL, null=True, blank=True)
693    seen = models.BooleanField(default=False)
694    user = models.ForeignKey(User, on_delete=models.CASCADE)
695
696    @property
697    def serializer(self) -> type[Serializer]:
698        from authentik.events.api.notifications import NotificationSerializer
699
700        return NotificationSerializer
701
702    def __str__(self) -> str:
703        body_trunc = (
704            (self.body[:NOTIFICATION_SUMMARY_LENGTH] + "..")
705            if len(self.body) > NOTIFICATION_SUMMARY_LENGTH
706            else self.body
707        )
708        return f"Notification for user {self.user_id}: {body_trunc}"
709
710    class Meta:
711        verbose_name = _("Notification")
712        verbose_name_plural = _("Notifications")
713        indexes = [
714            # The notification drawer lists a user's unseen notifications, newest first
715            models.Index(
716                fields=["user", "created"],
717                condition=Q(seen=False),
718                name="authentik_e_notif_unseen_idx",
719            ),
720        ]

Event Notification

def uuid(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def severity(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def body(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def created(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

event

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def seen(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

user

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

serializer: type[rest_framework.serializers.Serializer]
696    @property
697    def serializer(self) -> type[Serializer]:
698        from authentik.events.api.notifications import NotificationSerializer
699
700        return NotificationSerializer

Get serializer for this model

def get_severity_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_next_by_created(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_created(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

event_id
user_id
def objects(unknown):

The type of the None singleton.

class Notification.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class Notification.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

723class NotificationRule(TasksModel, SerializerModel, PolicyBindingModel):
724    """Decide when to create a Notification based on policies attached to this object."""
725
726    name = models.TextField(unique=True)
727    transports = models.ManyToManyField(
728        NotificationTransport,
729        help_text=_(
730            "Select which transports should be used to notify the user. Select a transport "
731            "in Local mode to show the notification in the authentik UI. If none are selected, "
732            "no notification is created."
733        ),
734        blank=True,
735        through="NotificationRuleNotificationTransport",
736    )
737    severity = models.TextField(
738        choices=NotificationSeverity.choices,
739        default=NotificationSeverity.NOTICE,
740        help_text=_("Controls which severity level the created notifications will have."),
741    )
742    destination_group = models.ForeignKey(
743        Group,
744        help_text=_(
745            "Define which group of users this notification should be sent and shown to. "
746            "If left empty, Notification won't ben sent."
747        ),
748        null=True,
749        blank=True,
750        on_delete=models.SET_NULL,
751    )
752    destination_event_user = models.BooleanField(
753        default=False,
754        help_text=_(
755            "When enabled, notification will be sent to user the user that triggered the event."
756            "When destination_group is configured, notification is sent to both."
757        ),
758    )
759
760    def destination_users(self, event: Event) -> Generator[User, Any]:
761        if self.destination_event_user and event.user.get("pk"):
762            yield User(pk=event.user.get("pk"))
763        if self.destination_group:
764            yield from self.destination_group.users.all()
765
766    @property
767    def serializer(self) -> type[Serializer]:
768        from authentik.events.api.notification_rules import NotificationRuleSerializer
769
770        return NotificationRuleSerializer
771
772    def __str__(self) -> str:
773        return f"Notification Rule {self.name}"
774
775    class Meta:
776        verbose_name = _("Notification Rule")
777        verbose_name_plural = _("Notification Rules")

Decide when to create a Notification based on policies attached to this object.

def name(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

transports

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

def severity(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

destination_group

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def destination_event_user(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def destination_users( self, event: Event) -> Generator[authentik.core.models.User, typing.Any]:
760    def destination_users(self, event: Event) -> Generator[User, Any]:
761        if self.destination_event_user and event.user.get("pk"):
762            yield User(pk=event.user.get("pk"))
763        if self.destination_group:
764            yield from self.destination_group.users.all()
serializer: type[rest_framework.serializers.Serializer]
766    @property
767    def serializer(self) -> type[Serializer]:
768        from authentik.events.api.notification_rules import NotificationRuleSerializer
769
770        return NotificationRuleSerializer

Get serializer for this model

tasks

Accessor to the related objects manager on the one-to-many relation created by GenericRelation.

In the example::

class Post(Model):
    comments = GenericRelation(Comment)

post.comments is a ReverseGenericManyToOneDescriptor instance.

def get_severity_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

destination_group_id
policybindingmodel_ptr_id
policybindingmodel_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

notificationrulenotificationtransport_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class NotificationRule.DoesNotExist(authentik.policies.models.PolicyBindingModel.DoesNotExist):

The requested object does not exist

class NotificationRule.MultipleObjectsReturned(authentik.policies.models.PolicyBindingModel.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class NotificationRuleNotificationTransport(authentik.lib.models.SimpleThroughModel):
780class NotificationRuleNotificationTransport(SimpleThroughModel):
781    notification_rule = models.ForeignKey(
782        NotificationRule, on_delete=models.CASCADE, db_column="notificationrule_id"
783    )
784    notification_transport = models.ForeignKey(
785        NotificationTransport,
786        on_delete=models.CASCADE,
787        db_column="notificationtransport_id",
788    )
789
790    class Meta:
791        db_table = "authentik_events_notificationrule_transports"
792        unique_together = (("notification_rule", "notification_transport"),)
793        verbose_name = _("Notification Rule Notification Transport")
794        verbose_name_plural = _("Notification Rule Notification Transports")
795
796    def __str__(self):
797        return (
798            "NotificationRuleNotificationTransport for NotificationRule "
799            f"{self.notification_rule_id} "
800            f"and NotificationTransport {self.notification_transport_id}."
801        )

NotificationRuleNotificationTransport(id, notification_rule, notification_transport)

notification_rule

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

notification_transport

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

notification_rule_id
notification_transport_id
def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def objects(unknown):

The type of the None singleton.

class NotificationRuleNotificationTransport.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class NotificationRuleNotificationTransport.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class NotificationWebhookMapping(authentik.core.models.PropertyMapping):
804class NotificationWebhookMapping(PropertyMapping):
805    """Modify the payload of outgoing webhook requests"""
806
807    @property
808    def component(self) -> str:
809        return "ak-property-mapping-notification-form"
810
811    @property
812    def serializer(self) -> type[type[Serializer]]:
813        from authentik.events.api.notification_mappings import (
814            NotificationWebhookMappingSerializer,
815        )
816
817        return NotificationWebhookMappingSerializer
818
819    def __str__(self):
820        return f"Webhook Mapping {self.name}"
821
822    class Meta:
823        verbose_name = _("Webhook Mapping")
824        verbose_name_plural = _("Webhook Mappings")

Modify the payload of outgoing webhook requests

component: str
807    @property
808    def component(self) -> str:
809        return "ak-property-mapping-notification-form"

Return component used to edit this object

serializer: type[type[rest_framework.serializers.Serializer]]
811    @property
812    def serializer(self) -> type[type[Serializer]]:
813        from authentik.events.api.notification_mappings import (
814            NotificationWebhookMappingSerializer,
815        )
816
817        return NotificationWebhookMappingSerializer

Get serializer for this model

propertymapping_ptr_id
propertymapping_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

authenticatorsmsstage_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class NotificationWebhookMapping.DoesNotExist(authentik.core.models.PropertyMapping.DoesNotExist):

The requested object does not exist

class NotificationWebhookMapping.MultipleObjectsReturned(authentik.core.models.PropertyMapping.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.