authentik.stages.prompt.models
prompt models
1"""prompt models""" 2 3from typing import Any, Type # noqa: UP035 4from urllib.parse import urlparse, urlunparse 5from uuid import uuid4 6 7from django.db import models 8from django.http import HttpRequest 9from django.utils.translation import gettext_lazy as _ 10from django.views import View 11from rest_framework.exceptions import ValidationError 12from rest_framework.fields import ( 13 BooleanField, 14 CharField, 15 ChoiceField, 16 DateField, 17 DateTimeField, 18 EmailField, 19 HiddenField, 20 IntegerField, 21) 22from rest_framework.serializers import BaseSerializer 23from structlog.stdlib import get_logger 24 25from authentik.core.expression.evaluator import PropertyMappingEvaluator 26from authentik.core.expression.exceptions import PropertyMappingExpressionException 27from authentik.core.models import User 28from authentik.flows.models import Stage 29from authentik.lib.models import SerializerModel, SimpleThroughModel 30from authentik.policies.models import Policy 31 32CHOICES_CONTEXT_SUFFIX = "__choices" 33 34LOGGER = get_logger() 35 36 37class FieldTypes(models.TextChoices): 38 """Field types an Prompt can be""" 39 40 # update website/docs/add-secure-apps/flows-stages/stages/prompt/index.mdx 41 42 # Simple text field 43 TEXT = "text", _("Text: Simple Text input") 44 # Long text field 45 TEXT_AREA = "text_area", _("Text area: Multiline Text Input.") 46 # Simple text field 47 TEXT_READ_ONLY = "text_read_only", _( 48 "Text (read-only): Simple Text input, but cannot be edited." 49 ) 50 # Long text field 51 TEXT_AREA_READ_ONLY = "text_area_read_only", _( 52 "Text area (read-only): Multiline Text input, but cannot be edited." 53 ) 54 55 # Same as text, but has autocomplete for password managers 56 USERNAME = ( 57 "username", 58 _("Username: Same as Text input, but checks for and prevents duplicate usernames."), 59 ) 60 EMAIL = "email", _("Email: Text field with Email type.") 61 PASSWORD = ( 62 "password", # noqa # nosec 63 _( 64 "Password: Masked input, multiple inputs of this type on the same prompt " 65 "need to be identical." 66 ), 67 ) 68 PASSWORD_VIEWABLE = ( 69 "password_viewable", 70 _( 71 "Password with show button: Masked input w/show button, multiple inputs of this type" 72 " on the same prompt need to be identical." 73 ), 74 ) 75 NUMBER = "number" 76 CHECKBOX = "checkbox" 77 RADIO_BUTTON_GROUP = "radio-button-group", _( 78 "Fixed choice field rendered as a group of radio buttons." 79 ) 80 DROPDOWN = "dropdown", _("Fixed choice field rendered as a dropdown.") 81 DATE = "date" 82 DATE_TIME = "date-time" 83 84 FILE = ( 85 "file", 86 _( 87 "File: File upload for arbitrary files. File content will be available in flow " 88 "context as data-URI" 89 ), 90 ) 91 92 SEPARATOR = "separator", _("Separator: Static Separator Line") 93 HIDDEN = "hidden", _("Hidden: Hidden field, can be used to insert data into form.") 94 STATIC = "static", _("Static: Static value, displayed as-is.") 95 96 # Alert box types for displaying styled messages 97 ALERT_INFO = "alert_info", _("Alert (Info): Static alert box with info styling") 98 ALERT_WARNING = "alert_warning", _("Alert (Warning): Static alert box with warning styling") 99 ALERT_DANGER = "alert_danger", _("Alert (Danger): Static alert box with danger styling") 100 101 AK_LOCALE = "ak-locale", _("authentik: Selection of locales authentik supports") 102 103 104CHOICE_FIELDS = (FieldTypes.RADIO_BUTTON_GROUP, FieldTypes.DROPDOWN) 105 106 107class InlineFileField(CharField): 108 """Field for inline data-URI base64 encoded files""" 109 110 def to_internal_value(self, data: str): 111 uri = urlparse(data) 112 if uri.scheme != "data": 113 raise ValidationError("Invalid scheme") 114 header, _encoded = uri.path.split(",", 1) 115 _mime, _, enc = header.partition(";") 116 if enc != "base64": 117 raise ValidationError("Invalid encoding") 118 return super().to_internal_value(urlunparse(uri)) 119 120 121class Prompt(SerializerModel): 122 """Single Prompt, part of a prompt stage.""" 123 124 prompt_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4) 125 name = models.TextField(unique=True, blank=False) 126 127 field_key = models.TextField( 128 help_text=_("Name of the form field, also used to store the value") 129 ) 130 label = models.TextField() 131 type = models.CharField(max_length=100, choices=FieldTypes.choices) 132 required = models.BooleanField(default=True) 133 placeholder = models.TextField( 134 blank=True, 135 help_text=_( 136 "Optionally provide a short hint that describes the expected input value. " 137 "When creating a fixed choice field, enable interpreting as " 138 "expression and return a list to return multiple choices." 139 ), 140 ) 141 initial_value = models.TextField( 142 blank=True, 143 help_text=_( 144 "Optionally pre-fill the input with an initial value. " 145 "When creating a fixed choice field, enable interpreting as " 146 "expression and return a list to return multiple default choices." 147 ), 148 ) 149 sub_text = models.TextField(blank=True, default="") 150 151 order = models.IntegerField(default=0) 152 153 placeholder_expression = models.BooleanField(default=False) 154 initial_value_expression = models.BooleanField(default=False) 155 156 @property 157 def serializer(self) -> Type[BaseSerializer]: # noqa: UP006 158 from authentik.stages.prompt.api import PromptSerializer 159 160 return PromptSerializer 161 162 def get_choices( 163 self, 164 prompt_context: dict, 165 user: User, 166 request: HttpRequest, 167 dry_run: bool | None = False, 168 ) -> tuple[dict[str, Any]] | None: 169 """Get fully interpolated list of choices""" 170 if self.type not in CHOICE_FIELDS: 171 return None 172 173 raw_choices = self.placeholder 174 175 if self.field_key + CHOICES_CONTEXT_SUFFIX in prompt_context: 176 raw_choices = prompt_context[self.field_key + CHOICES_CONTEXT_SUFFIX] 177 elif self.placeholder_expression: 178 evaluator = PropertyMappingEvaluator( 179 self, user, request, prompt_context=prompt_context, dry_run=dry_run 180 ) 181 try: 182 raw_choices = evaluator.evaluate(self.placeholder) 183 except Exception as exc: # pylint:disable=broad-except 184 wrapped = PropertyMappingExpressionException(exc, None) 185 LOGGER.warning( 186 "failed to evaluate prompt choices", 187 exc=wrapped, 188 ) 189 if dry_run: 190 raise wrapped from exc 191 192 if isinstance(raw_choices, list | tuple | set): 193 choices = raw_choices 194 else: 195 choices = [raw_choices] 196 197 if len(choices) == 0: 198 LOGGER.warning("failed to get prompt choices", choices=choices, input=raw_choices) 199 200 return tuple(choices) 201 202 def get_placeholder( 203 self, 204 prompt_context: dict, 205 user: User, 206 request: HttpRequest, 207 dry_run: bool | None = False, 208 ) -> str: 209 """Get fully interpolated placeholder""" 210 if self.type in CHOICE_FIELDS: 211 # Choice fields use the placeholder to define all valid choices. 212 # Therefore their actual placeholder is always blank 213 return "" 214 215 if self.placeholder_expression: 216 evaluator = PropertyMappingEvaluator( 217 self, user, request, prompt_context=prompt_context, dry_run=dry_run 218 ) 219 try: 220 return evaluator.evaluate(self.placeholder) 221 except Exception as exc: # pylint:disable=broad-except 222 wrapped = PropertyMappingExpressionException(exc, None) 223 LOGGER.warning( 224 "failed to evaluate prompt placeholder", 225 exc=wrapped, 226 ) 227 if dry_run: 228 raise wrapped from exc 229 return self.placeholder 230 231 def get_initial_value( 232 self, 233 prompt_context: dict, 234 user: User, 235 request: HttpRequest, 236 dry_run: bool | None = False, 237 ) -> str: 238 """Get fully interpolated initial value""" 239 240 if self.field_key in prompt_context: 241 # We don't want to parse this as an expression since a user will 242 # be able to control the input 243 value = prompt_context[self.field_key] 244 elif self.initial_value_expression: 245 evaluator = PropertyMappingEvaluator( 246 self, user, request, prompt_context=prompt_context, dry_run=dry_run 247 ) 248 try: 249 value = evaluator.evaluate(self.initial_value) 250 except Exception as exc: # pylint:disable=broad-except 251 wrapped = PropertyMappingExpressionException(exc, None) 252 LOGGER.warning( 253 "failed to evaluate prompt initial value", 254 exc=wrapped, 255 ) 256 if dry_run: 257 raise wrapped from exc 258 value = self.initial_value 259 else: 260 value = self.initial_value 261 262 if self.type in CHOICE_FIELDS: 263 # Ensure returned value is a valid choice 264 choices = self.get_choices(prompt_context, user, request) 265 if not choices: 266 return "" 267 if not any( 268 choice.get("value") == value if isinstance(choice, dict) else choice == value 269 for choice in choices 270 ): 271 return choices[0] 272 273 return value 274 275 def field( # noqa PLR0915 276 self, default: Any | None, choices: list[Any] | None = None 277 ) -> CharField: 278 """Get field type for Challenge and response. Choices are only valid for CHOICE_FIELDS.""" 279 field_class = CharField 280 kwargs = { 281 "required": self.required, 282 } 283 match self.type: 284 case FieldTypes.TEXT | FieldTypes.TEXT_AREA: 285 kwargs["trim_whitespace"] = False 286 kwargs["allow_blank"] = not self.required 287 case FieldTypes.TEXT_READ_ONLY | FieldTypes.TEXT_AREA_READ_ONLY: 288 kwargs["required"] = False 289 kwargs["allow_blank"] = True 290 case FieldTypes.EMAIL: 291 field_class = EmailField 292 kwargs["allow_blank"] = not self.required 293 case FieldTypes.NUMBER: 294 field_class = IntegerField 295 case FieldTypes.CHECKBOX: 296 field_class = BooleanField 297 kwargs["required"] = False 298 case FieldTypes.DATE: 299 field_class = DateField 300 case FieldTypes.DATE_TIME: 301 field_class = DateTimeField 302 case FieldTypes.FILE: 303 field_class = InlineFileField 304 case FieldTypes.SEPARATOR: 305 kwargs["required"] = False 306 kwargs["label"] = "" 307 case FieldTypes.HIDDEN: 308 field_class = HiddenField 309 kwargs["required"] = False 310 kwargs["default"] = self.placeholder 311 case ( 312 FieldTypes.STATIC 313 | FieldTypes.ALERT_INFO 314 | FieldTypes.ALERT_WARNING 315 | FieldTypes.ALERT_DANGER 316 ): 317 kwargs["default"] = self.placeholder 318 kwargs["required"] = False 319 kwargs["label"] = "" 320 321 case FieldTypes.AK_LOCALE: 322 kwargs["allow_blank"] = True 323 324 if self.type in CHOICE_FIELDS: 325 field_class = ChoiceField 326 kwargs["choices"] = [] 327 if choices: 328 for choice in choices: 329 label, value = choice, choice 330 if isinstance(choice, dict): 331 label = choice.get("label", "") 332 value = choice.get("value", "") 333 kwargs["choices"].append((value, label)) 334 335 if default is not None: 336 kwargs["default"] = default 337 # May not set both `required` and `default` 338 if "default" in kwargs: 339 kwargs.pop("required", None) 340 return field_class(**kwargs) 341 342 def save(self, *args, **kwargs): 343 if self.type not in FieldTypes: 344 raise ValueError 345 return super().save(*args, **kwargs) 346 347 def __str__(self): 348 return f"Prompt field '{self.field_key}' type {self.type}" 349 350 class Meta: 351 verbose_name = _("Prompt") 352 verbose_name_plural = _("Prompts") 353 354 355class PromptStage(Stage): 356 """Prompt the user to enter information.""" 357 358 fields = models.ManyToManyField(Prompt, through="PromptStageField") 359 360 validation_policies = models.ManyToManyField( 361 Policy, blank=True, through="PromptStageValidationPolicy" 362 ) 363 364 @property 365 def serializer(self) -> type[BaseSerializer]: 366 from authentik.stages.prompt.api import PromptStageSerializer 367 368 return PromptStageSerializer 369 370 @property 371 def view(self) -> type[View]: 372 from authentik.stages.prompt.stage import PromptStageView 373 374 return PromptStageView 375 376 @property 377 def component(self) -> str: 378 return "ak-stage-prompt-form" 379 380 class Meta: 381 verbose_name = _("Prompt Stage") 382 verbose_name_plural = _("Prompt Stages") 383 384 385class PromptStageField(SimpleThroughModel): 386 prompt_stage = models.ForeignKey( 387 PromptStage, 388 on_delete=models.CASCADE, 389 db_column="promptstage_id", 390 ) 391 prompt = models.ForeignKey(Prompt, on_delete=models.CASCADE) 392 393 class Meta: 394 db_table = "authentik_stages_prompt_promptstage_fields" 395 unique_together = (("prompt_stage", "prompt"),) 396 verbose_name = _("Prompt Stage Field") 397 verbose_name_plural = _("Prompt Stage Fields") 398 399 def __str__(self): 400 return ( 401 f"PromptStageField for PromptStage {self.prompt_stage_id} " 402 f"and Field {self.prompt_id}." 403 ) 404 405 406class PromptStageValidationPolicy(SimpleThroughModel): 407 prompt_stage = models.ForeignKey( 408 PromptStage, 409 on_delete=models.CASCADE, 410 db_column="promptstage_id", 411 ) 412 policy = models.ForeignKey(Policy, on_delete=models.CASCADE) 413 414 class Meta: 415 db_table = "authentik_stages_prompt_promptstage_validation_policies" 416 unique_together = (("prompt_stage", "policy"),) 417 verbose_name = _("Prompt Stage Validation Policy") 418 verbose_name_plural = _("Prompt Stage Validation Policys") 419 420 def __str__(self): 421 return ( 422 f"PromptStageValidationPolicy for PromptStage {self.prompt_stage_id} " 423 f"and Policy {self.policy_id}." 424 )
38class FieldTypes(models.TextChoices): 39 """Field types an Prompt can be""" 40 41 # update website/docs/add-secure-apps/flows-stages/stages/prompt/index.mdx 42 43 # Simple text field 44 TEXT = "text", _("Text: Simple Text input") 45 # Long text field 46 TEXT_AREA = "text_area", _("Text area: Multiline Text Input.") 47 # Simple text field 48 TEXT_READ_ONLY = "text_read_only", _( 49 "Text (read-only): Simple Text input, but cannot be edited." 50 ) 51 # Long text field 52 TEXT_AREA_READ_ONLY = "text_area_read_only", _( 53 "Text area (read-only): Multiline Text input, but cannot be edited." 54 ) 55 56 # Same as text, but has autocomplete for password managers 57 USERNAME = ( 58 "username", 59 _("Username: Same as Text input, but checks for and prevents duplicate usernames."), 60 ) 61 EMAIL = "email", _("Email: Text field with Email type.") 62 PASSWORD = ( 63 "password", # noqa # nosec 64 _( 65 "Password: Masked input, multiple inputs of this type on the same prompt " 66 "need to be identical." 67 ), 68 ) 69 PASSWORD_VIEWABLE = ( 70 "password_viewable", 71 _( 72 "Password with show button: Masked input w/show button, multiple inputs of this type" 73 " on the same prompt need to be identical." 74 ), 75 ) 76 NUMBER = "number" 77 CHECKBOX = "checkbox" 78 RADIO_BUTTON_GROUP = "radio-button-group", _( 79 "Fixed choice field rendered as a group of radio buttons." 80 ) 81 DROPDOWN = "dropdown", _("Fixed choice field rendered as a dropdown.") 82 DATE = "date" 83 DATE_TIME = "date-time" 84 85 FILE = ( 86 "file", 87 _( 88 "File: File upload for arbitrary files. File content will be available in flow " 89 "context as data-URI" 90 ), 91 ) 92 93 SEPARATOR = "separator", _("Separator: Static Separator Line") 94 HIDDEN = "hidden", _("Hidden: Hidden field, can be used to insert data into form.") 95 STATIC = "static", _("Static: Static value, displayed as-is.") 96 97 # Alert box types for displaying styled messages 98 ALERT_INFO = "alert_info", _("Alert (Info): Static alert box with info styling") 99 ALERT_WARNING = "alert_warning", _("Alert (Warning): Static alert box with warning styling") 100 ALERT_DANGER = "alert_danger", _("Alert (Danger): Static alert box with danger styling") 101 102 AK_LOCALE = "ak-locale", _("authentik: Selection of locales authentik supports")
Field types an Prompt can be
108class InlineFileField(CharField): 109 """Field for inline data-URI base64 encoded files""" 110 111 def to_internal_value(self, data: str): 112 uri = urlparse(data) 113 if uri.scheme != "data": 114 raise ValidationError("Invalid scheme") 115 header, _encoded = uri.path.split(",", 1) 116 _mime, _, enc = header.partition(";") 117 if enc != "base64": 118 raise ValidationError("Invalid encoding") 119 return super().to_internal_value(urlunparse(uri))
Field for inline data-URI base64 encoded files
111 def to_internal_value(self, data: str): 112 uri = urlparse(data) 113 if uri.scheme != "data": 114 raise ValidationError("Invalid scheme") 115 header, _encoded = uri.path.split(",", 1) 116 _mime, _, enc = header.partition(";") 117 if enc != "base64": 118 raise ValidationError("Invalid encoding") 119 return super().to_internal_value(urlunparse(uri))
Transform the incoming primitive data into a native value.
122class Prompt(SerializerModel): 123 """Single Prompt, part of a prompt stage.""" 124 125 prompt_uuid = models.UUIDField(primary_key=True, editable=False, default=uuid4) 126 name = models.TextField(unique=True, blank=False) 127 128 field_key = models.TextField( 129 help_text=_("Name of the form field, also used to store the value") 130 ) 131 label = models.TextField() 132 type = models.CharField(max_length=100, choices=FieldTypes.choices) 133 required = models.BooleanField(default=True) 134 placeholder = models.TextField( 135 blank=True, 136 help_text=_( 137 "Optionally provide a short hint that describes the expected input value. " 138 "When creating a fixed choice field, enable interpreting as " 139 "expression and return a list to return multiple choices." 140 ), 141 ) 142 initial_value = models.TextField( 143 blank=True, 144 help_text=_( 145 "Optionally pre-fill the input with an initial value. " 146 "When creating a fixed choice field, enable interpreting as " 147 "expression and return a list to return multiple default choices." 148 ), 149 ) 150 sub_text = models.TextField(blank=True, default="") 151 152 order = models.IntegerField(default=0) 153 154 placeholder_expression = models.BooleanField(default=False) 155 initial_value_expression = models.BooleanField(default=False) 156 157 @property 158 def serializer(self) -> Type[BaseSerializer]: # noqa: UP006 159 from authentik.stages.prompt.api import PromptSerializer 160 161 return PromptSerializer 162 163 def get_choices( 164 self, 165 prompt_context: dict, 166 user: User, 167 request: HttpRequest, 168 dry_run: bool | None = False, 169 ) -> tuple[dict[str, Any]] | None: 170 """Get fully interpolated list of choices""" 171 if self.type not in CHOICE_FIELDS: 172 return None 173 174 raw_choices = self.placeholder 175 176 if self.field_key + CHOICES_CONTEXT_SUFFIX in prompt_context: 177 raw_choices = prompt_context[self.field_key + CHOICES_CONTEXT_SUFFIX] 178 elif self.placeholder_expression: 179 evaluator = PropertyMappingEvaluator( 180 self, user, request, prompt_context=prompt_context, dry_run=dry_run 181 ) 182 try: 183 raw_choices = evaluator.evaluate(self.placeholder) 184 except Exception as exc: # pylint:disable=broad-except 185 wrapped = PropertyMappingExpressionException(exc, None) 186 LOGGER.warning( 187 "failed to evaluate prompt choices", 188 exc=wrapped, 189 ) 190 if dry_run: 191 raise wrapped from exc 192 193 if isinstance(raw_choices, list | tuple | set): 194 choices = raw_choices 195 else: 196 choices = [raw_choices] 197 198 if len(choices) == 0: 199 LOGGER.warning("failed to get prompt choices", choices=choices, input=raw_choices) 200 201 return tuple(choices) 202 203 def get_placeholder( 204 self, 205 prompt_context: dict, 206 user: User, 207 request: HttpRequest, 208 dry_run: bool | None = False, 209 ) -> str: 210 """Get fully interpolated placeholder""" 211 if self.type in CHOICE_FIELDS: 212 # Choice fields use the placeholder to define all valid choices. 213 # Therefore their actual placeholder is always blank 214 return "" 215 216 if self.placeholder_expression: 217 evaluator = PropertyMappingEvaluator( 218 self, user, request, prompt_context=prompt_context, dry_run=dry_run 219 ) 220 try: 221 return evaluator.evaluate(self.placeholder) 222 except Exception as exc: # pylint:disable=broad-except 223 wrapped = PropertyMappingExpressionException(exc, None) 224 LOGGER.warning( 225 "failed to evaluate prompt placeholder", 226 exc=wrapped, 227 ) 228 if dry_run: 229 raise wrapped from exc 230 return self.placeholder 231 232 def get_initial_value( 233 self, 234 prompt_context: dict, 235 user: User, 236 request: HttpRequest, 237 dry_run: bool | None = False, 238 ) -> str: 239 """Get fully interpolated initial value""" 240 241 if self.field_key in prompt_context: 242 # We don't want to parse this as an expression since a user will 243 # be able to control the input 244 value = prompt_context[self.field_key] 245 elif self.initial_value_expression: 246 evaluator = PropertyMappingEvaluator( 247 self, user, request, prompt_context=prompt_context, dry_run=dry_run 248 ) 249 try: 250 value = evaluator.evaluate(self.initial_value) 251 except Exception as exc: # pylint:disable=broad-except 252 wrapped = PropertyMappingExpressionException(exc, None) 253 LOGGER.warning( 254 "failed to evaluate prompt initial value", 255 exc=wrapped, 256 ) 257 if dry_run: 258 raise wrapped from exc 259 value = self.initial_value 260 else: 261 value = self.initial_value 262 263 if self.type in CHOICE_FIELDS: 264 # Ensure returned value is a valid choice 265 choices = self.get_choices(prompt_context, user, request) 266 if not choices: 267 return "" 268 if not any( 269 choice.get("value") == value if isinstance(choice, dict) else choice == value 270 for choice in choices 271 ): 272 return choices[0] 273 274 return value 275 276 def field( # noqa PLR0915 277 self, default: Any | None, choices: list[Any] | None = None 278 ) -> CharField: 279 """Get field type for Challenge and response. Choices are only valid for CHOICE_FIELDS.""" 280 field_class = CharField 281 kwargs = { 282 "required": self.required, 283 } 284 match self.type: 285 case FieldTypes.TEXT | FieldTypes.TEXT_AREA: 286 kwargs["trim_whitespace"] = False 287 kwargs["allow_blank"] = not self.required 288 case FieldTypes.TEXT_READ_ONLY | FieldTypes.TEXT_AREA_READ_ONLY: 289 kwargs["required"] = False 290 kwargs["allow_blank"] = True 291 case FieldTypes.EMAIL: 292 field_class = EmailField 293 kwargs["allow_blank"] = not self.required 294 case FieldTypes.NUMBER: 295 field_class = IntegerField 296 case FieldTypes.CHECKBOX: 297 field_class = BooleanField 298 kwargs["required"] = False 299 case FieldTypes.DATE: 300 field_class = DateField 301 case FieldTypes.DATE_TIME: 302 field_class = DateTimeField 303 case FieldTypes.FILE: 304 field_class = InlineFileField 305 case FieldTypes.SEPARATOR: 306 kwargs["required"] = False 307 kwargs["label"] = "" 308 case FieldTypes.HIDDEN: 309 field_class = HiddenField 310 kwargs["required"] = False 311 kwargs["default"] = self.placeholder 312 case ( 313 FieldTypes.STATIC 314 | FieldTypes.ALERT_INFO 315 | FieldTypes.ALERT_WARNING 316 | FieldTypes.ALERT_DANGER 317 ): 318 kwargs["default"] = self.placeholder 319 kwargs["required"] = False 320 kwargs["label"] = "" 321 322 case FieldTypes.AK_LOCALE: 323 kwargs["allow_blank"] = True 324 325 if self.type in CHOICE_FIELDS: 326 field_class = ChoiceField 327 kwargs["choices"] = [] 328 if choices: 329 for choice in choices: 330 label, value = choice, choice 331 if isinstance(choice, dict): 332 label = choice.get("label", "") 333 value = choice.get("value", "") 334 kwargs["choices"].append((value, label)) 335 336 if default is not None: 337 kwargs["default"] = default 338 # May not set both `required` and `default` 339 if "default" in kwargs: 340 kwargs.pop("required", None) 341 return field_class(**kwargs) 342 343 def save(self, *args, **kwargs): 344 if self.type not in FieldTypes: 345 raise ValueError 346 return super().save(*args, **kwargs) 347 348 def __str__(self): 349 return f"Prompt field '{self.field_key}' type {self.type}" 350 351 class Meta: 352 verbose_name = _("Prompt") 353 verbose_name_plural = _("Prompts")
Single Prompt, part of a prompt stage.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
157 @property 158 def serializer(self) -> Type[BaseSerializer]: # noqa: UP006 159 from authentik.stages.prompt.api import PromptSerializer 160 161 return PromptSerializer
Get serializer for this model
163 def get_choices( 164 self, 165 prompt_context: dict, 166 user: User, 167 request: HttpRequest, 168 dry_run: bool | None = False, 169 ) -> tuple[dict[str, Any]] | None: 170 """Get fully interpolated list of choices""" 171 if self.type not in CHOICE_FIELDS: 172 return None 173 174 raw_choices = self.placeholder 175 176 if self.field_key + CHOICES_CONTEXT_SUFFIX in prompt_context: 177 raw_choices = prompt_context[self.field_key + CHOICES_CONTEXT_SUFFIX] 178 elif self.placeholder_expression: 179 evaluator = PropertyMappingEvaluator( 180 self, user, request, prompt_context=prompt_context, dry_run=dry_run 181 ) 182 try: 183 raw_choices = evaluator.evaluate(self.placeholder) 184 except Exception as exc: # pylint:disable=broad-except 185 wrapped = PropertyMappingExpressionException(exc, None) 186 LOGGER.warning( 187 "failed to evaluate prompt choices", 188 exc=wrapped, 189 ) 190 if dry_run: 191 raise wrapped from exc 192 193 if isinstance(raw_choices, list | tuple | set): 194 choices = raw_choices 195 else: 196 choices = [raw_choices] 197 198 if len(choices) == 0: 199 LOGGER.warning("failed to get prompt choices", choices=choices, input=raw_choices) 200 201 return tuple(choices)
Get fully interpolated list of choices
203 def get_placeholder( 204 self, 205 prompt_context: dict, 206 user: User, 207 request: HttpRequest, 208 dry_run: bool | None = False, 209 ) -> str: 210 """Get fully interpolated placeholder""" 211 if self.type in CHOICE_FIELDS: 212 # Choice fields use the placeholder to define all valid choices. 213 # Therefore their actual placeholder is always blank 214 return "" 215 216 if self.placeholder_expression: 217 evaluator = PropertyMappingEvaluator( 218 self, user, request, prompt_context=prompt_context, dry_run=dry_run 219 ) 220 try: 221 return evaluator.evaluate(self.placeholder) 222 except Exception as exc: # pylint:disable=broad-except 223 wrapped = PropertyMappingExpressionException(exc, None) 224 LOGGER.warning( 225 "failed to evaluate prompt placeholder", 226 exc=wrapped, 227 ) 228 if dry_run: 229 raise wrapped from exc 230 return self.placeholder
Get fully interpolated placeholder
232 def get_initial_value( 233 self, 234 prompt_context: dict, 235 user: User, 236 request: HttpRequest, 237 dry_run: bool | None = False, 238 ) -> str: 239 """Get fully interpolated initial value""" 240 241 if self.field_key in prompt_context: 242 # We don't want to parse this as an expression since a user will 243 # be able to control the input 244 value = prompt_context[self.field_key] 245 elif self.initial_value_expression: 246 evaluator = PropertyMappingEvaluator( 247 self, user, request, prompt_context=prompt_context, dry_run=dry_run 248 ) 249 try: 250 value = evaluator.evaluate(self.initial_value) 251 except Exception as exc: # pylint:disable=broad-except 252 wrapped = PropertyMappingExpressionException(exc, None) 253 LOGGER.warning( 254 "failed to evaluate prompt initial value", 255 exc=wrapped, 256 ) 257 if dry_run: 258 raise wrapped from exc 259 value = self.initial_value 260 else: 261 value = self.initial_value 262 263 if self.type in CHOICE_FIELDS: 264 # Ensure returned value is a valid choice 265 choices = self.get_choices(prompt_context, user, request) 266 if not choices: 267 return "" 268 if not any( 269 choice.get("value") == value if isinstance(choice, dict) else choice == value 270 for choice in choices 271 ): 272 return choices[0] 273 274 return value
Get fully interpolated initial value
276 def field( # noqa PLR0915 277 self, default: Any | None, choices: list[Any] | None = None 278 ) -> CharField: 279 """Get field type for Challenge and response. Choices are only valid for CHOICE_FIELDS.""" 280 field_class = CharField 281 kwargs = { 282 "required": self.required, 283 } 284 match self.type: 285 case FieldTypes.TEXT | FieldTypes.TEXT_AREA: 286 kwargs["trim_whitespace"] = False 287 kwargs["allow_blank"] = not self.required 288 case FieldTypes.TEXT_READ_ONLY | FieldTypes.TEXT_AREA_READ_ONLY: 289 kwargs["required"] = False 290 kwargs["allow_blank"] = True 291 case FieldTypes.EMAIL: 292 field_class = EmailField 293 kwargs["allow_blank"] = not self.required 294 case FieldTypes.NUMBER: 295 field_class = IntegerField 296 case FieldTypes.CHECKBOX: 297 field_class = BooleanField 298 kwargs["required"] = False 299 case FieldTypes.DATE: 300 field_class = DateField 301 case FieldTypes.DATE_TIME: 302 field_class = DateTimeField 303 case FieldTypes.FILE: 304 field_class = InlineFileField 305 case FieldTypes.SEPARATOR: 306 kwargs["required"] = False 307 kwargs["label"] = "" 308 case FieldTypes.HIDDEN: 309 field_class = HiddenField 310 kwargs["required"] = False 311 kwargs["default"] = self.placeholder 312 case ( 313 FieldTypes.STATIC 314 | FieldTypes.ALERT_INFO 315 | FieldTypes.ALERT_WARNING 316 | FieldTypes.ALERT_DANGER 317 ): 318 kwargs["default"] = self.placeholder 319 kwargs["required"] = False 320 kwargs["label"] = "" 321 322 case FieldTypes.AK_LOCALE: 323 kwargs["allow_blank"] = True 324 325 if self.type in CHOICE_FIELDS: 326 field_class = ChoiceField 327 kwargs["choices"] = [] 328 if choices: 329 for choice in choices: 330 label, value = choice, choice 331 if isinstance(choice, dict): 332 label = choice.get("label", "") 333 value = choice.get("value", "") 334 kwargs["choices"].append((value, label)) 335 336 if default is not None: 337 kwargs["default"] = default 338 # May not set both `required` and `default` 339 if "default" in kwargs: 340 kwargs.pop("required", None) 341 return field_class(**kwargs)
Get field type for Challenge and response. Choices are only valid for CHOICE_FIELDS.
343 def save(self, *args, **kwargs): 344 if self.type not in FieldTypes: 345 raise ValueError 346 return 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.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
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.
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.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
356class PromptStage(Stage): 357 """Prompt the user to enter information.""" 358 359 fields = models.ManyToManyField(Prompt, through="PromptStageField") 360 361 validation_policies = models.ManyToManyField( 362 Policy, blank=True, through="PromptStageValidationPolicy" 363 ) 364 365 @property 366 def serializer(self) -> type[BaseSerializer]: 367 from authentik.stages.prompt.api import PromptStageSerializer 368 369 return PromptStageSerializer 370 371 @property 372 def view(self) -> type[View]: 373 from authentik.stages.prompt.stage import PromptStageView 374 375 return PromptStageView 376 377 @property 378 def component(self) -> str: 379 return "ak-stage-prompt-form" 380 381 class Meta: 382 verbose_name = _("Prompt Stage") 383 verbose_name_plural = _("Prompt Stages")
Prompt the user to enter information.
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.
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.
365 @property 366 def serializer(self) -> type[BaseSerializer]: 367 from authentik.stages.prompt.api import PromptStageSerializer 368 369 return PromptStageSerializer
Get serializer for this model
371 @property 372 def view(self) -> type[View]: 373 from authentik.stages.prompt.stage import PromptStageView 374 375 return PromptStageView
Return StageView class that implements logic for this stage
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
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.
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.
Inherited Members
- authentik.flows.models.Stage
- stage_uuid
- name
- objects
- ui_user_settings
- is_in_memory
- flow_set
- flowstagebinding_set
- emailstage
- passwordstage
- endpointstage
- invitationstage
- promptstage
- authenticatorstaticstage
- authenticatorduostage
- authenticatoremailstage
- authenticatorsmsstage
- authenticatorwebauthnstage
- authenticatorvalidatestage
- authenticator_validate_stage_m2m_objects
- captchastage
- identificationstage
- authenticatortotpstage
- consentstage
- denystage
- dummystage
- redirectstage
- userdeletestage
- userloginstage
- userlogoutstage
- userwritestage
- accountlockdownstage
- authenticatorendpointgdtcstage
- mutualtlsstage
- sourcestage
The requested object does not exist
The query returned multiple objects when only one was expected.
386class PromptStageField(SimpleThroughModel): 387 prompt_stage = models.ForeignKey( 388 PromptStage, 389 on_delete=models.CASCADE, 390 db_column="promptstage_id", 391 ) 392 prompt = models.ForeignKey(Prompt, on_delete=models.CASCADE) 393 394 class Meta: 395 db_table = "authentik_stages_prompt_promptstage_fields" 396 unique_together = (("prompt_stage", "prompt"),) 397 verbose_name = _("Prompt Stage Field") 398 verbose_name_plural = _("Prompt Stage Fields") 399 400 def __str__(self): 401 return ( 402 f"PromptStageField for PromptStage {self.prompt_stage_id} " 403 f"and Field {self.prompt_id}." 404 )
PromptStageField(id, prompt_stage, prompt)
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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.
407class PromptStageValidationPolicy(SimpleThroughModel): 408 prompt_stage = models.ForeignKey( 409 PromptStage, 410 on_delete=models.CASCADE, 411 db_column="promptstage_id", 412 ) 413 policy = models.ForeignKey(Policy, on_delete=models.CASCADE) 414 415 class Meta: 416 db_table = "authentik_stages_prompt_promptstage_validation_policies" 417 unique_together = (("prompt_stage", "policy"),) 418 verbose_name = _("Prompt Stage Validation Policy") 419 verbose_name_plural = _("Prompt Stage Validation Policys") 420 421 def __str__(self): 422 return ( 423 f"PromptStageValidationPolicy for PromptStage {self.prompt_stage_id} " 424 f"and Policy {self.policy_id}." 425 )
PromptStageValidationPolicy(id, prompt_stage, policy)
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.
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.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.