authentik.endpoints.models

  1from datetime import UTC, datetime
  2from typing import TYPE_CHECKING, Any
  3from uuid import uuid4
  4
  5from django.core.cache import cache
  6from django.db import models, transaction
  7from django.db.models import Case, OuterRef, Q, Subquery, When
  8from django.utils.timezone import now
  9from django.utils.translation import gettext_lazy as _
 10from model_utils.managers import InheritanceManager
 11from rest_framework.serializers import Serializer
 12from structlog.stdlib import get_logger
 13
 14from authentik.core.models import AttributesMixin
 15from authentik.flows.models import Stage
 16from authentik.flows.stage import StageView
 17from authentik.lib.merge import MERGE_LIST_UNIQUE
 18from authentik.lib.models import (
 19    ExpiringModel,
 20    InheritanceForeignKey,
 21    InternallyManagedMixin,
 22    SerializerModel,
 23)
 24from authentik.lib.utils.time import timedelta_from_string, timedelta_string_validator
 25from authentik.policies.models import PolicyBinding, PolicyBindingModel
 26from authentik.tasks.schedules.common import ScheduleSpec
 27from authentik.tasks.schedules.models import ScheduledModel
 28
 29if TYPE_CHECKING:
 30    from authentik.endpoints.controller import BaseController
 31
 32LOGGER = get_logger()
 33DEVICE_FACTS_CACHE_TIMEOUT = 3600
 34# Addresses which are never usable to reach a device from the outside
 35LOCAL_ADDRESS_PREFIXES = ("127.", "::1", "169.254.", "fe80:")
 36
 37
 38class Device(InternallyManagedMixin, ExpiringModel, AttributesMixin, PolicyBindingModel):
 39    device_uuid = models.UUIDField(default=uuid4, primary_key=True)
 40
 41    name = models.TextField(unique=True)
 42    identifier = models.TextField(unique=True)
 43    connections = models.ManyToManyField("Connector", through="DeviceConnection")
 44    access_group = models.ForeignKey(
 45        "DeviceAccessGroup", null=True, on_delete=models.SET_DEFAULT, default=None
 46    )
 47
 48    @staticmethod
 49    @transaction.atomic
 50    def get_or_create(identifier: str, name: str, defaults: dict[str, Any] | None = None) -> Device:
 51        defaults = defaults or {}
 52        query = Q()
 53        if identifier:
 54            query |= Q(identifier=identifier)
 55        if name:
 56            query |= Q(name=name)
 57        if query:
 58            # Identifier and name can match different devices; the identifier match wins
 59            device = (
 60                Device.objects.filter(query)
 61                .order_by(Case(When(identifier=identifier, then=0), default=1))
 62                .first()
 63            )
 64            if device:
 65                return device
 66        return Device.objects.create(name=name, identifier=identifier, **defaults)
 67
 68    @property
 69    def cache_key_facts(self):
 70        return f"goauthentik.io/endpoints/devices/{self.device_uuid}/facts"
 71
 72    @property
 73    def cached_facts(self) -> DeviceFactSnapshot:
 74        if cached := cache.get(self.cache_key_facts):
 75            return cached
 76        facts = self.facts
 77        cache.set(self.cache_key_facts, facts, timeout=DEVICE_FACTS_CACHE_TIMEOUT)
 78        return facts
 79
 80    @property
 81    def facts(self) -> DeviceFactSnapshot:
 82        data = {}
 83        last_updated = datetime.fromtimestamp(0, UTC)
 84        for snapshot_data, snapshort_created in DeviceFactSnapshot.objects.filter(
 85            snapshot_id__in=Subquery(
 86                DeviceFactSnapshot.objects.filter(
 87                    connection__connector=OuterRef("connection__connector"), connection__device=self
 88                )
 89                .order_by("-created")
 90                .values("snapshot_id")[:1]
 91            )
 92        ).values_list("data", "created"):
 93            MERGE_LIST_UNIQUE.merge(data, snapshot_data)
 94            last_updated = max(last_updated, snapshort_created)
 95        return DeviceFactSnapshot(data=data, created=last_updated)
 96
 97    @property
 98    def facts_data(self) -> dict[str, Any]:
 99        """Facts of this device, or an empty dict when there are none (yet)"""
100        try:
101            return self.cached_facts.data or {}
102        except KeyError, AttributeError:
103            return {}
104
105    @property
106    def address(self) -> str | None:
107        """Best-effort address to reach this device on, from its most recent facts.
108        The reported hostname is preferred over an interface address."""
109        network = self.facts_data.get("network") or {}
110        if hostname := network.get("hostname"):
111            return hostname
112        for interface in network.get("interfaces") or []:
113            for raw_address in interface.get("ip_addresses") or []:
114                # Interface addresses may carry a prefix length
115                address = raw_address.partition("/")[0]
116                if address.startswith(LOCAL_ADDRESS_PREFIXES):
117                    continue
118                return address
119        return None
120
121    @property
122    def primary_user_binding(self) -> DeviceUserBinding | None:
123        if hasattr(self, "user_bindings"):
124            return next((b for b in self.user_bindings if b.is_primary), None)
125        return DeviceUserBinding.objects.filter(target=self, is_primary=True).first()
126
127    def __str__(self):
128        return f"Device {self.name} {self.identifier} ({self.pk})"
129
130    class Meta(ExpiringModel.Meta):
131        verbose_name = _("Device")
132        verbose_name_plural = _("Devices")
133
134
135class DeviceUserBinding(PolicyBinding):
136    is_primary = models.BooleanField(default=False)
137    # Used for storing a reference to the connector if this user/group binding was created
138    # by a connector and not manually
139    connector = models.ForeignKey("Connector", on_delete=models.CASCADE, null=True)
140
141    class Meta:
142        verbose_name = _("Device User binding")
143        verbose_name_plural = _("Device User bindings")
144
145
146class DeviceConnection(InternallyManagedMixin, SerializerModel):
147    device_connection_uuid = models.UUIDField(default=uuid4, primary_key=True)
148    device = models.ForeignKey("Device", on_delete=models.CASCADE)
149    connector = models.ForeignKey("Connector", on_delete=models.CASCADE)
150
151    @transaction.atomic
152    def create_snapshot(self, data: dict[str, Any]):
153        # If this is the first snapshot for this connection, purge the cache
154        if not DeviceFactSnapshot.objects.filter(connection=self).exists():
155            LOGGER.debug("Purging facts cache for device", device=self.device)
156            cache.delete(self.device.cache_key_facts)
157        # The latest snapshot of a connection never expires, so a device keeps its facts
158        # even when the connector stops reporting. Superseded snapshots start expiring now.
159        DeviceFactSnapshot.objects.filter(connection=self, expiring=False).update(
160            expiring=True,
161            expires=now() + timedelta_from_string(self.connector.snapshot_expiry),
162        )
163        return DeviceFactSnapshot.objects.create(
164            connection=self,
165            data=data,
166            expiring=False,
167        )
168
169    @property
170    def serializer(self) -> type[Serializer]:
171        from authentik.endpoints.api.device_connections import DeviceConnectionSerializer
172
173        return DeviceConnectionSerializer
174
175    class Meta:
176        verbose_name = _("Device connection")
177        verbose_name_plural = _("Device connections")
178
179
180class DeviceFactSnapshot(InternallyManagedMixin, ExpiringModel, SerializerModel):
181    snapshot_id = models.UUIDField(primary_key=True, default=uuid4)
182    connection = models.ForeignKey(DeviceConnection, on_delete=models.CASCADE)
183    data = models.JSONField(default=dict)
184    created = models.DateTimeField(auto_now_add=True)
185
186    def __str__(self):
187        return f"Device fact snapshot {self.snapshot_id} from {self.created}"
188
189    @property
190    def serializer(self) -> type[Serializer]:
191        from authentik.endpoints.api.device_fact_snapshots import DeviceFactSnapshotSerializer
192
193        return DeviceFactSnapshotSerializer
194
195    class Meta(ExpiringModel.Meta):
196        verbose_name = _("Device fact snapshot")
197        verbose_name_plural = _("Device fact snapshots")
198
199
200class Connector(ScheduledModel, SerializerModel):
201    connector_uuid = models.UUIDField(default=uuid4, primary_key=True)
202
203    name = models.TextField()
204    enabled = models.BooleanField(default=True)
205
206    snapshot_expiry = models.TextField(
207        default="hours=24",
208        validators=[timedelta_string_validator],
209    )
210
211    objects = InheritanceManager()
212
213    @property
214    def stage(self) -> type[StageView] | None:
215        return None
216
217    @property
218    def component(self) -> str:
219        raise NotImplementedError
220
221    @property
222    def controller(self) -> type[BaseController[Connector]]:
223        raise NotImplementedError
224
225    @property
226    def schedule_specs(self) -> list[ScheduleSpec]:
227        from authentik.endpoints.controller import Capabilities, ConnectorSyncException
228        from authentik.endpoints.tasks import endpoints_sync
229
230        try:
231            if Capabilities.ENROLL_AUTOMATIC_API not in self.controller(self).capabilities():
232                return []
233        except ConnectorSyncException:
234            return []
235        return [
236            ScheduleSpec(
237                actor=endpoints_sync,
238                uid=self.name,
239                args=(self.pk,),
240                crontab="3-59/15 * * * *",
241                send_on_save=True,
242            ),
243        ]
244
245
246class DeviceAccessGroup(AttributesMixin, SerializerModel, PolicyBindingModel):
247    name = models.TextField(unique=True)
248
249    @property
250    def serializer(self) -> type[Serializer]:
251        from authentik.endpoints.api.device_access_group import DeviceAccessGroupSerializer
252
253        return DeviceAccessGroupSerializer
254
255    class Meta:
256        verbose_name = _("Device access group")
257        verbose_name_plural = _("Device access groups")
258
259
260class StageMode(models.TextChoices):
261    """Modes the Stage can operate in"""
262
263    OPTIONAL = "optional"
264    REQUIRED = "required"
265
266
267class EndpointStage(Stage):
268    """Stage which associates the currently used device with the current session."""
269
270    connector = InheritanceForeignKey(Connector, on_delete=models.CASCADE)
271
272    mode = models.TextField(choices=StageMode.choices, default=StageMode.OPTIONAL)
273
274    @property
275    def view(self) -> type[StageView]:
276        from authentik.endpoints.stage import EndpointStageView
277
278        return EndpointStageView
279
280    @property
281    def serializer(self) -> type[Serializer]:
282        from authentik.endpoints.api.stages import EndpointStageSerializer
283
284        return EndpointStageSerializer
285
286    @property
287    def component(self) -> str:
288        return "ak-endpoints-stage-form"
289
290    class Meta:
291        verbose_name = _("Endpoint Stage")
292        verbose_name_plural = _("Endpoint Stages")
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
DEVICE_FACTS_CACHE_TIMEOUT = 3600
LOCAL_ADDRESS_PREFIXES = ('127.', '::1', '169.254.', 'fe80:')
 39class Device(InternallyManagedMixin, ExpiringModel, AttributesMixin, PolicyBindingModel):
 40    device_uuid = models.UUIDField(default=uuid4, primary_key=True)
 41
 42    name = models.TextField(unique=True)
 43    identifier = models.TextField(unique=True)
 44    connections = models.ManyToManyField("Connector", through="DeviceConnection")
 45    access_group = models.ForeignKey(
 46        "DeviceAccessGroup", null=True, on_delete=models.SET_DEFAULT, default=None
 47    )
 48
 49    @staticmethod
 50    @transaction.atomic
 51    def get_or_create(identifier: str, name: str, defaults: dict[str, Any] | None = None) -> Device:
 52        defaults = defaults or {}
 53        query = Q()
 54        if identifier:
 55            query |= Q(identifier=identifier)
 56        if name:
 57            query |= Q(name=name)
 58        if query:
 59            # Identifier and name can match different devices; the identifier match wins
 60            device = (
 61                Device.objects.filter(query)
 62                .order_by(Case(When(identifier=identifier, then=0), default=1))
 63                .first()
 64            )
 65            if device:
 66                return device
 67        return Device.objects.create(name=name, identifier=identifier, **defaults)
 68
 69    @property
 70    def cache_key_facts(self):
 71        return f"goauthentik.io/endpoints/devices/{self.device_uuid}/facts"
 72
 73    @property
 74    def cached_facts(self) -> DeviceFactSnapshot:
 75        if cached := cache.get(self.cache_key_facts):
 76            return cached
 77        facts = self.facts
 78        cache.set(self.cache_key_facts, facts, timeout=DEVICE_FACTS_CACHE_TIMEOUT)
 79        return facts
 80
 81    @property
 82    def facts(self) -> DeviceFactSnapshot:
 83        data = {}
 84        last_updated = datetime.fromtimestamp(0, UTC)
 85        for snapshot_data, snapshort_created in DeviceFactSnapshot.objects.filter(
 86            snapshot_id__in=Subquery(
 87                DeviceFactSnapshot.objects.filter(
 88                    connection__connector=OuterRef("connection__connector"), connection__device=self
 89                )
 90                .order_by("-created")
 91                .values("snapshot_id")[:1]
 92            )
 93        ).values_list("data", "created"):
 94            MERGE_LIST_UNIQUE.merge(data, snapshot_data)
 95            last_updated = max(last_updated, snapshort_created)
 96        return DeviceFactSnapshot(data=data, created=last_updated)
 97
 98    @property
 99    def facts_data(self) -> dict[str, Any]:
100        """Facts of this device, or an empty dict when there are none (yet)"""
101        try:
102            return self.cached_facts.data or {}
103        except KeyError, AttributeError:
104            return {}
105
106    @property
107    def address(self) -> str | None:
108        """Best-effort address to reach this device on, from its most recent facts.
109        The reported hostname is preferred over an interface address."""
110        network = self.facts_data.get("network") or {}
111        if hostname := network.get("hostname"):
112            return hostname
113        for interface in network.get("interfaces") or []:
114            for raw_address in interface.get("ip_addresses") or []:
115                # Interface addresses may carry a prefix length
116                address = raw_address.partition("/")[0]
117                if address.startswith(LOCAL_ADDRESS_PREFIXES):
118                    continue
119                return address
120        return None
121
122    @property
123    def primary_user_binding(self) -> DeviceUserBinding | None:
124        if hasattr(self, "user_bindings"):
125            return next((b for b in self.user_bindings if b.is_primary), None)
126        return DeviceUserBinding.objects.filter(target=self, is_primary=True).first()
127
128    def __str__(self):
129        return f"Device {self.name} {self.identifier} ({self.pk})"
130
131    class Meta(ExpiringModel.Meta):
132        verbose_name = _("Device")
133        verbose_name_plural = _("Devices")

Device(pbm_uuid, policy_engine_mode, policybindingmodel_ptr, expires, expiring, attributes, device_uuid, name, identifier, access_group)

def device_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 identifier(unknown):

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

connections

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.

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

@staticmethod
@transaction.atomic
def get_or_create( identifier: str, name: str, defaults: dict[str, Any] | None = None) -> Device:
49    @staticmethod
50    @transaction.atomic
51    def get_or_create(identifier: str, name: str, defaults: dict[str, Any] | None = None) -> Device:
52        defaults = defaults or {}
53        query = Q()
54        if identifier:
55            query |= Q(identifier=identifier)
56        if name:
57            query |= Q(name=name)
58        if query:
59            # Identifier and name can match different devices; the identifier match wins
60            device = (
61                Device.objects.filter(query)
62                .order_by(Case(When(identifier=identifier, then=0), default=1))
63                .first()
64            )
65            if device:
66                return device
67        return Device.objects.create(name=name, identifier=identifier, **defaults)
cache_key_facts
69    @property
70    def cache_key_facts(self):
71        return f"goauthentik.io/endpoints/devices/{self.device_uuid}/facts"
cached_facts: DeviceFactSnapshot
73    @property
74    def cached_facts(self) -> DeviceFactSnapshot:
75        if cached := cache.get(self.cache_key_facts):
76            return cached
77        facts = self.facts
78        cache.set(self.cache_key_facts, facts, timeout=DEVICE_FACTS_CACHE_TIMEOUT)
79        return facts
facts: DeviceFactSnapshot
81    @property
82    def facts(self) -> DeviceFactSnapshot:
83        data = {}
84        last_updated = datetime.fromtimestamp(0, UTC)
85        for snapshot_data, snapshort_created in DeviceFactSnapshot.objects.filter(
86            snapshot_id__in=Subquery(
87                DeviceFactSnapshot.objects.filter(
88                    connection__connector=OuterRef("connection__connector"), connection__device=self
89                )
90                .order_by("-created")
91                .values("snapshot_id")[:1]
92            )
93        ).values_list("data", "created"):
94            MERGE_LIST_UNIQUE.merge(data, snapshot_data)
95            last_updated = max(last_updated, snapshort_created)
96        return DeviceFactSnapshot(data=data, created=last_updated)
facts_data: dict[str, typing.Any]
 98    @property
 99    def facts_data(self) -> dict[str, Any]:
100        """Facts of this device, or an empty dict when there are none (yet)"""
101        try:
102            return self.cached_facts.data or {}
103        except KeyError, AttributeError:
104            return {}

Facts of this device, or an empty dict when there are none (yet)

address: str | None
106    @property
107    def address(self) -> str | None:
108        """Best-effort address to reach this device on, from its most recent facts.
109        The reported hostname is preferred over an interface address."""
110        network = self.facts_data.get("network") or {}
111        if hostname := network.get("hostname"):
112            return hostname
113        for interface in network.get("interfaces") or []:
114            for raw_address in interface.get("ip_addresses") or []:
115                # Interface addresses may carry a prefix length
116                address = raw_address.partition("/")[0]
117                if address.startswith(LOCAL_ADDRESS_PREFIXES):
118                    continue
119                return address
120        return None

Best-effort address to reach this device on, from its most recent facts. The reported hostname is preferred over an interface address.

primary_user_binding: DeviceUserBinding | None
122    @property
123    def primary_user_binding(self) -> DeviceUserBinding | None:
124        if hasattr(self, "user_bindings"):
125            return next((b for b in self.user_bindings if b.is_primary), None)
126        return DeviceUserBinding.objects.filter(target=self, is_primary=True).first()
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.

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 attributes(unknown):

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

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

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

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.

rac_override

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.

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

The requested object does not exist

The query returned multiple objects when only one was expected.

class DeviceUserBinding(authentik.policies.models.PolicyBinding):
136class DeviceUserBinding(PolicyBinding):
137    is_primary = models.BooleanField(default=False)
138    # Used for storing a reference to the connector if this user/group binding was created
139    # by a connector and not manually
140    connector = models.ForeignKey("Connector", on_delete=models.CASCADE, null=True)
141
142    class Meta:
143        verbose_name = _("Device User binding")
144        verbose_name_plural = _("Device User bindings")

DeviceUserBinding(expires, policy_binding_uuid, enabled, dry_run, expiring, policy, group, user, target, negate, timeout, failure_result, order, policybinding_ptr, is_primary, connector)

def is_primary(unknown):

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

connector

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.

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

agentdeviceuserbinding

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.

class DeviceUserBinding.DoesNotExist(authentik.policies.models.PolicyBinding.DoesNotExist):

The requested object does not exist

class DeviceUserBinding.MultipleObjectsReturned(authentik.policies.models.PolicyBinding.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

147class DeviceConnection(InternallyManagedMixin, SerializerModel):
148    device_connection_uuid = models.UUIDField(default=uuid4, primary_key=True)
149    device = models.ForeignKey("Device", on_delete=models.CASCADE)
150    connector = models.ForeignKey("Connector", on_delete=models.CASCADE)
151
152    @transaction.atomic
153    def create_snapshot(self, data: dict[str, Any]):
154        # If this is the first snapshot for this connection, purge the cache
155        if not DeviceFactSnapshot.objects.filter(connection=self).exists():
156            LOGGER.debug("Purging facts cache for device", device=self.device)
157            cache.delete(self.device.cache_key_facts)
158        # The latest snapshot of a connection never expires, so a device keeps its facts
159        # even when the connector stops reporting. Superseded snapshots start expiring now.
160        DeviceFactSnapshot.objects.filter(connection=self, expiring=False).update(
161            expiring=True,
162            expires=now() + timedelta_from_string(self.connector.snapshot_expiry),
163        )
164        return DeviceFactSnapshot.objects.create(
165            connection=self,
166            data=data,
167            expiring=False,
168        )
169
170    @property
171    def serializer(self) -> type[Serializer]:
172        from authentik.endpoints.api.device_connections import DeviceConnectionSerializer
173
174        return DeviceConnectionSerializer
175
176    class Meta:
177        verbose_name = _("Device connection")
178        verbose_name_plural = _("Device connections")

DeviceConnection(device_connection_uuid, device, connector)

def device_connection_uuid(unknown):

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

device

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.

connector

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.

@transaction.atomic
def create_snapshot(self, data: dict[str, typing.Any]):
152    @transaction.atomic
153    def create_snapshot(self, data: dict[str, Any]):
154        # If this is the first snapshot for this connection, purge the cache
155        if not DeviceFactSnapshot.objects.filter(connection=self).exists():
156            LOGGER.debug("Purging facts cache for device", device=self.device)
157            cache.delete(self.device.cache_key_facts)
158        # The latest snapshot of a connection never expires, so a device keeps its facts
159        # even when the connector stops reporting. Superseded snapshots start expiring now.
160        DeviceFactSnapshot.objects.filter(connection=self, expiring=False).update(
161            expiring=True,
162            expires=now() + timedelta_from_string(self.connector.snapshot_expiry),
163        )
164        return DeviceFactSnapshot.objects.create(
165            connection=self,
166            data=data,
167            expiring=False,
168        )
serializer: type[rest_framework.serializers.Serializer]
170    @property
171    def serializer(self) -> type[Serializer]:
172        from authentik.endpoints.api.device_connections import DeviceConnectionSerializer
173
174        return DeviceConnectionSerializer

Get serializer for this model

device_id
connector_id
def objects(unknown):

The type of the None singleton.

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

agentdeviceconnection

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.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

181class DeviceFactSnapshot(InternallyManagedMixin, ExpiringModel, SerializerModel):
182    snapshot_id = models.UUIDField(primary_key=True, default=uuid4)
183    connection = models.ForeignKey(DeviceConnection, on_delete=models.CASCADE)
184    data = models.JSONField(default=dict)
185    created = models.DateTimeField(auto_now_add=True)
186
187    def __str__(self):
188        return f"Device fact snapshot {self.snapshot_id} from {self.created}"
189
190    @property
191    def serializer(self) -> type[Serializer]:
192        from authentik.endpoints.api.device_fact_snapshots import DeviceFactSnapshotSerializer
193
194        return DeviceFactSnapshotSerializer
195
196    class Meta(ExpiringModel.Meta):
197        verbose_name = _("Device fact snapshot")
198        verbose_name_plural = _("Device fact snapshots")

DeviceFactSnapshot(expires, expiring, snapshot_id, connection, data, created)

def snapshot_id(unknown):

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

connection

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

serializer: type[rest_framework.serializers.Serializer]
190    @property
191    def serializer(self) -> type[Serializer]:
192        from authentik.endpoints.api.device_fact_snapshots import DeviceFactSnapshotSerializer
193
194        return DeviceFactSnapshotSerializer

Get serializer for this model

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.

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.

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

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

201class Connector(ScheduledModel, SerializerModel):
202    connector_uuid = models.UUIDField(default=uuid4, primary_key=True)
203
204    name = models.TextField()
205    enabled = models.BooleanField(default=True)
206
207    snapshot_expiry = models.TextField(
208        default="hours=24",
209        validators=[timedelta_string_validator],
210    )
211
212    objects = InheritanceManager()
213
214    @property
215    def stage(self) -> type[StageView] | None:
216        return None
217
218    @property
219    def component(self) -> str:
220        raise NotImplementedError
221
222    @property
223    def controller(self) -> type[BaseController[Connector]]:
224        raise NotImplementedError
225
226    @property
227    def schedule_specs(self) -> list[ScheduleSpec]:
228        from authentik.endpoints.controller import Capabilities, ConnectorSyncException
229        from authentik.endpoints.tasks import endpoints_sync
230
231        try:
232            if Capabilities.ENROLL_AUTOMATIC_API not in self.controller(self).capabilities():
233                return []
234        except ConnectorSyncException:
235            return []
236        return [
237            ScheduleSpec(
238                actor=endpoints_sync,
239                uid=self.name,
240                args=(self.pk,),
241                crontab="3-59/15 * * * *",
242                send_on_save=True,
243            ),
244        ]

Connector(connector_uuid, name, enabled, snapshot_expiry)

def connector_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 enabled(unknown):

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

def snapshot_expiry(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.

stage: type[authentik.flows.stage.StageView] | None
214    @property
215    def stage(self) -> type[StageView] | None:
216        return None
component: str
218    @property
219    def component(self) -> str:
220        raise NotImplementedError
controller
222    @property
223    def controller(self) -> type[BaseController[Connector]]:
224        raise NotImplementedError
schedule_specs: list[authentik.tasks.schedules.common.ScheduleSpec]
226    @property
227    def schedule_specs(self) -> list[ScheduleSpec]:
228        from authentik.endpoints.controller import Capabilities, ConnectorSyncException
229        from authentik.endpoints.tasks import endpoints_sync
230
231        try:
232            if Capabilities.ENROLL_AUTOMATIC_API not in self.controller(self).capabilities():
233                return []
234        except ConnectorSyncException:
235            return []
236        return [
237            ScheduleSpec(
238                actor=endpoints_sync,
239                uid=self.name,
240                args=(self.pk,),
241                crontab="3-59/15 * * * *",
242                send_on_save=True,
243            ),
244        ]
schedules

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.

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.

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

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

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

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

agentconnector

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.

fleetconnector

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.

googlechromeconnector

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.

microsoftintuneconnector

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.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

247class DeviceAccessGroup(AttributesMixin, SerializerModel, PolicyBindingModel):
248    name = models.TextField(unique=True)
249
250    @property
251    def serializer(self) -> type[Serializer]:
252        from authentik.endpoints.api.device_access_group import DeviceAccessGroupSerializer
253
254        return DeviceAccessGroupSerializer
255
256    class Meta:
257        verbose_name = _("Device access group")
258        verbose_name_plural = _("Device access groups")

DeviceAccessGroup(pbm_uuid, policy_engine_mode, policybindingmodel_ptr, attributes, name)

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.

serializer: type[rest_framework.serializers.Serializer]
250    @property
251    def serializer(self) -> type[Serializer]:
252        from authentik.endpoints.api.device_access_group import DeviceAccessGroupSerializer
253
254        return DeviceAccessGroupSerializer

Get serializer for this model

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.

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.

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

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

racprovider_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 DeviceAccessGroup.DoesNotExist(authentik.policies.models.PolicyBindingModel.DoesNotExist):

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class StageMode(django.db.models.enums.TextChoices):
261class StageMode(models.TextChoices):
262    """Modes the Stage can operate in"""
263
264    OPTIONAL = "optional"
265    REQUIRED = "required"

Modes the Stage can operate in

OPTIONAL = StageMode.OPTIONAL
REQUIRED = StageMode.REQUIRED
class EndpointStage(authentik.flows.models.Stage):
268class EndpointStage(Stage):
269    """Stage which associates the currently used device with the current session."""
270
271    connector = InheritanceForeignKey(Connector, on_delete=models.CASCADE)
272
273    mode = models.TextField(choices=StageMode.choices, default=StageMode.OPTIONAL)
274
275    @property
276    def view(self) -> type[StageView]:
277        from authentik.endpoints.stage import EndpointStageView
278
279        return EndpointStageView
280
281    @property
282    def serializer(self) -> type[Serializer]:
283        from authentik.endpoints.api.stages import EndpointStageSerializer
284
285        return EndpointStageSerializer
286
287    @property
288    def component(self) -> str:
289        return "ak-endpoints-stage-form"
290
291    class Meta:
292        verbose_name = _("Endpoint Stage")
293        verbose_name_plural = _("Endpoint Stages")

Stage which associates the currently used device with the current session.

connector

Forward ManyToOne Descriptor that selects subclass. Requires InheritanceAutoManager.

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.

view: type[authentik.flows.stage.StageView]
275    @property
276    def view(self) -> type[StageView]:
277        from authentik.endpoints.stage import EndpointStageView
278
279        return EndpointStageView

Return StageView class that implements logic for this stage

serializer: type[rest_framework.serializers.Serializer]
281    @property
282    def serializer(self) -> type[Serializer]:
283        from authentik.endpoints.api.stages import EndpointStageSerializer
284
285        return EndpointStageSerializer

Get serializer for this model

component: str
287    @property
288    def component(self) -> str:
289        return "ak-endpoints-stage-form"

Return component used to edit this object

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

stage_ptr_id
stage_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.

class EndpointStage.DoesNotExist(authentik.flows.models.Stage.DoesNotExist):

The requested object does not exist

class EndpointStage.MultipleObjectsReturned(authentik.flows.models.Stage.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.