authentik.brands.utils
Brand utilities
1"""Brand utilities""" 2 3from typing import Any 4 5from django.db.models import Case, F, IntegerField, Q, Value, When 6from django.db.models.functions import Concat, Length 7from django.http.request import HttpRequest 8from django.utils.html import _json_script_escapes 9from django.utils.safestring import mark_safe 10 11from authentik import authentik_full_version 12from authentik.admin.models import SystemSettings 13from authentik.admin.utils import get_system_settings 14from authentik.brands.models import _BRAND_RELATED_FK_FIELDS, SESSION_KEY_BRAND_SAFE_MODE, Brand 15from authentik.lib.config import CONFIG 16from authentik.lib.tracing import active_tracer 17from authentik.root.cache import in_memory_cache 18 19_q_default = Q(default=True) 20DEFAULT_BRAND = Brand(domain="fallback") 21 22 23def session_safe_mode(request: HttpRequest) -> bool: 24 """Whether the current session is in brand "safe mode" (e.g. created via a recovery 25 link), in which case lock-out-prone customization such as custom CSS are suppressed.""" 26 session = getattr(request, "session", None) 27 if session is None: 28 return False 29 return bool(session.get(SESSION_KEY_BRAND_SAFE_MODE)) 30 31 32@in_memory_cache( 33 key=lambda request: request.get_host(), timeout=CONFIG.get_int("cache.timeout_brands", 30) 34) 35def get_brand_for_request(request: HttpRequest) -> Brand: 36 """Get brand object for current request""" 37 38 brand = ( 39 Brand.objects.select_related(*_BRAND_RELATED_FK_FIELDS) 40 .annotate( 41 host_domain=Value(request.get_host()), 42 domain_length=Length("domain"), 43 match_priority=Case( 44 When( 45 condition=Q(host_domain__iexact=F("domain")) 46 | Q(host_domain__iendswith=Concat(Value("."), F("domain"))), 47 then=F("domain_length"), 48 ), 49 default=Value(-1), 50 output_field=IntegerField(), 51 ), 52 is_default_fallback=Case( 53 When( 54 condition=Q(default=True), 55 then=Value(0), 56 ), 57 default=Value(-2), 58 output_field=IntegerField(), 59 ), 60 ) 61 .filter(Q(match_priority__gt=-1) | Q(default=True)) 62 .order_by("-match_priority", "-is_default_fallback") 63 .first() 64 ) 65 66 if brand is None: 67 return DEFAULT_BRAND 68 return brand 69 70 71def context_processor(request: HttpRequest) -> dict[str, Any]: 72 """Context Processor that injects brand object into every template""" 73 brand = getattr(request, "brand", DEFAULT_BRAND) 74 try: 75 footer_links = get_system_settings().footer_links 76 except SystemSettings.DoesNotExist: 77 footer_links = [] 78 # Suppress custom CSS for safe-mode sessions so misconfigured branding can't lock a 79 # user out of the UI needed to fix it. 80 safe_mode = session_safe_mode(request) 81 custom_css = "" if safe_mode else str(brand.branding_custom_css) 82 # similarly to `json_script` we escape everything HTML-related, however django 83 # only directly exposes this as a function that also wraps it in a <script> tag 84 # which we dont want for CSS 85 brand_css = mark_safe(custom_css.translate(_json_script_escapes)) # nosec 86 return { 87 "brand": brand, 88 "brand_css": brand_css, 89 "safe_mode": safe_mode, 90 "footer_links": footer_links, 91 "html_meta": {**active_tracer().get_http_meta()}, 92 "version": authentik_full_version(), 93 }
DEFAULT_BRAND =
<Brand: Brand fallback>
def
session_safe_mode(request: django.http.request.HttpRequest) -> bool:
24def session_safe_mode(request: HttpRequest) -> bool: 25 """Whether the current session is in brand "safe mode" (e.g. created via a recovery 26 link), in which case lock-out-prone customization such as custom CSS are suppressed.""" 27 session = getattr(request, "session", None) 28 if session is None: 29 return False 30 return bool(session.get(SESSION_KEY_BRAND_SAFE_MODE))
Whether the current session is in brand "safe mode" (e.g. created via a recovery link), in which case lock-out-prone customization such as custom CSS are suppressed.
@in_memory_cache(key=lambda request: request.get_host(), timeout=CONFIG.get_int('cache.timeout_brands', 30))
def
get_brand_for_request( request: django.http.request.HttpRequest) -> authentik.brands.models.Brand:
33@in_memory_cache( 34 key=lambda request: request.get_host(), timeout=CONFIG.get_int("cache.timeout_brands", 30) 35) 36def get_brand_for_request(request: HttpRequest) -> Brand: 37 """Get brand object for current request""" 38 39 brand = ( 40 Brand.objects.select_related(*_BRAND_RELATED_FK_FIELDS) 41 .annotate( 42 host_domain=Value(request.get_host()), 43 domain_length=Length("domain"), 44 match_priority=Case( 45 When( 46 condition=Q(host_domain__iexact=F("domain")) 47 | Q(host_domain__iendswith=Concat(Value("."), F("domain"))), 48 then=F("domain_length"), 49 ), 50 default=Value(-1), 51 output_field=IntegerField(), 52 ), 53 is_default_fallback=Case( 54 When( 55 condition=Q(default=True), 56 then=Value(0), 57 ), 58 default=Value(-2), 59 output_field=IntegerField(), 60 ), 61 ) 62 .filter(Q(match_priority__gt=-1) | Q(default=True)) 63 .order_by("-match_priority", "-is_default_fallback") 64 .first() 65 ) 66 67 if brand is None: 68 return DEFAULT_BRAND 69 return brand
Get brand object for current request
def
context_processor(request: django.http.request.HttpRequest) -> dict[str, typing.Any]:
72def context_processor(request: HttpRequest) -> dict[str, Any]: 73 """Context Processor that injects brand object into every template""" 74 brand = getattr(request, "brand", DEFAULT_BRAND) 75 try: 76 footer_links = get_system_settings().footer_links 77 except SystemSettings.DoesNotExist: 78 footer_links = [] 79 # Suppress custom CSS for safe-mode sessions so misconfigured branding can't lock a 80 # user out of the UI needed to fix it. 81 safe_mode = session_safe_mode(request) 82 custom_css = "" if safe_mode else str(brand.branding_custom_css) 83 # similarly to `json_script` we escape everything HTML-related, however django 84 # only directly exposes this as a function that also wraps it in a <script> tag 85 # which we dont want for CSS 86 brand_css = mark_safe(custom_css.translate(_json_script_escapes)) # nosec 87 return { 88 "brand": brand, 89 "brand_css": brand_css, 90 "safe_mode": safe_mode, 91 "footer_links": footer_links, 92 "html_meta": {**active_tracer().get_http_meta()}, 93 "version": authentik_full_version(), 94 }
Context Processor that injects brand object into every template