authentik.brands.models

brand models

  1"""brand models"""
  2
  3from uuid import uuid4
  4
  5from django.db import models
  6from django.http import HttpRequest
  7from django.utils.translation import gettext_lazy as _
  8from rest_framework.serializers import Serializer
  9from structlog.stdlib import get_logger
 10
 11from authentik.admin.files.fields import FileField
 12from authentik.admin.files.manager import get_file_manager
 13from authentik.admin.files.usage import FileUsage
 14from authentik.crypto.models import CertificateKeyPair
 15from authentik.flows.models import Flow
 16from authentik.lib.models import SerializerModel, SimpleThroughModel
 17
 18LOGGER = get_logger()
 19
 20# Session flag marking a "safe mode" session (e.g. one created via a recovery link).
 21SESSION_KEY_BRAND_SAFE_MODE = "authentik/brands/safe_mode"
 22
 23
 24# Brand FKs read on the request hot path. select_related pulls them into the
 25# same SELECT to avoid N+1 lazy loads; CurrentBrandSerializer alone reads 7.
 26_BRAND_RELATED_FK_FIELDS = (
 27    "flow_authentication",
 28    "flow_user_switch",
 29    "flow_invalidation",
 30    "flow_recovery",
 31    "flow_unenrollment",
 32    "flow_user_settings",
 33    "flow_device_code",
 34    "flow_lockdown",
 35    "flow_request",
 36    "default_application",
 37)
 38
 39
 40class Brand(SerializerModel):
 41    """Single brand"""
 42
 43    brand_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
 44    domain = models.TextField(
 45        help_text=_(
 46            "Domain that activates this brand. Can be a superset, i.e. `a.b` for `aa.b` and `ba.b`"
 47        )
 48    )
 49    default = models.BooleanField(
 50        default=False,
 51    )
 52
 53    branding_title = models.TextField(default="authentik")
 54
 55    branding_logo = FileField(default="/static/dist/assets/icons/icon_left_brand.svg")
 56    branding_favicon = FileField(default="/static/dist/assets/icons/icon.png")
 57    branding_custom_css = models.TextField(default="", blank=True)
 58    branding_default_flow_background = FileField(
 59        default="/static/dist/assets/images/flow_background.jpg",
 60    )
 61    branding_map_tiles = models.TextField(
 62        default="",
 63        blank=True,
 64        help_text=_(
 65            "URL template for the vector tile source used by the events map. "
 66            "Supports XYZ templates with {z}, {x} and {y} placeholders, or "
 67            "pmtiles:// archive URLs. When empty, the frontend uses the "
 68            "bundled hexworld basemap. This value is part of the brand "
 69            "information served to unauthenticated clients; do not embed API "
 70            "keys or other credentials in it."
 71        ),
 72    )
 73
 74    flow_authentication = models.ForeignKey(
 75        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_authentication"
 76    )
 77    flow_user_switch = models.ForeignKey(
 78        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_user_switch"
 79    )
 80    flow_invalidation = models.ForeignKey(
 81        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_invalidation"
 82    )
 83    flow_recovery = models.ForeignKey(
 84        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_recovery"
 85    )
 86    flow_unenrollment = models.ForeignKey(
 87        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_unenrollment"
 88    )
 89    flow_user_settings = models.ForeignKey(
 90        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_user_settings"
 91    )
 92    flow_device_code = models.ForeignKey(
 93        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_device_code"
 94    )
 95    flow_lockdown = models.ForeignKey(
 96        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_lockdown"
 97    )
 98    flow_request = models.ForeignKey(
 99        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_request"
100    )
101
102    default_application = models.ForeignKey(
103        "authentik_core.Application",
104        null=True,
105        default=None,
106        on_delete=models.SET_DEFAULT,
107        help_text=_(
108            "When set, external users will be redirected to this application after authenticating."
109        ),
110    )
111
112    web_certificate = models.ForeignKey(
113        CertificateKeyPair,
114        null=True,
115        default=None,
116        on_delete=models.SET_DEFAULT,
117        help_text=_("Web Certificate used by the authentik Core webserver."),
118        related_name="+",
119    )
120    client_certificates = models.ManyToManyField(
121        CertificateKeyPair,
122        default=None,
123        blank=True,
124        help_text=_("Certificates used for client authentication."),
125        through="BrandClientCertificate",
126    )
127    attributes = models.JSONField(default=dict, blank=True)
128
129    def branding_logo_url(self) -> str:
130        """Get branding_logo URL"""
131        return get_file_manager(FileUsage.MEDIA).file_url(self.branding_logo)
132
133    def branding_logo_themed_urls(self) -> dict[str, str] | None:
134        """Get themed URLs for branding_logo if it contains %(theme)s"""
135        return get_file_manager(FileUsage.MEDIA).themed_urls(self.branding_logo)
136
137    def branding_favicon_url(self) -> str:
138        """Get branding_favicon URL"""
139        return get_file_manager(FileUsage.MEDIA).file_url(self.branding_favicon)
140
141    def branding_favicon_themed_urls(self) -> dict[str, str] | None:
142        """Get themed URLs for branding_favicon if it contains %(theme)s"""
143        return get_file_manager(FileUsage.MEDIA).themed_urls(self.branding_favicon)
144
145    def branding_default_flow_background_url(self, request=None, use_cache: bool = True) -> str:
146        """Get branding_default_flow_background URL"""
147        return get_file_manager(FileUsage.MEDIA).file_url(
148            self.branding_default_flow_background,
149            request,
150            use_cache=use_cache,
151        )
152
153    def branding_default_flow_background_themed_urls(
154        self, request=None, use_cache: bool = True
155    ) -> dict[str, str] | None:
156        """Get themed URLs for branding_default_flow_background if it contains %(theme)s"""
157        return get_file_manager(FileUsage.MEDIA).themed_urls(
158            self.branding_default_flow_background,
159            request,
160            use_cache=use_cache,
161        )
162
163    @property
164    def serializer(self) -> type[Serializer]:
165        from authentik.brands.api import BrandSerializer
166
167        return BrandSerializer
168
169    @property
170    def default_locale(self) -> str:
171        """Get default locale"""
172        try:
173            return self.attributes.get("settings", {}).get("locale", "")
174
175        except Exception as exc:  # noqa
176            LOGGER.warning("Failed to get default locale", exc=exc)
177            return ""
178
179    def __str__(self) -> str:
180        if self.default:
181            return "Default brand"
182        return f"Brand {self.domain}"
183
184    class Meta:
185        verbose_name = _("Brand")
186        verbose_name_plural = _("Brands")
187        indexes = [
188            models.Index(fields=["domain"]),
189            models.Index(fields=["default"]),
190        ]
191
192
193class BrandClientCertificate(SimpleThroughModel):
194    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
195    certificate_key_pair = models.ForeignKey(
196        CertificateKeyPair, on_delete=models.CASCADE, db_column="certificatekeypair_id"
197    )
198
199    class Meta:
200        db_table = "authentik_brands_brand_client_certificates"
201        unique_together = (("brand", "certificate_key_pair"),)
202        verbose_name = _("Brand Client Certificate")
203        verbose_name_plural = _("Brand Client Certificates")
204
205    def __str__(self):
206        return (
207            f"BrandClientCertificate for Brand {self.brand_id} "
208            f"and CertificateKeyPair {self.certificate_key_pair_id}."
209        )
210
211
212class WebfingerProvider(models.Model):
213    """Provider which supports webfinger discovery"""
214
215    class Meta:
216        abstract = True
217
218    def webfinger(self, resource: str, request: HttpRequest) -> dict:
219        raise NotImplementedError()
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
SESSION_KEY_BRAND_SAFE_MODE = 'authentik/brands/safe_mode'
class Brand(authentik.lib.models.SerializerModel):
 41class Brand(SerializerModel):
 42    """Single brand"""
 43
 44    brand_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4)
 45    domain = models.TextField(
 46        help_text=_(
 47            "Domain that activates this brand. Can be a superset, i.e. `a.b` for `aa.b` and `ba.b`"
 48        )
 49    )
 50    default = models.BooleanField(
 51        default=False,
 52    )
 53
 54    branding_title = models.TextField(default="authentik")
 55
 56    branding_logo = FileField(default="/static/dist/assets/icons/icon_left_brand.svg")
 57    branding_favicon = FileField(default="/static/dist/assets/icons/icon.png")
 58    branding_custom_css = models.TextField(default="", blank=True)
 59    branding_default_flow_background = FileField(
 60        default="/static/dist/assets/images/flow_background.jpg",
 61    )
 62    branding_map_tiles = models.TextField(
 63        default="",
 64        blank=True,
 65        help_text=_(
 66            "URL template for the vector tile source used by the events map. "
 67            "Supports XYZ templates with {z}, {x} and {y} placeholders, or "
 68            "pmtiles:// archive URLs. When empty, the frontend uses the "
 69            "bundled hexworld basemap. This value is part of the brand "
 70            "information served to unauthenticated clients; do not embed API "
 71            "keys or other credentials in it."
 72        ),
 73    )
 74
 75    flow_authentication = models.ForeignKey(
 76        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_authentication"
 77    )
 78    flow_user_switch = models.ForeignKey(
 79        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_user_switch"
 80    )
 81    flow_invalidation = models.ForeignKey(
 82        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_invalidation"
 83    )
 84    flow_recovery = models.ForeignKey(
 85        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_recovery"
 86    )
 87    flow_unenrollment = models.ForeignKey(
 88        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_unenrollment"
 89    )
 90    flow_user_settings = models.ForeignKey(
 91        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_user_settings"
 92    )
 93    flow_device_code = models.ForeignKey(
 94        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_device_code"
 95    )
 96    flow_lockdown = models.ForeignKey(
 97        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_lockdown"
 98    )
 99    flow_request = models.ForeignKey(
100        Flow, null=True, on_delete=models.SET_NULL, related_name="brand_request"
101    )
102
103    default_application = models.ForeignKey(
104        "authentik_core.Application",
105        null=True,
106        default=None,
107        on_delete=models.SET_DEFAULT,
108        help_text=_(
109            "When set, external users will be redirected to this application after authenticating."
110        ),
111    )
112
113    web_certificate = models.ForeignKey(
114        CertificateKeyPair,
115        null=True,
116        default=None,
117        on_delete=models.SET_DEFAULT,
118        help_text=_("Web Certificate used by the authentik Core webserver."),
119        related_name="+",
120    )
121    client_certificates = models.ManyToManyField(
122        CertificateKeyPair,
123        default=None,
124        blank=True,
125        help_text=_("Certificates used for client authentication."),
126        through="BrandClientCertificate",
127    )
128    attributes = models.JSONField(default=dict, blank=True)
129
130    def branding_logo_url(self) -> str:
131        """Get branding_logo URL"""
132        return get_file_manager(FileUsage.MEDIA).file_url(self.branding_logo)
133
134    def branding_logo_themed_urls(self) -> dict[str, str] | None:
135        """Get themed URLs for branding_logo if it contains %(theme)s"""
136        return get_file_manager(FileUsage.MEDIA).themed_urls(self.branding_logo)
137
138    def branding_favicon_url(self) -> str:
139        """Get branding_favicon URL"""
140        return get_file_manager(FileUsage.MEDIA).file_url(self.branding_favicon)
141
142    def branding_favicon_themed_urls(self) -> dict[str, str] | None:
143        """Get themed URLs for branding_favicon if it contains %(theme)s"""
144        return get_file_manager(FileUsage.MEDIA).themed_urls(self.branding_favicon)
145
146    def branding_default_flow_background_url(self, request=None, use_cache: bool = True) -> str:
147        """Get branding_default_flow_background URL"""
148        return get_file_manager(FileUsage.MEDIA).file_url(
149            self.branding_default_flow_background,
150            request,
151            use_cache=use_cache,
152        )
153
154    def branding_default_flow_background_themed_urls(
155        self, request=None, use_cache: bool = True
156    ) -> dict[str, str] | None:
157        """Get themed URLs for branding_default_flow_background if it contains %(theme)s"""
158        return get_file_manager(FileUsage.MEDIA).themed_urls(
159            self.branding_default_flow_background,
160            request,
161            use_cache=use_cache,
162        )
163
164    @property
165    def serializer(self) -> type[Serializer]:
166        from authentik.brands.api import BrandSerializer
167
168        return BrandSerializer
169
170    @property
171    def default_locale(self) -> str:
172        """Get default locale"""
173        try:
174            return self.attributes.get("settings", {}).get("locale", "")
175
176        except Exception as exc:  # noqa
177            LOGGER.warning("Failed to get default locale", exc=exc)
178            return ""
179
180    def __str__(self) -> str:
181        if self.default:
182            return "Default brand"
183        return f"Brand {self.domain}"
184
185    class Meta:
186        verbose_name = _("Brand")
187        verbose_name_plural = _("Brands")
188        indexes = [
189            models.Index(fields=["domain"]),
190            models.Index(fields=["default"]),
191        ]

Single brand

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

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

def branding_title(unknown):

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

def branding_favicon(unknown):

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

def branding_custom_css(unknown):

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

def branding_default_flow_background(unknown):

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

def branding_map_tiles(unknown):

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

flow_authentication

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.

flow_user_switch

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.

flow_invalidation

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.

flow_recovery

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.

flow_unenrollment

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.

flow_user_settings

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.

flow_device_code

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.

flow_lockdown

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.

flow_request

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.

default_application

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.

web_certificate

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.

client_certificates

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 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 branding_logo_url(self) -> str:
130    def branding_logo_url(self) -> str:
131        """Get branding_logo URL"""
132        return get_file_manager(FileUsage.MEDIA).file_url(self.branding_logo)

Get branding_logo URL

def branding_logo_themed_urls(self) -> dict[str, str] | None:
134    def branding_logo_themed_urls(self) -> dict[str, str] | None:
135        """Get themed URLs for branding_logo if it contains %(theme)s"""
136        return get_file_manager(FileUsage.MEDIA).themed_urls(self.branding_logo)

Get themed URLs for branding_logo if it contains %(theme)s

def branding_favicon_url(self) -> str:
138    def branding_favicon_url(self) -> str:
139        """Get branding_favicon URL"""
140        return get_file_manager(FileUsage.MEDIA).file_url(self.branding_favicon)

Get branding_favicon URL

def branding_favicon_themed_urls(self) -> dict[str, str] | None:
142    def branding_favicon_themed_urls(self) -> dict[str, str] | None:
143        """Get themed URLs for branding_favicon if it contains %(theme)s"""
144        return get_file_manager(FileUsage.MEDIA).themed_urls(self.branding_favicon)

Get themed URLs for branding_favicon if it contains %(theme)s

def branding_default_flow_background_url(self, request=None, use_cache: bool = True) -> str:
146    def branding_default_flow_background_url(self, request=None, use_cache: bool = True) -> str:
147        """Get branding_default_flow_background URL"""
148        return get_file_manager(FileUsage.MEDIA).file_url(
149            self.branding_default_flow_background,
150            request,
151            use_cache=use_cache,
152        )

Get branding_default_flow_background URL

def branding_default_flow_background_themed_urls(self, request=None, use_cache: bool = True) -> dict[str, str] | None:
154    def branding_default_flow_background_themed_urls(
155        self, request=None, use_cache: bool = True
156    ) -> dict[str, str] | None:
157        """Get themed URLs for branding_default_flow_background if it contains %(theme)s"""
158        return get_file_manager(FileUsage.MEDIA).themed_urls(
159            self.branding_default_flow_background,
160            request,
161            use_cache=use_cache,
162        )

Get themed URLs for branding_default_flow_background if it contains %(theme)s

serializer: type[rest_framework.serializers.Serializer]
164    @property
165    def serializer(self) -> type[Serializer]:
166        from authentik.brands.api import BrandSerializer
167
168        return BrandSerializer

Get serializer for this model

default_locale: str
170    @property
171    def default_locale(self) -> str:
172        """Get default locale"""
173        try:
174            return self.attributes.get("settings", {}).get("locale", "")
175
176        except Exception as exc:  # noqa
177            LOGGER.warning("Failed to get default locale", exc=exc)
178            return ""

Get default locale

flow_authentication_id
flow_user_switch_id
flow_invalidation_id
flow_recovery_id
flow_unenrollment_id
flow_user_settings_id
flow_device_code_id
flow_lockdown_id
flow_request_id
default_application_id
web_certificate_id
def objects(unknown):

The type of the None singleton.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class BrandClientCertificate(authentik.lib.models.SimpleThroughModel):
194class BrandClientCertificate(SimpleThroughModel):
195    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
196    certificate_key_pair = models.ForeignKey(
197        CertificateKeyPair, on_delete=models.CASCADE, db_column="certificatekeypair_id"
198    )
199
200    class Meta:
201        db_table = "authentik_brands_brand_client_certificates"
202        unique_together = (("brand", "certificate_key_pair"),)
203        verbose_name = _("Brand Client Certificate")
204        verbose_name_plural = _("Brand Client Certificates")
205
206    def __str__(self):
207        return (
208            f"BrandClientCertificate for Brand {self.brand_id} "
209            f"and CertificateKeyPair {self.certificate_key_pair_id}."
210        )

BrandClientCertificate(id, brand, certificate_key_pair)

brand

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.

certificate_key_pair

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.

brand_id
certificate_key_pair_id
def id(unknown):

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

def objects(unknown):

The type of the None singleton.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class WebfingerProvider(django.db.models.base.Model):
213class WebfingerProvider(models.Model):
214    """Provider which supports webfinger discovery"""
215
216    class Meta:
217        abstract = True
218
219    def webfinger(self, resource: str, request: HttpRequest) -> dict:
220        raise NotImplementedError()

Provider which supports webfinger discovery

def webfinger(self, resource: str, request: django.http.request.HttpRequest) -> dict:
219    def webfinger(self, resource: str, request: HttpRequest) -> dict:
220        raise NotImplementedError()
class WebfingerProvider.Meta:
216    class Meta:
217        abstract = True
abstract = False