authentik.lib.models

Generic models

  1"""Generic models"""
  2
  3import re
  4from typing import Self
  5
  6from django.core.validators import URLValidator
  7from django.db import models
  8from django.db.models import Manager, Q, QuerySet
  9from django.utils.regex_helper import _lazy_re_compile
 10from django.utils.timezone import now
 11from model_utils.managers import InheritanceManager
 12from rest_framework.serializers import BaseSerializer
 13
 14from authentik.lib.utils.reflection import class_to_path
 15
 16
 17class SerializerModel(models.Model):
 18    """Base Abstract Model which has a serializer"""
 19
 20    class Meta:
 21        abstract = True
 22
 23    @property
 24    def serializer(self) -> type[BaseSerializer]:
 25        """Get serializer for this model"""
 26        # Special handling for built-in source
 27        if (
 28            hasattr(self, "managed")
 29            and hasattr(self, "MANAGED_INBUILT")
 30            and self.managed == self.MANAGED_INBUILT
 31        ):
 32            from authentik.core.api.sources import SourceSerializer
 33
 34            return SourceSerializer
 35        raise NotImplementedError
 36
 37
 38class CreatedUpdatedModel(models.Model):
 39    """Base Abstract Model to save created and update"""
 40
 41    created = models.DateTimeField(auto_now_add=True)
 42    last_updated = models.DateTimeField(auto_now=True)
 43
 44    class Meta:
 45        abstract = True
 46
 47
 48class InheritanceAutoManager(InheritanceManager):
 49    """Object manager which automatically selects the subclass"""
 50
 51    def get_queryset(self):
 52        return super().get_queryset().select_subclasses()
 53
 54
 55class InheritanceForwardManyToOneDescriptor(models.fields.related.ForwardManyToOneDescriptor):
 56    """Forward ManyToOne Descriptor that selects subclass. Requires InheritanceAutoManager."""
 57
 58    def get_queryset(self, **hints):
 59        return self.field.remote_field.model.objects.db_manager(hints=hints).select_subclasses()
 60
 61
 62class InheritanceForeignKey(models.ForeignKey):
 63    """Custom ForeignKey that uses InheritanceForwardManyToOneDescriptor"""
 64
 65    forward_related_accessor_class = InheritanceForwardManyToOneDescriptor
 66
 67
 68class DeprecatedMixin:
 69    """Mixin for classes that are deprecated"""
 70
 71
 72class InternallyManagedMixin:
 73    """Mixin for models that should _not_ be manageable via blueprint."""
 74
 75
 76class SimpleThroughModel(models.Model, InternallyManagedMixin):
 77    """
 78    Base class for explicit many-to-many through models, mainly used for adjusting API behavior as
 79    if there were no explicit through models
 80    """
 81
 82    class Meta:
 83        abstract = True
 84
 85
 86class DomainlessURLValidator(URLValidator):
 87    """Subclass of URLValidator which doesn't check the domain
 88    (to allow hostnames without domain)"""
 89
 90    def __init__(self, *args, **kwargs) -> None:
 91        super().__init__(*args, **kwargs)
 92        self.host_re = "(" + self.hostname_re + self.domain_re + "|localhost)"
 93        self.regex = _lazy_re_compile(
 94            r"^(?:[a-z0-9.+-]*)://"  # scheme is validated separately
 95            r"(?:[^\s:@/]+(?::[^\s:@/]*)?@)?"  # user:pass authentication
 96            r"(?:" + self.ipv4_re + "|" + self.ipv6_re + "|" + self.host_re + ")"
 97            r"(?::\d{1,5})?"  # port
 98            r"(?:[/?#][^\s]*)?"  # resource path
 99            r"\Z",
100            re.IGNORECASE,
101        )
102        self.schemes = ["http", "https", "blank"] + list(self.schemes)
103
104    def __call__(self, value: str):
105        # Check if the scheme is valid.
106        scheme = value.split("://", maxsplit=1)[0].lower()
107        if scheme not in self.schemes:
108            value = "default" + value
109        super().__call__(value)
110
111
112class DomainlessFormattedURLValidator(DomainlessURLValidator):
113    """URL validator which allows for python format strings and paths relative to the
114    current host. Browsers treat a leading `//` or `/\\` as another host, so those are rejected."""
115
116    relative_re = _lazy_re_compile(r"^/(?![/\\])[^\s\\]*\Z")
117
118    def __init__(self, *args, **kwargs) -> None:
119        super().__init__(*args, **kwargs)
120        self.formatter_re = r"([%\(\)a-zA-Z])*"
121        self.host_re = "(" + self.formatter_re + self.hostname_re + self.domain_re + "|localhost)"
122        self.regex = _lazy_re_compile(
123            r"^(?:[a-z0-9.+-]*)://"  # scheme is validated separately
124            r"(?:[^\s:@/]+(?::[^\s:@/]*)?@)?"  # user:pass authentication
125            r"(?:" + self.ipv4_re + "|" + self.ipv6_re + "|" + self.host_re + ")"
126            r"(?::\d{1,5})?"  # port
127            r"(?:[/?#][^\s]*)?"  # resource path
128            r"\Z",
129            re.IGNORECASE,
130        )
131        self.schemes = ["http", "https", "blank", "ssh", "sftp"] + list(self.schemes)
132
133    def __call__(self, value: str):
134        if self.relative_re.match(value):
135            return
136        super().__call__(value)
137
138
139class ExpiringManager(Manager):
140    """Manager for expiring objects which filters out expired objects by default"""
141
142    def get_queryset(self):
143        return QuerySet(self.model, using=self._db).exclude(expires__lt=now(), expiring=True)
144
145    def including_expired(self):
146        return QuerySet(self.model, using=self._db)
147
148
149class ExpiringModel(models.Model):
150    """Base Model which can expire, and is automatically cleaned up."""
151
152    expires = models.DateTimeField(default=None, null=True)
153    expiring = models.BooleanField(default=True)
154
155    objects = ExpiringManager()
156
157    class Meta:
158        abstract = True
159        indexes = [
160            models.Index(fields=["expires"]),
161            models.Index(fields=["expiring"]),
162            models.Index(fields=["expiring", "expires"]),
163        ]
164
165    def expire_action(self, *args, **kwargs):
166        """Handler which is called when this object is expired. By
167        default the object is deleted. This is less efficient compared
168        to bulk deleting objects, but classes like Token() need to change
169        values instead of being deleted."""
170        try:
171            return self.delete(*args, **kwargs)
172        except self.DoesNotExist:
173            # Object has already been deleted, so this should be fine
174            return None
175
176    @classmethod
177    def filter_not_expired(cls, **kwargs) -> models.QuerySet[Self]:
178        """Filer for tokens which are not expired yet or are not expiring,
179        and match filters in `kwargs`"""
180        from authentik.events.models import Event
181
182        deprecation_id = f"{class_to_path(cls)}.filter_not_expired"
183
184        Event.log_deprecation(
185            deprecation_id,
186            message=(
187                ".filter_not_expired() is deprecated as the default lookup now excludes "
188                "expired objects."
189            ),
190        )
191
192        for obj in (
193            cls.objects.including_expired()
194            .filter(**kwargs)
195            .filter(Q(expires__lt=now(), expiring=True))
196        ):
197            obj.delete()
198        return cls.objects.filter(**kwargs)
199
200    @property
201    def is_expired(self) -> bool:
202        """Check if token is expired yet."""
203        if not self.expiring:
204            return False
205        return now() > self.expires
class SerializerModel(django.db.models.base.Model):
18class SerializerModel(models.Model):
19    """Base Abstract Model which has a serializer"""
20
21    class Meta:
22        abstract = True
23
24    @property
25    def serializer(self) -> type[BaseSerializer]:
26        """Get serializer for this model"""
27        # Special handling for built-in source
28        if (
29            hasattr(self, "managed")
30            and hasattr(self, "MANAGED_INBUILT")
31            and self.managed == self.MANAGED_INBUILT
32        ):
33            from authentik.core.api.sources import SourceSerializer
34
35            return SourceSerializer
36        raise NotImplementedError

Base Abstract Model which has a serializer

serializer: type[rest_framework.serializers.BaseSerializer]
24    @property
25    def serializer(self) -> type[BaseSerializer]:
26        """Get serializer for this model"""
27        # Special handling for built-in source
28        if (
29            hasattr(self, "managed")
30            and hasattr(self, "MANAGED_INBUILT")
31            and self.managed == self.MANAGED_INBUILT
32        ):
33            from authentik.core.api.sources import SourceSerializer
34
35            return SourceSerializer
36        raise NotImplementedError

Get serializer for this model

class SerializerModel.Meta:
21    class Meta:
22        abstract = True
abstract = False
class CreatedUpdatedModel(django.db.models.base.Model):
39class CreatedUpdatedModel(models.Model):
40    """Base Abstract Model to save created and update"""
41
42    created = models.DateTimeField(auto_now_add=True)
43    last_updated = models.DateTimeField(auto_now=True)
44
45    class Meta:
46        abstract = True

Base Abstract Model to save created and update

def created(unknown):

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

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

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

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

def get_previous_by_created(unknown):

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

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

def get_next_by_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.

class CreatedUpdatedModel.Meta:
45    class Meta:
46        abstract = True
abstract = False
class InheritanceAutoManager(model_utils.managers.InheritanceManagerMixin[+ModelT], django.db.models.manager.Manager):
49class InheritanceAutoManager(InheritanceManager):
50    """Object manager which automatically selects the subclass"""
51
52    def get_queryset(self):
53        return super().get_queryset().select_subclasses()

Object manager which automatically selects the subclass

def get_queryset(self):
52    def get_queryset(self):
53        return super().get_queryset().select_subclasses()

Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager.

class InheritanceForwardManyToOneDescriptor(django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor):
56class InheritanceForwardManyToOneDescriptor(models.fields.related.ForwardManyToOneDescriptor):
57    """Forward ManyToOne Descriptor that selects subclass. Requires InheritanceAutoManager."""
58
59    def get_queryset(self, **hints):
60        return self.field.remote_field.model.objects.db_manager(hints=hints).select_subclasses()

Forward ManyToOne Descriptor that selects subclass. Requires InheritanceAutoManager.

def get_queryset(self, **hints):
59    def get_queryset(self, **hints):
60        return self.field.remote_field.model.objects.db_manager(hints=hints).select_subclasses()
class InheritanceForeignKey(django.db.models.fields.related.ForeignKey):
63class InheritanceForeignKey(models.ForeignKey):
64    """Custom ForeignKey that uses InheritanceForwardManyToOneDescriptor"""
65
66    forward_related_accessor_class = InheritanceForwardManyToOneDescriptor

Custom ForeignKey that uses InheritanceForwardManyToOneDescriptor

class DeprecatedMixin:
69class DeprecatedMixin:
70    """Mixin for classes that are deprecated"""

Mixin for classes that are deprecated

class InternallyManagedMixin:
73class InternallyManagedMixin:
74    """Mixin for models that should _not_ be manageable via blueprint."""

Mixin for models that should _not_ be manageable via blueprint.

class SimpleThroughModel(django.db.models.base.Model, InternallyManagedMixin):
77class SimpleThroughModel(models.Model, InternallyManagedMixin):
78    """
79    Base class for explicit many-to-many through models, mainly used for adjusting API behavior as
80    if there were no explicit through models
81    """
82
83    class Meta:
84        abstract = True

Base class for explicit many-to-many through models, mainly used for adjusting API behavior as if there were no explicit through models

class SimpleThroughModel.Meta:
83    class Meta:
84        abstract = True
abstract = False
class DomainlessURLValidator(django.core.validators.URLValidator):
 87class DomainlessURLValidator(URLValidator):
 88    """Subclass of URLValidator which doesn't check the domain
 89    (to allow hostnames without domain)"""
 90
 91    def __init__(self, *args, **kwargs) -> None:
 92        super().__init__(*args, **kwargs)
 93        self.host_re = "(" + self.hostname_re + self.domain_re + "|localhost)"
 94        self.regex = _lazy_re_compile(
 95            r"^(?:[a-z0-9.+-]*)://"  # scheme is validated separately
 96            r"(?:[^\s:@/]+(?::[^\s:@/]*)?@)?"  # user:pass authentication
 97            r"(?:" + self.ipv4_re + "|" + self.ipv6_re + "|" + self.host_re + ")"
 98            r"(?::\d{1,5})?"  # port
 99            r"(?:[/?#][^\s]*)?"  # resource path
100            r"\Z",
101            re.IGNORECASE,
102        )
103        self.schemes = ["http", "https", "blank"] + list(self.schemes)
104
105    def __call__(self, value: str):
106        # Check if the scheme is valid.
107        scheme = value.split("://", maxsplit=1)[0].lower()
108        if scheme not in self.schemes:
109            value = "default" + value
110        super().__call__(value)

Subclass of URLValidator which doesn't check the domain (to allow hostnames without domain)

DomainlessURLValidator(*args, **kwargs)
 91    def __init__(self, *args, **kwargs) -> None:
 92        super().__init__(*args, **kwargs)
 93        self.host_re = "(" + self.hostname_re + self.domain_re + "|localhost)"
 94        self.regex = _lazy_re_compile(
 95            r"^(?:[a-z0-9.+-]*)://"  # scheme is validated separately
 96            r"(?:[^\s:@/]+(?::[^\s:@/]*)?@)?"  # user:pass authentication
 97            r"(?:" + self.ipv4_re + "|" + self.ipv6_re + "|" + self.host_re + ")"
 98            r"(?::\d{1,5})?"  # port
 99            r"(?:[/?#][^\s]*)?"  # resource path
100            r"\Z",
101            re.IGNORECASE,
102        )
103        self.schemes = ["http", "https", "blank"] + list(self.schemes)
host_re = '([a-z¡-\uffff0-9](?:[a-z¡-\uffff0-9-]{0,61}[a-z¡-\uffff0-9])?(?:\\.(?!-)[a-z¡-\uffff0-9-]{1,63}(?<!-))*\\.(?!-)(?:[a-z¡-\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\.?|localhost)'
regex = <SimpleLazyObject: re.compile('^(?:[a-z0-9.+-]*)://(?:[^\\s:@/]+(?::[^\\s:@/]*)?@)?(?:(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)(?:\\.(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)){3}|\\[[0-9a-f:.]+\\]|([a-z¡-\uffff, re.IGNORECASE)>
schemes = ['http', 'https', 'ftp', 'ftps']
class DomainlessFormattedURLValidator(DomainlessURLValidator):
113class DomainlessFormattedURLValidator(DomainlessURLValidator):
114    """URL validator which allows for python format strings and paths relative to the
115    current host. Browsers treat a leading `//` or `/\\` as another host, so those are rejected."""
116
117    relative_re = _lazy_re_compile(r"^/(?![/\\])[^\s\\]*\Z")
118
119    def __init__(self, *args, **kwargs) -> None:
120        super().__init__(*args, **kwargs)
121        self.formatter_re = r"([%\(\)a-zA-Z])*"
122        self.host_re = "(" + self.formatter_re + self.hostname_re + self.domain_re + "|localhost)"
123        self.regex = _lazy_re_compile(
124            r"^(?:[a-z0-9.+-]*)://"  # scheme is validated separately
125            r"(?:[^\s:@/]+(?::[^\s:@/]*)?@)?"  # user:pass authentication
126            r"(?:" + self.ipv4_re + "|" + self.ipv6_re + "|" + self.host_re + ")"
127            r"(?::\d{1,5})?"  # port
128            r"(?:[/?#][^\s]*)?"  # resource path
129            r"\Z",
130            re.IGNORECASE,
131        )
132        self.schemes = ["http", "https", "blank", "ssh", "sftp"] + list(self.schemes)
133
134    def __call__(self, value: str):
135        if self.relative_re.match(value):
136            return
137        super().__call__(value)

URL validator which allows for python format strings and paths relative to the current host. Browsers treat a leading // or /\ as another host, so those are rejected.

DomainlessFormattedURLValidator(*args, **kwargs)
119    def __init__(self, *args, **kwargs) -> None:
120        super().__init__(*args, **kwargs)
121        self.formatter_re = r"([%\(\)a-zA-Z])*"
122        self.host_re = "(" + self.formatter_re + self.hostname_re + self.domain_re + "|localhost)"
123        self.regex = _lazy_re_compile(
124            r"^(?:[a-z0-9.+-]*)://"  # scheme is validated separately
125            r"(?:[^\s:@/]+(?::[^\s:@/]*)?@)?"  # user:pass authentication
126            r"(?:" + self.ipv4_re + "|" + self.ipv6_re + "|" + self.host_re + ")"
127            r"(?::\d{1,5})?"  # port
128            r"(?:[/?#][^\s]*)?"  # resource path
129            r"\Z",
130            re.IGNORECASE,
131        )
132        self.schemes = ["http", "https", "blank", "ssh", "sftp"] + list(self.schemes)
relative_re = <SimpleLazyObject: re.compile('^/(?![/\\\\])[^\\s\\\\]*\\Z')>
formatter_re
host_re = '([a-z¡-\uffff0-9](?:[a-z¡-\uffff0-9-]{0,61}[a-z¡-\uffff0-9])?(?:\\.(?!-)[a-z¡-\uffff0-9-]{1,63}(?<!-))*\\.(?!-)(?:[a-z¡-\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\.?|localhost)'
regex = <SimpleLazyObject: re.compile('^(?:[a-z0-9.+-]*)://(?:[^\\s:@/]+(?::[^\\s:@/]*)?@)?(?:(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)(?:\\.(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)){3}|\\[[0-9a-f:.]+\\]|([a-z¡-\uffff, re.IGNORECASE)>
schemes = ['http', 'https', 'ftp', 'ftps']
class ExpiringManager(django.db.models.manager.Manager):
140class ExpiringManager(Manager):
141    """Manager for expiring objects which filters out expired objects by default"""
142
143    def get_queryset(self):
144        return QuerySet(self.model, using=self._db).exclude(expires__lt=now(), expiring=True)
145
146    def including_expired(self):
147        return QuerySet(self.model, using=self._db)

Manager for expiring objects which filters out expired objects by default

def get_queryset(self):
143    def get_queryset(self):
144        return QuerySet(self.model, using=self._db).exclude(expires__lt=now(), expiring=True)

Return a new QuerySet object. Subclasses can override this method to customize the behavior of the Manager.

def including_expired(self):
146    def including_expired(self):
147        return QuerySet(self.model, using=self._db)
class ExpiringModel(django.db.models.base.Model):
150class ExpiringModel(models.Model):
151    """Base Model which can expire, and is automatically cleaned up."""
152
153    expires = models.DateTimeField(default=None, null=True)
154    expiring = models.BooleanField(default=True)
155
156    objects = ExpiringManager()
157
158    class Meta:
159        abstract = True
160        indexes = [
161            models.Index(fields=["expires"]),
162            models.Index(fields=["expiring"]),
163            models.Index(fields=["expiring", "expires"]),
164        ]
165
166    def expire_action(self, *args, **kwargs):
167        """Handler which is called when this object is expired. By
168        default the object is deleted. This is less efficient compared
169        to bulk deleting objects, but classes like Token() need to change
170        values instead of being deleted."""
171        try:
172            return self.delete(*args, **kwargs)
173        except self.DoesNotExist:
174            # Object has already been deleted, so this should be fine
175            return None
176
177    @classmethod
178    def filter_not_expired(cls, **kwargs) -> models.QuerySet[Self]:
179        """Filer for tokens which are not expired yet or are not expiring,
180        and match filters in `kwargs`"""
181        from authentik.events.models import Event
182
183        deprecation_id = f"{class_to_path(cls)}.filter_not_expired"
184
185        Event.log_deprecation(
186            deprecation_id,
187            message=(
188                ".filter_not_expired() is deprecated as the default lookup now excludes "
189                "expired objects."
190            ),
191        )
192
193        for obj in (
194            cls.objects.including_expired()
195            .filter(**kwargs)
196            .filter(Q(expires__lt=now(), expiring=True))
197        ):
198            obj.delete()
199        return cls.objects.filter(**kwargs)
200
201    @property
202    def is_expired(self) -> bool:
203        """Check if token is expired yet."""
204        if not self.expiring:
205            return False
206        return now() > self.expires

Base Model which can expire, and is automatically cleaned up.

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

The type of the None singleton.

def expire_action(self, *args, **kwargs):
166    def expire_action(self, *args, **kwargs):
167        """Handler which is called when this object is expired. By
168        default the object is deleted. This is less efficient compared
169        to bulk deleting objects, but classes like Token() need to change
170        values instead of being deleted."""
171        try:
172            return self.delete(*args, **kwargs)
173        except self.DoesNotExist:
174            # Object has already been deleted, so this should be fine
175            return None

Handler which is called when this object is expired. By default the object is deleted. This is less efficient compared to bulk deleting objects, but classes like Token() need to change values instead of being deleted.

@classmethod
def filter_not_expired(cls, **kwargs) -> django.db.models.query.QuerySet:
177    @classmethod
178    def filter_not_expired(cls, **kwargs) -> models.QuerySet[Self]:
179        """Filer for tokens which are not expired yet or are not expiring,
180        and match filters in `kwargs`"""
181        from authentik.events.models import Event
182
183        deprecation_id = f"{class_to_path(cls)}.filter_not_expired"
184
185        Event.log_deprecation(
186            deprecation_id,
187            message=(
188                ".filter_not_expired() is deprecated as the default lookup now excludes "
189                "expired objects."
190            ),
191        )
192
193        for obj in (
194            cls.objects.including_expired()
195            .filter(**kwargs)
196            .filter(Q(expires__lt=now(), expiring=True))
197        ):
198            obj.delete()
199        return cls.objects.filter(**kwargs)

Filer for tokens which are not expired yet or are not expiring, and match filters in kwargs

is_expired: bool
201    @property
202    def is_expired(self) -> bool:
203        """Check if token is expired yet."""
204        if not self.expiring:
205            return False
206        return now() > self.expires

Check if token is expired yet.

class ExpiringModel.Meta:
158    class Meta:
159        abstract = True
160        indexes = [
161            models.Index(fields=["expires"]),
162            models.Index(fields=["expiring"]),
163            models.Index(fields=["expiring", "expires"]),
164        ]
abstract = False
indexes = [<Index: fields=['expires']>, <Index: fields=['expiring']>, <Index: fields=['expiring', 'expires']>]