authentik.stages.prompt.stage
Prompt Stage Logic
1"""Prompt Stage Logic""" 2 3from collections.abc import Callable 4from email.policy import Policy 5from types import MethodType 6from typing import Any 7 8from django.contrib.messages import INFO, add_message 9from django.db.models import Q 10from django.db.models.query import QuerySet 11from django.http import HttpRequest, HttpResponse 12from django.http.request import QueryDict 13from django.utils.translation import gettext_lazy as _ 14from rest_framework.fields import ( 15 BooleanField, 16 CharField, 17 ChoiceField, 18 IntegerField, 19 ListField, 20 empty, 21) 22from rest_framework.serializers import ValidationError 23 24from authentik.core.api.utils import PassiveSerializer 25from authentik.core.models import User 26from authentik.flows.challenge import Challenge, ChallengeResponse 27from authentik.flows.planner import FlowPlan 28from authentik.flows.stage import ChallengeStageView 29from authentik.policies.engine import PolicyEngine 30from authentik.policies.models import PolicyBinding, PolicyBindingModel, PolicyEngineMode 31from authentik.stages.prompt.models import FieldTypes, Prompt, PromptStage 32from authentik.stages.prompt.signals import password_validate 33 34PLAN_CONTEXT_PROMPT = "prompt_data" 35 36 37class PromptChoiceSerializer(PassiveSerializer): 38 """Serializer for a single Choice field""" 39 40 value = CharField(required=True) 41 label = CharField(required=True) 42 43 44class StagePromptSerializer(PassiveSerializer): 45 """Serializer for a single Prompt field""" 46 47 field_key = CharField() 48 label = CharField(allow_blank=True) 49 type = ChoiceField(choices=FieldTypes.choices) 50 required = BooleanField() 51 placeholder = CharField(allow_blank=True) 52 initial_value = CharField(allow_blank=True) 53 order = IntegerField() 54 sub_text = CharField(allow_blank=True) 55 choices = ListField(child=PromptChoiceSerializer(), allow_empty=True, allow_null=True) 56 57 58class PromptChallenge(Challenge): 59 """Initial challenge being sent, define fields""" 60 61 fields = StagePromptSerializer(many=True) 62 component = CharField(default="ak-stage-prompt") 63 64 65class PromptChallengeResponse(ChallengeResponse): 66 """Validate response, fields are dynamically created based 67 on the stage""" 68 69 stage_instance: PromptStage 70 71 component = CharField(default="ak-stage-prompt") 72 73 def __init__(self, *args, **kwargs): 74 stage: PromptStage = kwargs.pop("stage_instance", None) 75 plan: FlowPlan = kwargs.pop("plan", None) 76 request: HttpRequest = kwargs.pop("request", None) 77 user: User = kwargs.pop("user", None) 78 super().__init__(*args, **kwargs) 79 self.stage_instance = stage 80 self.plan = plan 81 self.request = request 82 if not self.stage_instance: 83 return 84 # list() is called so we only load the fields once 85 fields = list(self.stage_instance.fields.all()) 86 for field in fields: 87 field: Prompt 88 choices = field.get_choices( 89 plan.context.get(PLAN_CONTEXT_PROMPT, {}), user, self.request 90 ) 91 current = field.get_initial_value( 92 plan.context.get(PLAN_CONTEXT_PROMPT, {}), user, self.request 93 ) 94 self.fields[field.field_key] = field.field(current, choices) 95 # Special handling for fields with username type 96 # these check for existing users with the same username 97 if field.type == FieldTypes.USERNAME: 98 setattr( 99 self, 100 f"validate_{field.field_key}", 101 MethodType(username_field_validator_factory(), self), 102 ) 103 # Check if we have a password field, add a handler that sends a signal 104 # to validate it 105 if field.type in (FieldTypes.PASSWORD, FieldTypes.PASSWORD_VIEWABLE): 106 setattr( 107 self, 108 f"validate_{field.field_key}", 109 MethodType(password_single_validator_factory(), self), 110 ) 111 112 self.field_order = sorted(fields, key=lambda x: x.order) 113 114 def _validate_password_fields(self, *field_names): 115 """Check if the value of all password fields match by merging them into a set 116 and checking the length""" 117 all_passwords = {self.initial_data[x] for x in field_names} 118 if len(all_passwords) > 1: 119 raise ValidationError(_("Passwords don't match.")) 120 121 def validate(self, attrs: dict[str, Any]) -> dict[str, Any]: 122 # Check if we have any static or hidden fields, and ensure they 123 # still have the same value 124 static_hidden_fields: QuerySet[Prompt] = self.stage_instance.fields.filter( 125 type__in=[ 126 FieldTypes.HIDDEN, 127 FieldTypes.STATIC, 128 FieldTypes.ALERT_INFO, 129 FieldTypes.ALERT_WARNING, 130 FieldTypes.ALERT_DANGER, 131 FieldTypes.TEXT_READ_ONLY, 132 FieldTypes.TEXT_AREA_READ_ONLY, 133 ] 134 ) 135 for static_hidden in static_hidden_fields: 136 field = self.fields[static_hidden.field_key] 137 default = field.default 138 # Prevent rest_framework.fields.empty from ending up in policies and events 139 if default == empty: 140 default = "" 141 attrs[static_hidden.field_key] = default 142 143 # Check if we have two password fields, and make sure they are the same 144 password_fields: QuerySet[Prompt] = self.stage_instance.fields.filter( 145 Q(type=FieldTypes.PASSWORD) | Q(type=FieldTypes.PASSWORD_VIEWABLE) 146 ) 147 if password_fields.exists() and password_fields.count() == 2: # noqa: PLR2004 148 self._validate_password_fields(*[field.field_key for field in password_fields]) 149 150 engine = PromptValidationPolicyEngine( 151 self.stage_instance, 152 self.stage_instance.validation_policies.all(), 153 self.stage.get_pending_user(), 154 self.request, 155 ) 156 engine.mode = PolicyEngineMode.MODE_ALL 157 engine.request.context[PLAN_CONTEXT_PROMPT] = attrs 158 engine.use_cache = False 159 engine.build() 160 result = engine.result 161 if not result.passing: 162 raise ValidationError(list(result.messages)) 163 else: 164 for msg in result.messages: 165 add_message(self.request, INFO, msg) 166 return attrs 167 168 169def username_field_validator_factory() -> Callable[[PromptChallengeResponse, str], Any]: 170 """Return a `clean_` method for `field`. Clean method checks if username is taken already.""" 171 172 def username_field_validator(self: PromptChallengeResponse, value: str) -> Any: 173 """Check for duplicate usernames""" 174 pending_user = self.stage.get_pending_user() 175 query = User.objects.all() 176 if pending_user.pk: 177 query = query.exclude(username=pending_user.username) 178 if query.filter(username=value).exists(): 179 raise ValidationError("Username is already taken.") 180 return value 181 182 return username_field_validator 183 184 185def password_single_validator_factory() -> Callable[[PromptChallengeResponse, str], Any]: 186 """Return a `clean_` method for `field`. Clean method checks if the password meets configured 187 PasswordPolicy.""" 188 189 def password_single_clean(self: PromptChallengeResponse, value: str) -> Any: 190 """Send password validation signals for e.g. LDAP Source""" 191 password_validate.send(sender=self, password=value, plan_context=self.plan.context) 192 return value 193 194 return password_single_clean 195 196 197class PromptValidationPolicyEngine(PolicyEngine): 198 """Slightly modified policy engine, which uses a list instead of a PolicyBindingModel""" 199 200 def __init__( 201 self, 202 stage: PromptStage, 203 policies: list[Policy], 204 user: User, 205 request: HttpRequest = None, 206 ) -> None: 207 # Use the stage's primary key so that the engine's metric labels (obj_pk) 208 # are stable per stage instead of a random UUID per submission 209 super().__init__(PolicyBindingModel(pbm_uuid=stage.pk), user, request) 210 self.__list = policies 211 self.use_cache = False 212 213 def bindings(self): 214 for idx, policy in enumerate(self.__list): 215 yield PolicyBinding( 216 policy=policy, 217 order=idx, 218 ) 219 220 221class PromptStageView(ChallengeStageView): 222 """Prompt Stage, save form data in plan context.""" 223 224 response_class = PromptChallengeResponse 225 226 def get_prompt_challenge_fields(self, fields: list[Prompt], context: dict, dry_run=False): 227 """Get serializers for all fields in `fields`, using the context `context`. 228 If `dry_run` is set, property mapping expression errors are raised, otherwise they 229 are logged and events are created""" 230 serializers = [] 231 for field in fields: 232 data = StagePromptSerializer(field).data 233 # Ensure all placeholders and initial values are str, as 234 # otherwise further in we can fail serializer validation if we return 235 # some types such as bool 236 # choices can be a dict with value and label 237 choices = field.get_choices(context, self.get_pending_user(), self.request, dry_run) 238 if choices: 239 data["choices"] = list(self.clean_choices(choices)) 240 else: 241 data["choices"] = None 242 data["placeholder"] = str( 243 field.get_placeholder(context, self.get_pending_user(), self.request, dry_run) 244 ) 245 data["initial_value"] = str( 246 field.get_initial_value(context, self.get_pending_user(), self.request, dry_run) 247 ) 248 serializers.append(data) 249 return serializers 250 251 def clean_choices(self, choices): 252 for choice in choices: 253 label, value = choice, choice 254 if isinstance(choice, dict): 255 label = choice.get("label", "") 256 value = choice.get("value", "") 257 yield {"label": str(label), "value": str(value)} 258 259 def get_challenge(self, *args, **kwargs) -> Challenge: 260 fields: list[Prompt] = list(self.executor.current_stage.fields.all().order_by("order")) 261 context_prompt = self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {}) 262 serializers = self.get_prompt_challenge_fields(fields, context_prompt) 263 challenge = PromptChallenge( 264 data={ 265 "fields": serializers, 266 }, 267 ) 268 return challenge 269 270 def get_response_instance(self, data: QueryDict) -> ChallengeResponse: 271 if not self.executor.plan: # pragma: no cover 272 raise ValueError 273 return PromptChallengeResponse( 274 instance=None, 275 data=data, 276 request=self.request, 277 stage_instance=self.executor.current_stage, 278 stage=self, 279 plan=self.executor.plan, 280 user=self.get_pending_user(), 281 ) 282 283 def challenge_valid(self, response: ChallengeResponse) -> HttpResponse: 284 if PLAN_CONTEXT_PROMPT not in self.executor.plan.context: 285 self.executor.plan.context[PLAN_CONTEXT_PROMPT] = {} 286 self.executor.plan.context[PLAN_CONTEXT_PROMPT].update(response.validated_data) 287 return self.executor.stage_ok()
38class PromptChoiceSerializer(PassiveSerializer): 39 """Serializer for a single Choice field""" 40 41 value = CharField(required=True) 42 label = CharField(required=True)
Serializer for a single Choice field
Inherited Members
45class StagePromptSerializer(PassiveSerializer): 46 """Serializer for a single Prompt field""" 47 48 field_key = CharField() 49 label = CharField(allow_blank=True) 50 type = ChoiceField(choices=FieldTypes.choices) 51 required = BooleanField() 52 placeholder = CharField(allow_blank=True) 53 initial_value = CharField(allow_blank=True) 54 order = IntegerField() 55 sub_text = CharField(allow_blank=True) 56 choices = ListField(child=PromptChoiceSerializer(), allow_empty=True, allow_null=True)
Serializer for a single Prompt field
Inherited Members
59class PromptChallenge(Challenge): 60 """Initial challenge being sent, define fields""" 61 62 fields = StagePromptSerializer(many=True) 63 component = CharField(default="ak-stage-prompt")
Initial challenge being sent, define fields
66class PromptChallengeResponse(ChallengeResponse): 67 """Validate response, fields are dynamically created based 68 on the stage""" 69 70 stage_instance: PromptStage 71 72 component = CharField(default="ak-stage-prompt") 73 74 def __init__(self, *args, **kwargs): 75 stage: PromptStage = kwargs.pop("stage_instance", None) 76 plan: FlowPlan = kwargs.pop("plan", None) 77 request: HttpRequest = kwargs.pop("request", None) 78 user: User = kwargs.pop("user", None) 79 super().__init__(*args, **kwargs) 80 self.stage_instance = stage 81 self.plan = plan 82 self.request = request 83 if not self.stage_instance: 84 return 85 # list() is called so we only load the fields once 86 fields = list(self.stage_instance.fields.all()) 87 for field in fields: 88 field: Prompt 89 choices = field.get_choices( 90 plan.context.get(PLAN_CONTEXT_PROMPT, {}), user, self.request 91 ) 92 current = field.get_initial_value( 93 plan.context.get(PLAN_CONTEXT_PROMPT, {}), user, self.request 94 ) 95 self.fields[field.field_key] = field.field(current, choices) 96 # Special handling for fields with username type 97 # these check for existing users with the same username 98 if field.type == FieldTypes.USERNAME: 99 setattr( 100 self, 101 f"validate_{field.field_key}", 102 MethodType(username_field_validator_factory(), self), 103 ) 104 # Check if we have a password field, add a handler that sends a signal 105 # to validate it 106 if field.type in (FieldTypes.PASSWORD, FieldTypes.PASSWORD_VIEWABLE): 107 setattr( 108 self, 109 f"validate_{field.field_key}", 110 MethodType(password_single_validator_factory(), self), 111 ) 112 113 self.field_order = sorted(fields, key=lambda x: x.order) 114 115 def _validate_password_fields(self, *field_names): 116 """Check if the value of all password fields match by merging them into a set 117 and checking the length""" 118 all_passwords = {self.initial_data[x] for x in field_names} 119 if len(all_passwords) > 1: 120 raise ValidationError(_("Passwords don't match.")) 121 122 def validate(self, attrs: dict[str, Any]) -> dict[str, Any]: 123 # Check if we have any static or hidden fields, and ensure they 124 # still have the same value 125 static_hidden_fields: QuerySet[Prompt] = self.stage_instance.fields.filter( 126 type__in=[ 127 FieldTypes.HIDDEN, 128 FieldTypes.STATIC, 129 FieldTypes.ALERT_INFO, 130 FieldTypes.ALERT_WARNING, 131 FieldTypes.ALERT_DANGER, 132 FieldTypes.TEXT_READ_ONLY, 133 FieldTypes.TEXT_AREA_READ_ONLY, 134 ] 135 ) 136 for static_hidden in static_hidden_fields: 137 field = self.fields[static_hidden.field_key] 138 default = field.default 139 # Prevent rest_framework.fields.empty from ending up in policies and events 140 if default == empty: 141 default = "" 142 attrs[static_hidden.field_key] = default 143 144 # Check if we have two password fields, and make sure they are the same 145 password_fields: QuerySet[Prompt] = self.stage_instance.fields.filter( 146 Q(type=FieldTypes.PASSWORD) | Q(type=FieldTypes.PASSWORD_VIEWABLE) 147 ) 148 if password_fields.exists() and password_fields.count() == 2: # noqa: PLR2004 149 self._validate_password_fields(*[field.field_key for field in password_fields]) 150 151 engine = PromptValidationPolicyEngine( 152 self.stage_instance, 153 self.stage_instance.validation_policies.all(), 154 self.stage.get_pending_user(), 155 self.request, 156 ) 157 engine.mode = PolicyEngineMode.MODE_ALL 158 engine.request.context[PLAN_CONTEXT_PROMPT] = attrs 159 engine.use_cache = False 160 engine.build() 161 result = engine.result 162 if not result.passing: 163 raise ValidationError(list(result.messages)) 164 else: 165 for msg in result.messages: 166 add_message(self.request, INFO, msg) 167 return attrs
Validate response, fields are dynamically created based on the stage
74 def __init__(self, *args, **kwargs): 75 stage: PromptStage = kwargs.pop("stage_instance", None) 76 plan: FlowPlan = kwargs.pop("plan", None) 77 request: HttpRequest = kwargs.pop("request", None) 78 user: User = kwargs.pop("user", None) 79 super().__init__(*args, **kwargs) 80 self.stage_instance = stage 81 self.plan = plan 82 self.request = request 83 if not self.stage_instance: 84 return 85 # list() is called so we only load the fields once 86 fields = list(self.stage_instance.fields.all()) 87 for field in fields: 88 field: Prompt 89 choices = field.get_choices( 90 plan.context.get(PLAN_CONTEXT_PROMPT, {}), user, self.request 91 ) 92 current = field.get_initial_value( 93 plan.context.get(PLAN_CONTEXT_PROMPT, {}), user, self.request 94 ) 95 self.fields[field.field_key] = field.field(current, choices) 96 # Special handling for fields with username type 97 # these check for existing users with the same username 98 if field.type == FieldTypes.USERNAME: 99 setattr( 100 self, 101 f"validate_{field.field_key}", 102 MethodType(username_field_validator_factory(), self), 103 ) 104 # Check if we have a password field, add a handler that sends a signal 105 # to validate it 106 if field.type in (FieldTypes.PASSWORD, FieldTypes.PASSWORD_VIEWABLE): 107 setattr( 108 self, 109 f"validate_{field.field_key}", 110 MethodType(password_single_validator_factory(), self), 111 ) 112 113 self.field_order = sorted(fields, key=lambda x: x.order)
122 def validate(self, attrs: dict[str, Any]) -> dict[str, Any]: 123 # Check if we have any static or hidden fields, and ensure they 124 # still have the same value 125 static_hidden_fields: QuerySet[Prompt] = self.stage_instance.fields.filter( 126 type__in=[ 127 FieldTypes.HIDDEN, 128 FieldTypes.STATIC, 129 FieldTypes.ALERT_INFO, 130 FieldTypes.ALERT_WARNING, 131 FieldTypes.ALERT_DANGER, 132 FieldTypes.TEXT_READ_ONLY, 133 FieldTypes.TEXT_AREA_READ_ONLY, 134 ] 135 ) 136 for static_hidden in static_hidden_fields: 137 field = self.fields[static_hidden.field_key] 138 default = field.default 139 # Prevent rest_framework.fields.empty from ending up in policies and events 140 if default == empty: 141 default = "" 142 attrs[static_hidden.field_key] = default 143 144 # Check if we have two password fields, and make sure they are the same 145 password_fields: QuerySet[Prompt] = self.stage_instance.fields.filter( 146 Q(type=FieldTypes.PASSWORD) | Q(type=FieldTypes.PASSWORD_VIEWABLE) 147 ) 148 if password_fields.exists() and password_fields.count() == 2: # noqa: PLR2004 149 self._validate_password_fields(*[field.field_key for field in password_fields]) 150 151 engine = PromptValidationPolicyEngine( 152 self.stage_instance, 153 self.stage_instance.validation_policies.all(), 154 self.stage.get_pending_user(), 155 self.request, 156 ) 157 engine.mode = PolicyEngineMode.MODE_ALL 158 engine.request.context[PLAN_CONTEXT_PROMPT] = attrs 159 engine.use_cache = False 160 engine.build() 161 result = engine.result 162 if not result.passing: 163 raise ValidationError(list(result.messages)) 164 else: 165 for msg in result.messages: 166 add_message(self.request, INFO, msg) 167 return attrs
170def username_field_validator_factory() -> Callable[[PromptChallengeResponse, str], Any]: 171 """Return a `clean_` method for `field`. Clean method checks if username is taken already.""" 172 173 def username_field_validator(self: PromptChallengeResponse, value: str) -> Any: 174 """Check for duplicate usernames""" 175 pending_user = self.stage.get_pending_user() 176 query = User.objects.all() 177 if pending_user.pk: 178 query = query.exclude(username=pending_user.username) 179 if query.filter(username=value).exists(): 180 raise ValidationError("Username is already taken.") 181 return value 182 183 return username_field_validator
Return a clean_ method for field. Clean method checks if username is taken already.
186def password_single_validator_factory() -> Callable[[PromptChallengeResponse, str], Any]: 187 """Return a `clean_` method for `field`. Clean method checks if the password meets configured 188 PasswordPolicy.""" 189 190 def password_single_clean(self: PromptChallengeResponse, value: str) -> Any: 191 """Send password validation signals for e.g. LDAP Source""" 192 password_validate.send(sender=self, password=value, plan_context=self.plan.context) 193 return value 194 195 return password_single_clean
Return a clean_ method for field. Clean method checks if the password meets configured
PasswordPolicy.
198class PromptValidationPolicyEngine(PolicyEngine): 199 """Slightly modified policy engine, which uses a list instead of a PolicyBindingModel""" 200 201 def __init__( 202 self, 203 stage: PromptStage, 204 policies: list[Policy], 205 user: User, 206 request: HttpRequest = None, 207 ) -> None: 208 # Use the stage's primary key so that the engine's metric labels (obj_pk) 209 # are stable per stage instead of a random UUID per submission 210 super().__init__(PolicyBindingModel(pbm_uuid=stage.pk), user, request) 211 self.__list = policies 212 self.use_cache = False 213 214 def bindings(self): 215 for idx, policy in enumerate(self.__list): 216 yield PolicyBinding( 217 policy=policy, 218 order=idx, 219 )
Slightly modified policy engine, which uses a list instead of a PolicyBindingModel
201 def __init__( 202 self, 203 stage: PromptStage, 204 policies: list[Policy], 205 user: User, 206 request: HttpRequest = None, 207 ) -> None: 208 # Use the stage's primary key so that the engine's metric labels (obj_pk) 209 # are stable per stage instead of a random UUID per submission 210 super().__init__(PolicyBindingModel(pbm_uuid=stage.pk), user, request) 211 self.__list = policies 212 self.use_cache = False
222class PromptStageView(ChallengeStageView): 223 """Prompt Stage, save form data in plan context.""" 224 225 response_class = PromptChallengeResponse 226 227 def get_prompt_challenge_fields(self, fields: list[Prompt], context: dict, dry_run=False): 228 """Get serializers for all fields in `fields`, using the context `context`. 229 If `dry_run` is set, property mapping expression errors are raised, otherwise they 230 are logged and events are created""" 231 serializers = [] 232 for field in fields: 233 data = StagePromptSerializer(field).data 234 # Ensure all placeholders and initial values are str, as 235 # otherwise further in we can fail serializer validation if we return 236 # some types such as bool 237 # choices can be a dict with value and label 238 choices = field.get_choices(context, self.get_pending_user(), self.request, dry_run) 239 if choices: 240 data["choices"] = list(self.clean_choices(choices)) 241 else: 242 data["choices"] = None 243 data["placeholder"] = str( 244 field.get_placeholder(context, self.get_pending_user(), self.request, dry_run) 245 ) 246 data["initial_value"] = str( 247 field.get_initial_value(context, self.get_pending_user(), self.request, dry_run) 248 ) 249 serializers.append(data) 250 return serializers 251 252 def clean_choices(self, choices): 253 for choice in choices: 254 label, value = choice, choice 255 if isinstance(choice, dict): 256 label = choice.get("label", "") 257 value = choice.get("value", "") 258 yield {"label": str(label), "value": str(value)} 259 260 def get_challenge(self, *args, **kwargs) -> Challenge: 261 fields: list[Prompt] = list(self.executor.current_stage.fields.all().order_by("order")) 262 context_prompt = self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {}) 263 serializers = self.get_prompt_challenge_fields(fields, context_prompt) 264 challenge = PromptChallenge( 265 data={ 266 "fields": serializers, 267 }, 268 ) 269 return challenge 270 271 def get_response_instance(self, data: QueryDict) -> ChallengeResponse: 272 if not self.executor.plan: # pragma: no cover 273 raise ValueError 274 return PromptChallengeResponse( 275 instance=None, 276 data=data, 277 request=self.request, 278 stage_instance=self.executor.current_stage, 279 stage=self, 280 plan=self.executor.plan, 281 user=self.get_pending_user(), 282 ) 283 284 def challenge_valid(self, response: ChallengeResponse) -> HttpResponse: 285 if PLAN_CONTEXT_PROMPT not in self.executor.plan.context: 286 self.executor.plan.context[PLAN_CONTEXT_PROMPT] = {} 287 self.executor.plan.context[PLAN_CONTEXT_PROMPT].update(response.validated_data) 288 return self.executor.stage_ok()
Prompt Stage, save form data in plan context.
227 def get_prompt_challenge_fields(self, fields: list[Prompt], context: dict, dry_run=False): 228 """Get serializers for all fields in `fields`, using the context `context`. 229 If `dry_run` is set, property mapping expression errors are raised, otherwise they 230 are logged and events are created""" 231 serializers = [] 232 for field in fields: 233 data = StagePromptSerializer(field).data 234 # Ensure all placeholders and initial values are str, as 235 # otherwise further in we can fail serializer validation if we return 236 # some types such as bool 237 # choices can be a dict with value and label 238 choices = field.get_choices(context, self.get_pending_user(), self.request, dry_run) 239 if choices: 240 data["choices"] = list(self.clean_choices(choices)) 241 else: 242 data["choices"] = None 243 data["placeholder"] = str( 244 field.get_placeholder(context, self.get_pending_user(), self.request, dry_run) 245 ) 246 data["initial_value"] = str( 247 field.get_initial_value(context, self.get_pending_user(), self.request, dry_run) 248 ) 249 serializers.append(data) 250 return serializers
Get serializers for all fields in fields, using the context context.
If dry_run is set, property mapping expression errors are raised, otherwise they
are logged and events are created
260 def get_challenge(self, *args, **kwargs) -> Challenge: 261 fields: list[Prompt] = list(self.executor.current_stage.fields.all().order_by("order")) 262 context_prompt = self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {}) 263 serializers = self.get_prompt_challenge_fields(fields, context_prompt) 264 challenge = PromptChallenge( 265 data={ 266 "fields": serializers, 267 }, 268 ) 269 return challenge
Return the challenge that the client should solve
271 def get_response_instance(self, data: QueryDict) -> ChallengeResponse: 272 if not self.executor.plan: # pragma: no cover 273 raise ValueError 274 return PromptChallengeResponse( 275 instance=None, 276 data=data, 277 request=self.request, 278 stage_instance=self.executor.current_stage, 279 stage=self, 280 plan=self.executor.plan, 281 user=self.get_pending_user(), 282 )
Return the response class type
284 def challenge_valid(self, response: ChallengeResponse) -> HttpResponse: 285 if PLAN_CONTEXT_PROMPT not in self.executor.plan.context: 286 self.executor.plan.context[PLAN_CONTEXT_PROMPT] = {} 287 self.executor.plan.context[PLAN_CONTEXT_PROMPT].update(response.validated_data) 288 return self.executor.stage_ok()
Callback when the challenge has the correct format