authentik.providers.saml.tasks

SAML Provider tasks

  1"""SAML Provider tasks"""
  2
  3import requests
  4from django.contrib.auth import get_user_model
  5from dramatiq.actor import actor
  6from structlog.stdlib import get_logger
  7
  8from authentik.common.saml.parsers.logout_request import LogoutRequest
  9from authentik.events.models import Event, EventAction
 10from authentik.providers.saml.models import SAMLProvider
 11from authentik.providers.saml.processors.logout_request import LogoutRequestProcessor
 12from authentik.providers.saml.processors.logout_response_processor import LogoutResponseProcessor
 13
 14LOGGER = get_logger()
 15User = get_user_model()
 16
 17
 18@actor(description="Send SAML LogoutRequest to a Service Provider")
 19def send_saml_logout_request(
 20    provider_pk: int,
 21    sls_url: str,
 22    name_id: str,
 23    name_id_format: str,
 24    session_index: str,
 25    issuer: str,
 26):
 27    """Send SAML LogoutRequest to a Service Provider using session data"""
 28    provider = SAMLProvider.objects.filter(pk=provider_pk).first()
 29    if not provider:
 30        LOGGER.error(
 31            "Provider not found for SAML logout request",
 32            provider_pk=provider_pk,
 33            session_index=session_index,
 34        )
 35        return False
 36
 37    LOGGER.debug(
 38        "Sending SAML logout request",
 39        provider=provider.name,
 40        session_index=session_index,
 41    )
 42
 43    # Note: We don't need the user object for the logout request itself
 44    processor = LogoutRequestProcessor(
 45        provider=provider,
 46        user=None,
 47        destination=sls_url,
 48        name_id=name_id,
 49        name_id_format=name_id_format,
 50        session_index=session_index,
 51        issuer=issuer,
 52    )
 53
 54    return send_post_logout_request(provider, processor)
 55
 56
 57def send_post_logout_request(provider: SAMLProvider, processor: LogoutRequestProcessor) -> bool:
 58    """Send LogoutRequest using POST binding"""
 59    encoded_request = processor.encode_post()
 60
 61    form_data = {
 62        "SAMLRequest": encoded_request,
 63    }
 64
 65    if processor.relay_state:
 66        form_data["RelayState"] = processor.relay_state
 67
 68    response = requests.post(
 69        provider.sls_url,
 70        data=form_data,
 71        timeout=10,
 72        headers={
 73            "Content-Type": "application/x-www-form-urlencoded",
 74        },
 75        allow_redirects=True,
 76    )
 77    response.raise_for_status()
 78
 79    LOGGER.debug(
 80        "Sent POST logout request",
 81        provider=provider,
 82        status_code=response.status_code,
 83    )
 84
 85    return True
 86
 87
 88@actor(description="Send SAML LogoutResponse to a Service Provider (backchannel)")
 89def send_saml_logout_response(
 90    provider_pk: int,
 91    sls_url: str,
 92    logout_request_id: str | None = None,
 93    relay_state: str | None = None,
 94    issuer: str | None = None,
 95):
 96    """Send SAML LogoutResponse to a Service Provider using backchannel (server-to-server)"""
 97    provider = SAMLProvider.objects.filter(pk=provider_pk).first()
 98    if not provider:
 99        LOGGER.error(
100            "Provider not found for SAML logout response",
101            provider_pk=provider_pk,
102        )
103        return False
104
105    LOGGER.debug(
106        "Sending backchannel SAML logout response",
107        provider=provider.name,
108        sls_url=sls_url,
109    )
110
111    # Create a minimal LogoutRequest object for the response processor
112    # We only need the ID and relay_state for building the response
113    logout_request = None
114    if logout_request_id:
115        logout_request = LogoutRequest()
116        logout_request.id = logout_request_id
117        logout_request.relay_state = relay_state
118
119    # Build the logout response
120    processor = LogoutResponseProcessor(
121        provider=provider,
122        logout_request=logout_request,
123        destination=sls_url,
124        relay_state=relay_state,
125        issuer=issuer,
126    )
127
128    encoded_response = processor.encode_post()
129
130    form_data = {
131        "SAMLResponse": encoded_response,
132    }
133
134    if relay_state:
135        form_data["RelayState"] = relay_state
136
137    # Send the logout response to the SP
138    try:
139        response = requests.post(
140            sls_url,
141            data=form_data,
142            timeout=10,
143            headers={
144                "Content-Type": "application/x-www-form-urlencoded",
145            },
146            allow_redirects=True,
147        )
148        response.raise_for_status()
149
150        LOGGER.info(
151            "Successfully sent backchannel logout response to SP",
152            provider=provider.name,
153            sls_url=sls_url,
154            status_code=response.status_code,
155        )
156        return True
157
158    except requests.exceptions.RequestException as exc:
159        LOGGER.warning(
160            "Failed to send backchannel logout response to SP",
161            provider=provider.name,
162            sls_url=sls_url,
163            error=str(exc),
164        )
165        Event.new(
166            EventAction.CONFIGURATION_ERROR,
167            provider=provider,
168            message=f"Backchannel logout response failed: {str(exc)}",
169        ).save()
170        return False
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
class User(authentik.lib.models.SerializerModel, authentik.core.models.AttributesMixin, django.contrib.auth.models.AbstractUser):
392class User(SerializerModel, AttributesMixin, AbstractUser):
393    """authentik User model, based on django's contrib auth user model."""
394
395    # Overwriting PermissionsMixin: permissions are handled by roles.
396    # (This knowingly violates the Liskov substitution principle. It is better to fail loudly.)
397    user_permissions = None
398
399    uuid = models.UUIDField(default=uuid4, editable=False, unique=True)
400    name = models.TextField(help_text=_("User's display name."))
401    path = models.TextField(default="users")
402    type = models.TextField(choices=UserTypes.choices, default=UserTypes.INTERNAL)
403
404    sources = models.ManyToManyField("Source", through="UserSourceConnection")
405    groups = models.ManyToManyField("Group", related_name="users", through="UserGroup")
406    roles = models.ManyToManyField(
407        "authentik_rbac.Role", related_name="users", blank=True, through="UserRole"
408    )
409
410    last_updated = models.DateTimeField(auto_now=True)
411
412    objects = UserManager()
413
414    class Meta:
415        verbose_name = _("User")
416        verbose_name_plural = _("Users")
417        permissions = [
418            ("reset_user_password", _("Reset Password")),
419            ("impersonate", _("Can impersonate other users")),
420            ("preview_user", _("Can preview user data sent to providers")),
421            ("view_user_applications", _("View applications the user has access to")),
422        ]
423        indexes = [
424            models.Index(fields=["last_login"]),
425            models.Index(fields=["uuid"]),
426            models.Index(fields=["path"]),
427            models.Index(fields=["type"]),
428            models.Index(fields=["date_joined"]),
429            models.Index(fields=["last_updated"]),
430            models.Index(fields=["username", "is_active", "type"]),
431            models.Index(Upper("email"), name="%(app_label)s_%(class)s_email_idx"),
432        ]
433
434    def __str__(self):
435        return self.username
436
437    @staticmethod
438    def default_path() -> str:
439        """Get the default user path"""
440        return User._meta.get_field("path").default
441
442    def all_groups(self) -> QuerySet[Group]:
443        """Recursively get all groups this user is a member of."""
444        return self.groups.all().with_ancestors()
445
446    def all_roles(self) -> QuerySet[Role]:
447        """Get all roles of this user and all of its groups (recursively)."""
448        return Role.objects.filter(Q(users=self) | Q(groups__in=self.all_groups())).distinct()
449
450    def get_managed_role(self, create=False):
451        if create:
452            name = managed_role_name(self)
453            role, created = Role.objects.get_or_create(name=name, managed=name)
454            if created:
455                role.users.add(self)
456            return role
457        else:
458            return Role.objects.filter(name=managed_role_name(self)).first()
459
460    def get_all_model_perms_on_managed_role(self) -> QuerySet[RoleModelPermission]:
461        role = self.get_managed_role()
462        if not role:
463            return RoleModelPermission.objects.none()
464        return RoleModelPermission.objects.filter(role=role)
465
466    def get_all_obj_perms_on_managed_role(self) -> QuerySet[RoleObjectPermission]:
467        role = self.get_managed_role()
468        if not role:
469            return RoleObjectPermission.objects.none()
470        return RoleObjectPermission.objects.filter(role=role)
471
472    def assign_perms_to_managed_role(
473        self,
474        perms: str | list[str] | Permission | list[Permission],
475        obj: models.Model | None = None,
476    ):
477        if not perms:
478            return
479        role = self.get_managed_role(create=True)
480        role.assign_perms(perms, obj)
481
482    def remove_perms_from_managed_role(
483        self,
484        perms: str | list[str] | Permission | list[Permission],
485        obj: models.Model | None = None,
486    ):
487        role = self.get_managed_role()
488        if not role:
489            return None
490        role.remove_perms(perms, obj)
491
492    def remove_all_perms_from_managed_role(self):
493        role = self.get_managed_role()
494        if not role:
495            return None
496        RoleModelPermission.objects.filter(role=role).delete()
497        RoleObjectPermission.objects.filter(role=role).delete()
498
499    def group_attributes(self, request: HttpRequest | None = None) -> dict[str, Any]:
500        """Get a dictionary containing the attributes from all groups the user belongs to,
501        including the users attributes"""
502        final_attributes = {}
503        if request and hasattr(request, "brand"):
504            always_merger.merge(final_attributes, request.brand.attributes)
505        for group in self.all_groups().order_by("name"):
506            always_merger.merge(final_attributes, group.attributes)
507        always_merger.merge(final_attributes, self.attributes)
508        return final_attributes
509
510    def app_entitlements(self, app: Application | None) -> QuerySet[ApplicationEntitlement]:
511        """Get all entitlements this user has for `app`."""
512        if not app:
513            return ApplicationEntitlement.objects.none()
514        return self.all_app_entitlements().filter(app=app)
515
516    def all_app_entitlements(self) -> QuerySet[ApplicationEntitlement]:
517        """Get all entitlements this user is assigned, regardless of access to the application."""
518        all_groups = self.all_groups()
519        return (
520            ApplicationEntitlement.objects.filter(
521                Q(
522                    Q(bindings__user=self) | Q(bindings__group__in=all_groups),
523                    bindings__negate=False,
524                )
525                | Q(
526                    Q(~Q(bindings__user=self), bindings__user__isnull=False)
527                    | Q(~Q(bindings__group__in=all_groups), bindings__group__isnull=False),
528                    bindings__negate=True,
529                ),
530                bindings__enabled=True,
531            )
532            .distinct()
533            .order_by("name")
534        )
535
536    def app_entitlements_attributes(self, app: Application | None) -> dict:
537        """Get a dictionary containing all merged attributes from app entitlements for `app`."""
538        final_attributes = {}
539        for attrs in self.app_entitlements(app).values_list("attributes", flat=True):
540            always_merger.merge(final_attributes, attrs)
541        return final_attributes
542
543    @property
544    def serializer(self) -> Serializer:
545        from authentik.core.api.users import UserSerializer
546
547        return UserSerializer
548
549    @cached_property
550    def is_superuser(self) -> bool:
551        """Get supseruser status based on membership in a group with superuser status"""
552        return self.all_groups().filter(is_superuser=True).exists()
553
554    @property
555    def is_staff(self) -> bool:
556        """superuser == staff user"""
557        return self.is_superuser  # type: ignore
558
559    # TODO: remove this after 2026.
560    @property
561    def ak_groups(self):
562        """This is a proxy for a renamed, deprecated field."""
563        from authentik.events.models import Event
564
565        deprecation = "authentik.core.models.User.ak_groups"
566        replacement = "authentik.core.models.User.groups"
567        message_logger = (
568            f"{deprecation} is deprecated and will be removed in a future version of "
569            f"authentik. Please use {replacement} instead."
570        )
571        message_event = (
572            f"{message_logger} This event will not be repeated until it expires (by "
573            "default: in 30 days). See authentik logs for every will invocation of this "
574            "deprecation."
575        )
576        stacktrace = traceback.format_stack()
577        # The last line is this function, the next-to-last line is its caller
578        cause = stacktrace[-2] if len(stacktrace) > 1 else "Unknown, see stacktrace in logs"
579        if search := re.search(r'"(.*?)"', cause):
580            cause = f"Property mapping or Expression policy named {search.group(1)}"
581
582        LOGGER.warning(
583            "deprecation used",
584            message=message_logger,
585            deprecation=deprecation,
586            replacement=replacement,
587            cause=cause,
588            stacktrace=stacktrace,
589        )
590        Event.log_deprecation(
591            deprecation, message=message_event, cause=cause, replacement=replacement
592        )
593        return self.groups
594
595    # Passwords are written through authentik.stages.password.models.PasswordDevice.
596    # These read-only properties keep `user.password` and `user.password_change_date`
597    # working in expressions, Django's session hash and the user API.
598    @property
599    def password(self) -> str:
600        device = getattr(self, "password_device", None)
601        return device.password if device else UNUSABLE_PASSWORD_PREFIX
602
603    @property
604    def password_change_date(self) -> datetime:
605        device = getattr(self, "password_device", None)
606        return device.password_change_date if device else self.date_joined
607
608    def check_password(self, raw_password: str) -> bool:
609        # Django's version writes `password` when it upgrades an outdated hash.
610        device = getattr(self, "password_device", None)
611        return device.check_password(raw_password) if device else False
612
613    async def acheck_password(self, raw_password: str) -> bool:
614        return await sync_to_async(self.check_password)(raw_password)
615
616    # Django's password writes would assign the read-only `password`; fail loudly instead.
617    def set_password(self, raw_password):
618        raise NotImplementedError("Use PasswordDevice.set_password()")
619
620    def set_unusable_password(self):
621        raise NotImplementedError("Use PasswordDevice.set_unusable_password()")
622
623    @property
624    def uid(self) -> str:
625        """Generate a globally unique UID, based on the user ID and the hashed secret key"""
626        return sha256(f"{self.id}-{get_install_id()}".encode("ascii")).hexdigest()
627
628    def locale(self, request: HttpRequest | None = None) -> str:
629        """Get the locale the user has configured"""
630        try:
631            locale = self.attributes.get("settings", {}).get("locale", "")
632            if locale:
633                return locale
634        except Exception as exc:  # noqa
635            LOGGER.warning("Failed to get default locale", exc=exc)
636        if request and hasattr(request, "LANGUAGE_CODE"):
637            return request.LANGUAGE_CODE
638        return ""
639
640    @property
641    def avatar(self) -> str:
642        """Get avatar, depending on authentik.avatar setting"""
643        return get_avatar(self)

authentik User model, based on django's contrib auth user model.

user_permissions = None
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 path(unknown):

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

def type(unknown):

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

sources

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.

groups

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.

roles

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 last_updated(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.

@staticmethod
def default_path() -> str:
437    @staticmethod
438    def default_path() -> str:
439        """Get the default user path"""
440        return User._meta.get_field("path").default

Get the default user path

def all_groups(self) -> django.db.models.query.QuerySet:
442    def all_groups(self) -> QuerySet[Group]:
443        """Recursively get all groups this user is a member of."""
444        return self.groups.all().with_ancestors()

Recursively get all groups this user is a member of.

def all_roles(self) -> django.db.models.query.QuerySet:
446    def all_roles(self) -> QuerySet[Role]:
447        """Get all roles of this user and all of its groups (recursively)."""
448        return Role.objects.filter(Q(users=self) | Q(groups__in=self.all_groups())).distinct()

Get all roles of this user and all of its groups (recursively).

def get_managed_role(self, create=False):
450    def get_managed_role(self, create=False):
451        if create:
452            name = managed_role_name(self)
453            role, created = Role.objects.get_or_create(name=name, managed=name)
454            if created:
455                role.users.add(self)
456            return role
457        else:
458            return Role.objects.filter(name=managed_role_name(self)).first()
def get_all_model_perms_on_managed_role(self) -> django.db.models.query.QuerySet:
460    def get_all_model_perms_on_managed_role(self) -> QuerySet[RoleModelPermission]:
461        role = self.get_managed_role()
462        if not role:
463            return RoleModelPermission.objects.none()
464        return RoleModelPermission.objects.filter(role=role)
def get_all_obj_perms_on_managed_role(self) -> django.db.models.query.QuerySet:
466    def get_all_obj_perms_on_managed_role(self) -> QuerySet[RoleObjectPermission]:
467        role = self.get_managed_role()
468        if not role:
469            return RoleObjectPermission.objects.none()
470        return RoleObjectPermission.objects.filter(role=role)
def assign_perms_to_managed_role( self, perms: str | list[str] | django.contrib.auth.models.Permission | list[django.contrib.auth.models.Permission], obj: django.db.models.base.Model | None = None):
472    def assign_perms_to_managed_role(
473        self,
474        perms: str | list[str] | Permission | list[Permission],
475        obj: models.Model | None = None,
476    ):
477        if not perms:
478            return
479        role = self.get_managed_role(create=True)
480        role.assign_perms(perms, obj)
def remove_perms_from_managed_role( self, perms: str | list[str] | django.contrib.auth.models.Permission | list[django.contrib.auth.models.Permission], obj: django.db.models.base.Model | None = None):
482    def remove_perms_from_managed_role(
483        self,
484        perms: str | list[str] | Permission | list[Permission],
485        obj: models.Model | None = None,
486    ):
487        role = self.get_managed_role()
488        if not role:
489            return None
490        role.remove_perms(perms, obj)
def remove_all_perms_from_managed_role(self):
492    def remove_all_perms_from_managed_role(self):
493        role = self.get_managed_role()
494        if not role:
495            return None
496        RoleModelPermission.objects.filter(role=role).delete()
497        RoleObjectPermission.objects.filter(role=role).delete()
def group_attributes( self, request: django.http.request.HttpRequest | None = None) -> dict[str, typing.Any]:
499    def group_attributes(self, request: HttpRequest | None = None) -> dict[str, Any]:
500        """Get a dictionary containing the attributes from all groups the user belongs to,
501        including the users attributes"""
502        final_attributes = {}
503        if request and hasattr(request, "brand"):
504            always_merger.merge(final_attributes, request.brand.attributes)
505        for group in self.all_groups().order_by("name"):
506            always_merger.merge(final_attributes, group.attributes)
507        always_merger.merge(final_attributes, self.attributes)
508        return final_attributes

Get a dictionary containing the attributes from all groups the user belongs to, including the users attributes

def app_entitlements( self, app: authentik.core.models.Application | None) -> django.db.models.query.QuerySet:
510    def app_entitlements(self, app: Application | None) -> QuerySet[ApplicationEntitlement]:
511        """Get all entitlements this user has for `app`."""
512        if not app:
513            return ApplicationEntitlement.objects.none()
514        return self.all_app_entitlements().filter(app=app)

Get all entitlements this user has for app.

def all_app_entitlements(self) -> django.db.models.query.QuerySet:
516    def all_app_entitlements(self) -> QuerySet[ApplicationEntitlement]:
517        """Get all entitlements this user is assigned, regardless of access to the application."""
518        all_groups = self.all_groups()
519        return (
520            ApplicationEntitlement.objects.filter(
521                Q(
522                    Q(bindings__user=self) | Q(bindings__group__in=all_groups),
523                    bindings__negate=False,
524                )
525                | Q(
526                    Q(~Q(bindings__user=self), bindings__user__isnull=False)
527                    | Q(~Q(bindings__group__in=all_groups), bindings__group__isnull=False),
528                    bindings__negate=True,
529                ),
530                bindings__enabled=True,
531            )
532            .distinct()
533            .order_by("name")
534        )

Get all entitlements this user is assigned, regardless of access to the application.

def app_entitlements_attributes(self, app: authentik.core.models.Application | None) -> dict:
536    def app_entitlements_attributes(self, app: Application | None) -> dict:
537        """Get a dictionary containing all merged attributes from app entitlements for `app`."""
538        final_attributes = {}
539        for attrs in self.app_entitlements(app).values_list("attributes", flat=True):
540            always_merger.merge(final_attributes, attrs)
541        return final_attributes

Get a dictionary containing all merged attributes from app entitlements for app.

serializer: rest_framework.serializers.Serializer
543    @property
544    def serializer(self) -> Serializer:
545        from authentik.core.api.users import UserSerializer
546
547        return UserSerializer

Get serializer for this model

def is_superuser(unknown):

Get supseruser status based on membership in a group with superuser status

is_staff: bool
554    @property
555    def is_staff(self) -> bool:
556        """superuser == staff user"""
557        return self.is_superuser  # type: ignore

superuser == staff user

ak_groups
560    @property
561    def ak_groups(self):
562        """This is a proxy for a renamed, deprecated field."""
563        from authentik.events.models import Event
564
565        deprecation = "authentik.core.models.User.ak_groups"
566        replacement = "authentik.core.models.User.groups"
567        message_logger = (
568            f"{deprecation} is deprecated and will be removed in a future version of "
569            f"authentik. Please use {replacement} instead."
570        )
571        message_event = (
572            f"{message_logger} This event will not be repeated until it expires (by "
573            "default: in 30 days). See authentik logs for every will invocation of this "
574            "deprecation."
575        )
576        stacktrace = traceback.format_stack()
577        # The last line is this function, the next-to-last line is its caller
578        cause = stacktrace[-2] if len(stacktrace) > 1 else "Unknown, see stacktrace in logs"
579        if search := re.search(r'"(.*?)"', cause):
580            cause = f"Property mapping or Expression policy named {search.group(1)}"
581
582        LOGGER.warning(
583            "deprecation used",
584            message=message_logger,
585            deprecation=deprecation,
586            replacement=replacement,
587            cause=cause,
588            stacktrace=stacktrace,
589        )
590        Event.log_deprecation(
591            deprecation, message=message_event, cause=cause, replacement=replacement
592        )
593        return self.groups

This is a proxy for a renamed, deprecated field.

password: str
598    @property
599    def password(self) -> str:
600        device = getattr(self, "password_device", None)
601        return device.password if device else UNUSABLE_PASSWORD_PREFIX

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

password_change_date: datetime.datetime
603    @property
604    def password_change_date(self) -> datetime:
605        device = getattr(self, "password_device", None)
606        return device.password_change_date if device else self.date_joined
def check_password(self, raw_password: str) -> bool:
608    def check_password(self, raw_password: str) -> bool:
609        # Django's version writes `password` when it upgrades an outdated hash.
610        device = getattr(self, "password_device", None)
611        return device.check_password(raw_password) if device else False

Return a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes.

async def acheck_password(self, raw_password: str) -> bool:
613    async def acheck_password(self, raw_password: str) -> bool:
614        return await sync_to_async(self.check_password)(raw_password)

See check_password().

def set_password(self, raw_password):
617    def set_password(self, raw_password):
618        raise NotImplementedError("Use PasswordDevice.set_password()")
def set_unusable_password(self):
620    def set_unusable_password(self):
621        raise NotImplementedError("Use PasswordDevice.set_unusable_password()")
uid: str
623    @property
624    def uid(self) -> str:
625        """Generate a globally unique UID, based on the user ID and the hashed secret key"""
626        return sha256(f"{self.id}-{get_install_id()}".encode("ascii")).hexdigest()

Generate a globally unique UID, based on the user ID and the hashed secret key

def locale(self, request: django.http.request.HttpRequest | None = None) -> str:
628    def locale(self, request: HttpRequest | None = None) -> str:
629        """Get the locale the user has configured"""
630        try:
631            locale = self.attributes.get("settings", {}).get("locale", "")
632            if locale:
633                return locale
634        except Exception as exc:  # noqa
635            LOGGER.warning("Failed to get default locale", exc=exc)
636        if request and hasattr(request, "LANGUAGE_CODE"):
637            return request.LANGUAGE_CODE
638        return ""

Get the locale the user has configured

avatar: str
640    @property
641    def avatar(self) -> str:
642        """Get avatar, depending on authentik.avatar setting"""
643        return get_avatar(self)

Get avatar, depending on authentik.avatar setting

def attributes(unknown):

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

def username(unknown):

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

def first_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 last_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 email(unknown):

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

def is_active(unknown):

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

def date_joined(unknown):

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

def last_login(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_type_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_last_updated(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_last_updated(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_date_joined(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_date_joined(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 id(unknown):

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

policybinding_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.

usersourceconnection_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.

userrole_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.

usergroup_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.

authenticatedsession_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.

actors

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.

actor

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

In the example::

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

Place.restaurant is a ReverseOneToOneDescriptor instance.

activity

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

In the example::

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

Place.restaurant is a ReverseOneToOneDescriptor instance.

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.

password_device

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

In the example::

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

Place.restaurant is a ReverseOneToOneDescriptor instance.

deviceauthenticationtoken_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.

appleauthorizationcode_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.

appleindependentsecureenclave_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.

invitation_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.

authorizationcode_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.

actor_for_authorizationcodes

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.

accesstoken_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.

actor_for_accesstokens

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.

refreshtoken_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.

actor_for_refreshtokens

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.

devicetoken_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.

samlsession_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.

scimprovideruser_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.

scimprovider_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.

staticdevice_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.

duodevice_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.

emaildevice_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.

smsdevice_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.

webauthndevice_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.

scimsourceuser_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.

totpdevice_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.

userconsent_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.

lifecyclerulereviewer_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.

review_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.

offboardings

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.

old_passwords

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.

googleworkspaceprovideruser_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.

microsoftentraprovideruser_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.

dataexport_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.

grant_requests_created

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.

grant_requests_fulfilled

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.

grant_requests_revoked

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.

agent_grant_requests

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.

grantrequestapproval_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.

endpointdevice_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 User.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

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

The query returned multiple objects when only one was expected.

send_saml_logout_request = Actor(<function send_saml_logout_request>, queue_name='default', actor_name='send_saml_logout_request')

Send SAML LogoutRequest to a Service Provider using session data

58def send_post_logout_request(provider: SAMLProvider, processor: LogoutRequestProcessor) -> bool:
59    """Send LogoutRequest using POST binding"""
60    encoded_request = processor.encode_post()
61
62    form_data = {
63        "SAMLRequest": encoded_request,
64    }
65
66    if processor.relay_state:
67        form_data["RelayState"] = processor.relay_state
68
69    response = requests.post(
70        provider.sls_url,
71        data=form_data,
72        timeout=10,
73        headers={
74            "Content-Type": "application/x-www-form-urlencoded",
75        },
76        allow_redirects=True,
77    )
78    response.raise_for_status()
79
80    LOGGER.debug(
81        "Sent POST logout request",
82        provider=provider,
83        status_code=response.status_code,
84    )
85
86    return True

Send LogoutRequest using POST binding

send_saml_logout_response = Actor(<function send_saml_logout_response>, queue_name='default', actor_name='send_saml_logout_response')

Send SAML LogoutResponse to a Service Provider using backchannel (server-to-server)