authentik.admin.models

authentik admin models

  1"""authentik admin models"""
  2
  3from django.core.validators import MaxValueValidator, MinValueValidator
  4from django.db import IntegrityError, models
  5from django.utils.translation import gettext_lazy as _
  6from rest_framework.serializers import Serializer
  7
  8from authentik.lib.models import (
  9    DomainlessURLValidator,
 10    InternallyManagedMixin,
 11    SerializerModel,
 12)
 13from authentik.lib.utils.time import timedelta_string_validator
 14
 15DEFAULT_TOKEN_DURATION = "days=1"  # nosec
 16DEFAULT_TOKEN_LENGTH = 60
 17DEFAULT_REPUTATION_LOWER_LIMIT = -5
 18DEFAULT_REPUTATION_UPPER_LIMIT = 5
 19
 20
 21class SystemSettingsQuerySet(models.QuerySet):
 22    def update(self, **kwargs) -> int:
 23        # Queryset updates skip post_save, so drop the cached settings here too
 24        from authentik.admin.utils import get_system_settings
 25
 26        rows = super().update(**kwargs)
 27        get_system_settings.cache_clear()
 28        return rows
 29
 30
 31class SystemSettings(InternallyManagedMixin, SerializerModel):
 32    """Global settings for this authentik instance"""
 33
 34    id = models.BooleanField(primary_key=True, default=True)
 35
 36    objects = SystemSettingsQuerySet.as_manager()
 37
 38    avatars = models.TextField(
 39        help_text=_("Configure how authentik should show avatars for users."),
 40        default="gravatar,initials",
 41    )
 42    base_url = models.TextField(
 43        default="",
 44        validators=[
 45            DomainlessURLValidator(
 46                schemes=("http", "https"),
 47                message=_("Enter a valid URL, for example https://authentik.company"),
 48            )
 49        ],
 50        help_text=_(
 51            "Configure the base URL under which this authentik instance is "
 52            "reachable, e.g. https://authentik.company"
 53        ),
 54    )
 55    default_user_change_name = models.BooleanField(
 56        help_text=_("Enable the ability for users to change their name."), default=True
 57    )
 58    default_user_change_email = models.BooleanField(
 59        help_text=_("Enable the ability for users to change their email address."), default=False
 60    )
 61    default_user_change_username = models.BooleanField(
 62        help_text=_("Enable the ability for users to change their username."), default=False
 63    )
 64    event_retention = models.TextField(
 65        default="days=365",
 66        validators=[timedelta_string_validator],
 67        help_text=_(
 68            "Events will be deleted after this duration.(Format: weeks=3;days=2;hours=3;seconds=2)."
 69        ),
 70    )
 71    reputation_lower_limit = models.IntegerField(
 72        help_text=_("Reputation cannot decrease lower than this value. Zero or negative."),
 73        default=DEFAULT_REPUTATION_LOWER_LIMIT,
 74        validators=[MaxValueValidator(0)],
 75    )
 76    reputation_upper_limit = models.IntegerField(
 77        help_text=_("Reputation cannot increase higher than this value. Zero or positive."),
 78        default=DEFAULT_REPUTATION_UPPER_LIMIT,
 79        validators=[MinValueValidator(0)],
 80    )
 81    footer_links = models.JSONField(
 82        help_text=_("The option configures the footer links on the flow executor pages."),
 83        default=list,
 84        blank=True,
 85    )
 86    gdpr_compliance = models.BooleanField(
 87        help_text=_(
 88            "When enabled, all the events caused by a user "
 89            "will be deleted upon the user's deletion."
 90        ),
 91        default=True,
 92    )
 93    impersonation = models.BooleanField(
 94        help_text=_("Globally enable/disable impersonation."), default=True
 95    )
 96    impersonation_require_reason = models.BooleanField(
 97        help_text=_("Require administrators to provide a reason for impersonating a user."),
 98        default=True,
 99    )
100    default_token_duration = models.TextField(
101        help_text=_("Default token duration"),
102        default=DEFAULT_TOKEN_DURATION,
103        validators=[timedelta_string_validator],
104    )
105    default_token_length = models.PositiveIntegerField(
106        help_text=_("Default token length"),
107        default=DEFAULT_TOKEN_LENGTH,
108        validators=[MinValueValidator(1)],
109    )
110
111    pagination_default_page_size = models.PositiveIntegerField(
112        help_text=_("Default page size for API responses, if no size was requested."),
113        default=20,
114    )
115    pagination_max_page_size = models.PositiveIntegerField(
116        help_text=_("Maximum page size"),
117        default=100,
118    )
119
120    flags = models.JSONField(default=dict)
121
122    def save(self, *args, **kwargs):
123        if not self.pk:
124            raise IntegrityError("Only one instance of system settings is allowed")
125        super().save(*args, **kwargs)
126
127    @property
128    def serializer(self) -> Serializer:
129        from authentik.admin.api.settings import SettingsSerializer
130
131        return SettingsSerializer
132
133    def __str__(self) -> str:
134        return "System settings"
135
136    class Meta:
137        verbose_name = _("System settings")
138        verbose_name_plural = _("System settings")
139        default_permissions = []
140
141
142class VersionHistory(models.Model):
143    id = models.BigAutoField(primary_key=True)
144    timestamp = models.DateTimeField()
145    version = models.TextField()
146    build = models.TextField()
147
148    class Meta:
149        managed = False
150        db_table = "authentik_version_history"
151        ordering = ("-timestamp",)
152        verbose_name = _("Version history")
153        verbose_name_plural = _("Version history")
154        default_permissions = []
155
156    def __str__(self):
157        return f"{self.version}.{self.build} ({self.timestamp})"
DEFAULT_TOKEN_DURATION = 'days=1'
DEFAULT_TOKEN_LENGTH = 60
DEFAULT_REPUTATION_LOWER_LIMIT = -5
DEFAULT_REPUTATION_UPPER_LIMIT = 5
class SystemSettingsQuerySet(django.db.models.query.QuerySet):
22class SystemSettingsQuerySet(models.QuerySet):
23    def update(self, **kwargs) -> int:
24        # Queryset updates skip post_save, so drop the cached settings here too
25        from authentik.admin.utils import get_system_settings
26
27        rows = super().update(**kwargs)
28        get_system_settings.cache_clear()
29        return rows

Represent a lazy database lookup for a set of objects.

def update(self, **kwargs) -> int:
23    def update(self, **kwargs) -> int:
24        # Queryset updates skip post_save, so drop the cached settings here too
25        from authentik.admin.utils import get_system_settings
26
27        rows = super().update(**kwargs)
28        get_system_settings.cache_clear()
29        return rows

Update all elements in the current QuerySet, setting all the given fields to the appropriate values.

 32class SystemSettings(InternallyManagedMixin, SerializerModel):
 33    """Global settings for this authentik instance"""
 34
 35    id = models.BooleanField(primary_key=True, default=True)
 36
 37    objects = SystemSettingsQuerySet.as_manager()
 38
 39    avatars = models.TextField(
 40        help_text=_("Configure how authentik should show avatars for users."),
 41        default="gravatar,initials",
 42    )
 43    base_url = models.TextField(
 44        default="",
 45        validators=[
 46            DomainlessURLValidator(
 47                schemes=("http", "https"),
 48                message=_("Enter a valid URL, for example https://authentik.company"),
 49            )
 50        ],
 51        help_text=_(
 52            "Configure the base URL under which this authentik instance is "
 53            "reachable, e.g. https://authentik.company"
 54        ),
 55    )
 56    default_user_change_name = models.BooleanField(
 57        help_text=_("Enable the ability for users to change their name."), default=True
 58    )
 59    default_user_change_email = models.BooleanField(
 60        help_text=_("Enable the ability for users to change their email address."), default=False
 61    )
 62    default_user_change_username = models.BooleanField(
 63        help_text=_("Enable the ability for users to change their username."), default=False
 64    )
 65    event_retention = models.TextField(
 66        default="days=365",
 67        validators=[timedelta_string_validator],
 68        help_text=_(
 69            "Events will be deleted after this duration.(Format: weeks=3;days=2;hours=3;seconds=2)."
 70        ),
 71    )
 72    reputation_lower_limit = models.IntegerField(
 73        help_text=_("Reputation cannot decrease lower than this value. Zero or negative."),
 74        default=DEFAULT_REPUTATION_LOWER_LIMIT,
 75        validators=[MaxValueValidator(0)],
 76    )
 77    reputation_upper_limit = models.IntegerField(
 78        help_text=_("Reputation cannot increase higher than this value. Zero or positive."),
 79        default=DEFAULT_REPUTATION_UPPER_LIMIT,
 80        validators=[MinValueValidator(0)],
 81    )
 82    footer_links = models.JSONField(
 83        help_text=_("The option configures the footer links on the flow executor pages."),
 84        default=list,
 85        blank=True,
 86    )
 87    gdpr_compliance = models.BooleanField(
 88        help_text=_(
 89            "When enabled, all the events caused by a user "
 90            "will be deleted upon the user's deletion."
 91        ),
 92        default=True,
 93    )
 94    impersonation = models.BooleanField(
 95        help_text=_("Globally enable/disable impersonation."), default=True
 96    )
 97    impersonation_require_reason = models.BooleanField(
 98        help_text=_("Require administrators to provide a reason for impersonating a user."),
 99        default=True,
100    )
101    default_token_duration = models.TextField(
102        help_text=_("Default token duration"),
103        default=DEFAULT_TOKEN_DURATION,
104        validators=[timedelta_string_validator],
105    )
106    default_token_length = models.PositiveIntegerField(
107        help_text=_("Default token length"),
108        default=DEFAULT_TOKEN_LENGTH,
109        validators=[MinValueValidator(1)],
110    )
111
112    pagination_default_page_size = models.PositiveIntegerField(
113        help_text=_("Default page size for API responses, if no size was requested."),
114        default=20,
115    )
116    pagination_max_page_size = models.PositiveIntegerField(
117        help_text=_("Maximum page size"),
118        default=100,
119    )
120
121    flags = models.JSONField(default=dict)
122
123    def save(self, *args, **kwargs):
124        if not self.pk:
125            raise IntegrityError("Only one instance of system settings is allowed")
126        super().save(*args, **kwargs)
127
128    @property
129    def serializer(self) -> Serializer:
130        from authentik.admin.api.settings import SettingsSerializer
131
132        return SettingsSerializer
133
134    def __str__(self) -> str:
135        return "System settings"
136
137    class Meta:
138        verbose_name = _("System settings")
139        verbose_name_plural = _("System settings")
140        default_permissions = []

Global settings for this authentik instance

def id(unknown):

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

def objects(unknown):

The type of the None singleton.

def avatars(unknown):

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

def base_url(unknown):

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

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

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

def reputation_lower_limit(unknown):

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

def reputation_upper_limit(unknown):

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

def gdpr_compliance(unknown):

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

def impersonation(unknown):

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

def impersonation_require_reason(unknown):

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

def default_token_duration(unknown):

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

def default_token_length(unknown):

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

def pagination_default_page_size(unknown):

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

def pagination_max_page_size(unknown):

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

def flags(unknown):

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

def save(self, *args, **kwargs):
123    def save(self, *args, **kwargs):
124        if not self.pk:
125            raise IntegrityError("Only one instance of system settings is allowed")
126        super().save(*args, **kwargs)

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

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

serializer: rest_framework.serializers.Serializer
128    @property
129    def serializer(self) -> Serializer:
130        from authentik.admin.api.settings import SettingsSerializer
131
132        return SettingsSerializer

Get serializer for this model

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class VersionHistory(django.db.models.base.Model):
143class VersionHistory(models.Model):
144    id = models.BigAutoField(primary_key=True)
145    timestamp = models.DateTimeField()
146    version = models.TextField()
147    build = models.TextField()
148
149    class Meta:
150        managed = False
151        db_table = "authentik_version_history"
152        ordering = ("-timestamp",)
153        verbose_name = _("Version history")
154        verbose_name_plural = _("Version history")
155        default_permissions = []
156
157    def __str__(self):
158        return f"{self.version}.{self.build} ({self.timestamp})"

VersionHistory(id, timestamp, version, build)

def id(unknown):

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

def timestamp(unknown):

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

def version(unknown):

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

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

The type of the None singleton.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.