authentik.brands.api

Serializer for brands models

  1"""Serializer for brands models"""
  2
  3from typing import Any, get_args
  4
  5from django.db import models
  6from drf_spectacular.extensions import OpenApiSerializerFieldExtension
  7from drf_spectacular.plumbing import build_basic_type, build_object_type
  8from drf_spectacular.utils import extend_schema, extend_schema_field
  9from rest_framework.decorators import action
 10from rest_framework.exceptions import ValidationError
 11from rest_framework.fields import (
 12    CharField,
 13    ChoiceField,
 14    ListField,
 15    SerializerMethodField,
 16)
 17from rest_framework.filters import OrderingFilter, SearchFilter
 18from rest_framework.permissions import AllowAny
 19from rest_framework.request import Request
 20from rest_framework.response import Response
 21from rest_framework.validators import UniqueValidator
 22from rest_framework.viewsets import ModelViewSet
 23
 24from authentik.admin.api.settings import FlagJSONField
 25from authentik.admin.flags import Flag
 26from authentik.admin.utils import get_system_settings
 27from authentik.brands.models import Brand
 28from authentik.brands.utils import session_safe_mode
 29from authentik.core.api.used_by import UsedByMixin
 30from authentik.core.api.utils import ModelSerializer, PassiveSerializer, ThemedUrlsSerializer
 31from authentik.crypto.validators import TLS_KEY_TYPES, KeyTypeValidator
 32from authentik.rbac.filters import SecretKeyFilter
 33
 34
 35class FooterLinkSerializer(PassiveSerializer):
 36    """Links returned in Config API"""
 37
 38    href = CharField(read_only=True, allow_null=True)
 39    name = CharField(read_only=True)
 40
 41
 42class BrandSerializer(ModelSerializer):
 43    """Brand Serializer"""
 44
 45    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
 46        if attrs.get("default", False):
 47            brands = Brand.objects.filter(default=True)
 48            if self.instance:
 49                brands = brands.exclude(pk=self.instance.pk)
 50            if brands.exists():
 51                raise ValidationError({"default": "Only a single brand can be set as default."})
 52        return super().validate(attrs)
 53
 54    class Meta:
 55        model = Brand
 56        fields = [
 57            "brand_uuid",
 58            "domain",
 59            "default",
 60            "branding_title",
 61            "branding_logo",
 62            "branding_favicon",
 63            "branding_custom_css",
 64            "branding_default_flow_background",
 65            "branding_map_tiles",
 66            "flow_authentication",
 67            "flow_user_switch",
 68            "flow_invalidation",
 69            "flow_recovery",
 70            "flow_unenrollment",
 71            "flow_user_settings",
 72            "flow_device_code",
 73            "flow_lockdown",
 74            "flow_request",
 75            "default_application",
 76            "web_certificate",
 77            "client_certificates",
 78            "attributes",
 79        ]
 80        extra_kwargs = {
 81            # TODO: This field isn't unique on the database which is hard to backport
 82            # hence we just validate the uniqueness here
 83            "domain": {"validators": [UniqueValidator(Brand.objects.all())]},
 84            "web_certificate": {"validators": [KeyTypeValidator(*TLS_KEY_TYPES)]},
 85            "client_certificates": {"validators": [KeyTypeValidator(*TLS_KEY_TYPES)]},
 86        }
 87
 88
 89class Themes(models.TextChoices):
 90    """Themes"""
 91
 92    AUTOMATIC = "automatic"
 93    LIGHT = "light"
 94    DARK = "dark"
 95
 96
 97def get_default_ui_footer_links():
 98    """Get default UI footer links based on current system settings"""
 99    return get_system_settings().footer_links
100
101
102class PublicFlagsField(FlagJSONField):
103    pass
104
105
106class FlagsJSONExtension(OpenApiSerializerFieldExtension):
107    """Generate API Schema for JSON fields as"""
108
109    target_class = "authentik.brands.api.PublicFlagsField"
110
111    def map_serializer_field(self, auto_schema, direction):
112        props = {}
113        # Public flags are always present; authenticated flags are only present for
114        # authenticated requests, so they are exposed in the schema but not required.
115        required = []
116        for visibility in ("public", "authenticated"):
117            for flag in Flag.available(visibility=visibility):
118                _flag = flag()
119                props[_flag.key] = build_basic_type(get_args(_flag.__orig_bases__[0])[0])
120                if _flag.description:
121                    props[_flag.key]["description"] = _flag.description
122                if _flag.deprecated:
123                    props[_flag.key]["deprecated"] = _flag.deprecated
124                if visibility == "public" and not _flag.deprecated:
125                    required.append(_flag.key)
126        return build_object_type(props, required=required)
127
128
129class CurrentBrandSerializer(PassiveSerializer):
130    """Partial brand information for styling"""
131
132    matched_domain = CharField(source="domain")
133    branding_title = CharField()
134    branding_logo = CharField(source="branding_logo_url")
135    branding_logo_themed_urls = ThemedUrlsSerializer(read_only=True, allow_null=True)
136    branding_favicon = CharField(source="branding_favicon_url")
137    branding_favicon_themed_urls = ThemedUrlsSerializer(read_only=True, allow_null=True)
138    branding_custom_css = CharField()
139    branding_map_tiles = CharField()
140    ui_footer_links = ListField(
141        child=FooterLinkSerializer(),
142        read_only=True,
143        default=get_default_ui_footer_links,
144    )
145    ui_theme = ChoiceField(
146        choices=Themes.choices,
147        source="attributes.settings.theme.base",
148        default=Themes.AUTOMATIC,
149        read_only=True,
150    )
151
152    flow_authentication = CharField(source="flow_authentication.slug", required=False)
153    flow_user_switch = CharField(source="flow_user_switch.slug", required=False)
154    flow_invalidation = CharField(source="flow_invalidation.slug", required=False)
155    flow_recovery = CharField(source="flow_recovery.slug", required=False)
156    flow_unenrollment = CharField(source="flow_unenrollment.slug", required=False)
157    flow_user_settings = CharField(source="flow_user_settings.slug", required=False)
158    flow_device_code = CharField(source="flow_device_code.slug", required=False)
159    flow_lockdown = CharField(source="flow_lockdown.slug", required=False)
160    flow_request = CharField(source="flow_request.slug", required=False)
161
162    default_locale = CharField(read_only=True)
163    flags = SerializerMethodField()
164
165    @extend_schema_field(field=PublicFlagsField)
166    def get_flags(self, _):
167        values = {}
168        visibilities = ["public"]
169        request = self.context.get("request")
170        if request and request.user.is_authenticated:
171            visibilities.append("authenticated")
172        for visibility in visibilities:
173            for flag in Flag.available(visibility=visibility):
174                values[flag().key] = flag.get()
175        return values
176
177    def to_representation(self, instance: Brand) -> dict[str, Any]:
178        data = super().to_representation(instance)
179        # Suppress custom CSS for safe-mode sessions (e.g. recovery links) so that
180        # misconfigured branding cannot prevent a user from reaching the UI to fix it.
181        request = self.context.get("request")
182        if request is not None and session_safe_mode(request):
183            data["branding_custom_css"] = ""
184        return data
185
186
187class BrandViewSet(UsedByMixin, ModelViewSet):
188    """Brand Viewset"""
189
190    queryset = Brand.objects.all()
191    serializer_class = BrandSerializer
192    search_fields = [
193        "domain",
194        "branding_title",
195        "web_certificate__name",
196        "client_certificates__name",
197    ]
198    filterset_fields = [
199        "brand_uuid",
200        "domain",
201        "default",
202        "branding_title",
203        "branding_logo",
204        "branding_favicon",
205        "branding_default_flow_background",
206        "flow_authentication",
207        "flow_user_switch",
208        "flow_invalidation",
209        "flow_recovery",
210        "flow_unenrollment",
211        "flow_user_settings",
212        "flow_device_code",
213        "flow_lockdown",
214        "flow_request",
215        "web_certificate",
216        "client_certificates",
217    ]
218    ordering = ["domain"]
219
220    filter_backends = [SecretKeyFilter, OrderingFilter, SearchFilter]
221
222    @extend_schema(
223        responses=CurrentBrandSerializer(many=False),
224    )
225    @action(methods=["GET"], detail=False, permission_classes=[AllowAny])
226    def current(self, request: Request) -> Response:
227        """Get current brand"""
228        brand: Brand = request._request.brand
229        return Response(CurrentBrandSerializer(brand, context={"request": request}).data)
class FooterLinkSerializer(authentik.core.api.utils.PassiveSerializer):
36class FooterLinkSerializer(PassiveSerializer):
37    """Links returned in Config API"""
38
39    href = CharField(read_only=True, allow_null=True)
40    name = CharField(read_only=True)

Links returned in Config API

href
name
class BrandSerializer(authentik.core.api.utils.ModelSerializer):
43class BrandSerializer(ModelSerializer):
44    """Brand Serializer"""
45
46    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
47        if attrs.get("default", False):
48            brands = Brand.objects.filter(default=True)
49            if self.instance:
50                brands = brands.exclude(pk=self.instance.pk)
51            if brands.exists():
52                raise ValidationError({"default": "Only a single brand can be set as default."})
53        return super().validate(attrs)
54
55    class Meta:
56        model = Brand
57        fields = [
58            "brand_uuid",
59            "domain",
60            "default",
61            "branding_title",
62            "branding_logo",
63            "branding_favicon",
64            "branding_custom_css",
65            "branding_default_flow_background",
66            "branding_map_tiles",
67            "flow_authentication",
68            "flow_user_switch",
69            "flow_invalidation",
70            "flow_recovery",
71            "flow_unenrollment",
72            "flow_user_settings",
73            "flow_device_code",
74            "flow_lockdown",
75            "flow_request",
76            "default_application",
77            "web_certificate",
78            "client_certificates",
79            "attributes",
80        ]
81        extra_kwargs = {
82            # TODO: This field isn't unique on the database which is hard to backport
83            # hence we just validate the uniqueness here
84            "domain": {"validators": [UniqueValidator(Brand.objects.all())]},
85            "web_certificate": {"validators": [KeyTypeValidator(*TLS_KEY_TYPES)]},
86            "client_certificates": {"validators": [KeyTypeValidator(*TLS_KEY_TYPES)]},
87        }

Brand Serializer

def validate(self, attrs: dict[str, typing.Any]) -> dict[str, typing.Any]:
46    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
47        if attrs.get("default", False):
48            brands = Brand.objects.filter(default=True)
49            if self.instance:
50                brands = brands.exclude(pk=self.instance.pk)
51            if brands.exists():
52                raise ValidationError({"default": "Only a single brand can be set as default."})
53        return super().validate(attrs)
class BrandSerializer.Meta:
55    class Meta:
56        model = Brand
57        fields = [
58            "brand_uuid",
59            "domain",
60            "default",
61            "branding_title",
62            "branding_logo",
63            "branding_favicon",
64            "branding_custom_css",
65            "branding_default_flow_background",
66            "branding_map_tiles",
67            "flow_authentication",
68            "flow_user_switch",
69            "flow_invalidation",
70            "flow_recovery",
71            "flow_unenrollment",
72            "flow_user_settings",
73            "flow_device_code",
74            "flow_lockdown",
75            "flow_request",
76            "default_application",
77            "web_certificate",
78            "client_certificates",
79            "attributes",
80        ]
81        extra_kwargs = {
82            # TODO: This field isn't unique on the database which is hard to backport
83            # hence we just validate the uniqueness here
84            "domain": {"validators": [UniqueValidator(Brand.objects.all())]},
85            "web_certificate": {"validators": [KeyTypeValidator(*TLS_KEY_TYPES)]},
86            "client_certificates": {"validators": [KeyTypeValidator(*TLS_KEY_TYPES)]},
87        }
model = <class 'authentik.brands.models.Brand'>
fields = ['brand_uuid', 'domain', 'default', 'branding_title', 'branding_logo', 'branding_favicon', 'branding_custom_css', 'branding_default_flow_background', 'branding_map_tiles', 'flow_authentication', 'flow_user_switch', 'flow_invalidation', 'flow_recovery', 'flow_unenrollment', 'flow_user_settings', 'flow_device_code', 'flow_lockdown', 'flow_request', 'default_application', 'web_certificate', 'client_certificates', 'attributes']
extra_kwargs = {'domain': {'validators': [<UniqueValidator(queryset=<QuerySet []>)>]}, 'web_certificate': {'validators': [<KeyTypeValidator(allowed=[KeyType.RSA, KeyType.EC, KeyType.ED25519, KeyType.MLDSA44, KeyType.MLDSA65, KeyType.MLDSA87])>]}, 'client_certificates': {'validators': [<KeyTypeValidator(allowed=[KeyType.RSA, KeyType.EC, KeyType.ED25519, KeyType.MLDSA44, KeyType.MLDSA65, KeyType.MLDSA87])>]}}
class Themes(django.db.models.enums.TextChoices):
90class Themes(models.TextChoices):
91    """Themes"""
92
93    AUTOMATIC = "automatic"
94    LIGHT = "light"
95    DARK = "dark"

Themes

AUTOMATIC = Themes.AUTOMATIC
LIGHT = Themes.LIGHT
DARK = Themes.DARK
class PublicFlagsField(authentik.admin.api.settings.FlagJSONField):
103class PublicFlagsField(FlagJSONField):
104    pass

JSON Field which only allows dictionaries

class FlagsJSONExtension(drf_spectacular.plumbing.OpenApiGeneratorExtension[ForwardRef('OpenApiSerializerFieldExtension')]):
107class FlagsJSONExtension(OpenApiSerializerFieldExtension):
108    """Generate API Schema for JSON fields as"""
109
110    target_class = "authentik.brands.api.PublicFlagsField"
111
112    def map_serializer_field(self, auto_schema, direction):
113        props = {}
114        # Public flags are always present; authenticated flags are only present for
115        # authenticated requests, so they are exposed in the schema but not required.
116        required = []
117        for visibility in ("public", "authenticated"):
118            for flag in Flag.available(visibility=visibility):
119                _flag = flag()
120                props[_flag.key] = build_basic_type(get_args(_flag.__orig_bases__[0])[0])
121                if _flag.description:
122                    props[_flag.key]["description"] = _flag.description
123                if _flag.deprecated:
124                    props[_flag.key]["deprecated"] = _flag.deprecated
125                if visibility == "public" and not _flag.deprecated:
126                    required.append(_flag.key)
127        return build_object_type(props, required=required)

Generate API Schema for JSON fields as

target_class = 'PublicFlagsField'
def map_serializer_field(self, auto_schema, direction):
112    def map_serializer_field(self, auto_schema, direction):
113        props = {}
114        # Public flags are always present; authenticated flags are only present for
115        # authenticated requests, so they are exposed in the schema but not required.
116        required = []
117        for visibility in ("public", "authenticated"):
118            for flag in Flag.available(visibility=visibility):
119                _flag = flag()
120                props[_flag.key] = build_basic_type(get_args(_flag.__orig_bases__[0])[0])
121                if _flag.description:
122                    props[_flag.key]["description"] = _flag.description
123                if _flag.deprecated:
124                    props[_flag.key]["deprecated"] = _flag.deprecated
125                if visibility == "public" and not _flag.deprecated:
126                    required.append(_flag.key)
127        return build_object_type(props, required=required)

override for customized serializer field mapping

class CurrentBrandSerializer(authentik.core.api.utils.PassiveSerializer):
130class CurrentBrandSerializer(PassiveSerializer):
131    """Partial brand information for styling"""
132
133    matched_domain = CharField(source="domain")
134    branding_title = CharField()
135    branding_logo = CharField(source="branding_logo_url")
136    branding_logo_themed_urls = ThemedUrlsSerializer(read_only=True, allow_null=True)
137    branding_favicon = CharField(source="branding_favicon_url")
138    branding_favicon_themed_urls = ThemedUrlsSerializer(read_only=True, allow_null=True)
139    branding_custom_css = CharField()
140    branding_map_tiles = CharField()
141    ui_footer_links = ListField(
142        child=FooterLinkSerializer(),
143        read_only=True,
144        default=get_default_ui_footer_links,
145    )
146    ui_theme = ChoiceField(
147        choices=Themes.choices,
148        source="attributes.settings.theme.base",
149        default=Themes.AUTOMATIC,
150        read_only=True,
151    )
152
153    flow_authentication = CharField(source="flow_authentication.slug", required=False)
154    flow_user_switch = CharField(source="flow_user_switch.slug", required=False)
155    flow_invalidation = CharField(source="flow_invalidation.slug", required=False)
156    flow_recovery = CharField(source="flow_recovery.slug", required=False)
157    flow_unenrollment = CharField(source="flow_unenrollment.slug", required=False)
158    flow_user_settings = CharField(source="flow_user_settings.slug", required=False)
159    flow_device_code = CharField(source="flow_device_code.slug", required=False)
160    flow_lockdown = CharField(source="flow_lockdown.slug", required=False)
161    flow_request = CharField(source="flow_request.slug", required=False)
162
163    default_locale = CharField(read_only=True)
164    flags = SerializerMethodField()
165
166    @extend_schema_field(field=PublicFlagsField)
167    def get_flags(self, _):
168        values = {}
169        visibilities = ["public"]
170        request = self.context.get("request")
171        if request and request.user.is_authenticated:
172            visibilities.append("authenticated")
173        for visibility in visibilities:
174            for flag in Flag.available(visibility=visibility):
175                values[flag().key] = flag.get()
176        return values
177
178    def to_representation(self, instance: Brand) -> dict[str, Any]:
179        data = super().to_representation(instance)
180        # Suppress custom CSS for safe-mode sessions (e.g. recovery links) so that
181        # misconfigured branding cannot prevent a user from reaching the UI to fix it.
182        request = self.context.get("request")
183        if request is not None and session_safe_mode(request):
184            data["branding_custom_css"] = ""
185        return data

Partial brand information for styling

matched_domain
branding_title
branding_logo_themed_urls
branding_favicon
branding_favicon_themed_urls
branding_custom_css
branding_map_tiles
ui_theme
flow_authentication
flow_user_switch
flow_invalidation
flow_recovery
flow_unenrollment
flow_user_settings
flow_device_code
flow_lockdown
flow_request
default_locale
flags
@extend_schema_field(field=PublicFlagsField)
def get_flags(self, _):
166    @extend_schema_field(field=PublicFlagsField)
167    def get_flags(self, _):
168        values = {}
169        visibilities = ["public"]
170        request = self.context.get("request")
171        if request and request.user.is_authenticated:
172            visibilities.append("authenticated")
173        for visibility in visibilities:
174            for flag in Flag.available(visibility=visibility):
175                values[flag().key] = flag.get()
176        return values
def to_representation(self, instance: authentik.brands.models.Brand) -> dict[str, typing.Any]:
178    def to_representation(self, instance: Brand) -> dict[str, Any]:
179        data = super().to_representation(instance)
180        # Suppress custom CSS for safe-mode sessions (e.g. recovery links) so that
181        # misconfigured branding cannot prevent a user from reaching the UI to fix it.
182        request = self.context.get("request")
183        if request is not None and session_safe_mode(request):
184            data["branding_custom_css"] = ""
185        return data

Object instance -> Dict of primitive datatypes.

class BrandViewSet(authentik.core.api.used_by.UsedByMixin, rest_framework.viewsets.ModelViewSet):
188class BrandViewSet(UsedByMixin, ModelViewSet):
189    """Brand Viewset"""
190
191    queryset = Brand.objects.all()
192    serializer_class = BrandSerializer
193    search_fields = [
194        "domain",
195        "branding_title",
196        "web_certificate__name",
197        "client_certificates__name",
198    ]
199    filterset_fields = [
200        "brand_uuid",
201        "domain",
202        "default",
203        "branding_title",
204        "branding_logo",
205        "branding_favicon",
206        "branding_default_flow_background",
207        "flow_authentication",
208        "flow_user_switch",
209        "flow_invalidation",
210        "flow_recovery",
211        "flow_unenrollment",
212        "flow_user_settings",
213        "flow_device_code",
214        "flow_lockdown",
215        "flow_request",
216        "web_certificate",
217        "client_certificates",
218    ]
219    ordering = ["domain"]
220
221    filter_backends = [SecretKeyFilter, OrderingFilter, SearchFilter]
222
223    @extend_schema(
224        responses=CurrentBrandSerializer(many=False),
225    )
226    @action(methods=["GET"], detail=False, permission_classes=[AllowAny])
227    def current(self, request: Request) -> Response:
228        """Get current brand"""
229        brand: Brand = request._request.brand
230        return Response(CurrentBrandSerializer(brand, context={"request": request}).data)

Brand Viewset

queryset = <QuerySet []>
serializer_class = <class 'BrandSerializer'>
search_fields = ['domain', 'branding_title', 'web_certificate__name', 'client_certificates__name']
filterset_fields = ['brand_uuid', 'domain', 'default', 'branding_title', 'branding_logo', 'branding_favicon', 'branding_default_flow_background', 'flow_authentication', 'flow_user_switch', 'flow_invalidation', 'flow_recovery', 'flow_unenrollment', 'flow_user_settings', 'flow_device_code', 'flow_lockdown', 'flow_request', 'web_certificate', 'client_certificates']
ordering = ['domain']
filter_backends = [<class 'authentik.rbac.filters.SecretKeyFilter'>, <class 'rest_framework.filters.OrderingFilter'>, <class 'rest_framework.filters.SearchFilter'>]
@extend_schema(responses=CurrentBrandSerializer(many=False))
@action(methods=['GET'], detail=False, permission_classes=[AllowAny])
def current( self, request: rest_framework.request.Request) -> rest_framework.response.Response:
223    @extend_schema(
224        responses=CurrentBrandSerializer(many=False),
225    )
226    @action(methods=["GET"], detail=False, permission_classes=[AllowAny])
227    def current(self, request: Request) -> Response:
228        """Get current brand"""
229        brand: Brand = request._request.brand
230        return Response(CurrentBrandSerializer(brand, context={"request": request}).data)

Get current brand

name = None
description = None
suffix = None
detail = None
basename = None