authentik.stages.user_write.stage
Write stage logic
1"""Write stage logic""" 2 3from copy import deepcopy 4from typing import Any 5 6from django.contrib.auth import update_session_auth_hash 7from django.db import transaction 8from django.db.utils import IntegrityError, InternalError 9from django.http import HttpRequest, HttpResponse 10from django.utils.functional import SimpleLazyObject 11from django.utils.translation import gettext as _ 12from rest_framework.exceptions import ValidationError 13 14from authentik.core.middleware import SESSION_KEY_IMPERSONATE_USER 15from authentik.core.models import USER_ATTRIBUTE_SOURCES, User, UserSourceConnection, UserTypes 16from authentik.core.sources.stage import PLAN_CONTEXT_SOURCES_CONNECTION 17from authentik.events.utils import sanitize_dict, sanitize_item 18from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER 19from authentik.flows.stage import StageView 20from authentik.flows.views.executor import FlowExecutorView 21from authentik.lib.utils.dict import set_path_in_dict 22from authentik.stages.password import BACKEND_INBUILT 23from authentik.stages.password.models import PasswordDevice 24from authentik.stages.password.stage import PLAN_CONTEXT_AUTHENTICATION_BACKEND 25from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT 26from authentik.stages.user_write.models import UserCreationMode 27from authentik.stages.user_write.signals import user_write 28 29PLAN_CONTEXT_GROUPS = "groups" 30PLAN_CONTEXT_USER_TYPE = "user_type" 31PLAN_CONTEXT_USER_PATH = "user_path" 32 33 34class UserWriteStageView(StageView): 35 """Finalize Enrollment flow by creating a user object.""" 36 37 def __init__(self, executor: FlowExecutorView, **kwargs): 38 super().__init__(executor, **kwargs) 39 self.disallowed_user_attributes = [ 40 "groups", 41 # Block attribute writes that would otherwise land on the model's 42 # primary key. An IdP that returns an `id` claim (mocksaml is one 43 # example) used to crash the enrollment flow with 44 # ValueError: Field 'id' expected a number but got '<hex>' 45 # because hasattr(user, "id") is true and setattr(user, "id", ...) 46 # was taken unchecked. See #21580. 47 "id", 48 "pk", 49 ] 50 51 @staticmethod 52 def write_attribute(user: User, key: str, value: Any): 53 """Allow use of attributes.foo.bar when writing to a user, with full 54 recursion""" 55 parts = key.replace("attributes_", "attributes.", 1).split(".") 56 if len(parts) < 1: # pragma: no cover 57 return 58 # Function will always be called with a key like attributes. 59 # this is just a sanity check to ensure that is removed 60 if parts[0] == "attributes": 61 parts = parts[1:] 62 set_path_in_dict(user.attributes, ".".join(parts), sanitize_item(value)) 63 64 def ensure_user(self) -> tuple[User | None, bool]: 65 """Ensure a user exists""" 66 user_created = False 67 path = self.executor.plan.context.get( 68 PLAN_CONTEXT_USER_PATH, self.executor.current_stage.user_path_template 69 ) 70 if path == "": 71 path = User.default_path() 72 73 try: 74 user_type = UserTypes( 75 self.executor.plan.context.get( 76 PLAN_CONTEXT_USER_TYPE, 77 self.executor.current_stage.user_type, 78 ) 79 ) 80 except ValueError: 81 user_type = self.executor.current_stage.user_type 82 if user_type == UserTypes.INTERNAL_SERVICE_ACCOUNT: 83 user_type = UserTypes.SERVICE_ACCOUNT 84 85 if not self.request.user.is_anonymous: 86 self.executor.plan.context.setdefault(PLAN_CONTEXT_PENDING_USER, self.request.user) 87 if ( 88 PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context 89 or self.executor.current_stage.user_creation_mode == UserCreationMode.ALWAYS_CREATE 90 ): 91 if self.executor.current_stage.user_creation_mode == UserCreationMode.NEVER_CREATE: 92 return None, False 93 self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = User( 94 is_active=not self.executor.current_stage.create_users_as_inactive, 95 path=path, 96 type=user_type, 97 ) 98 self.executor.plan.context[PLAN_CONTEXT_AUTHENTICATION_BACKEND] = BACKEND_INBUILT 99 self.logger.debug( 100 "Created new user", 101 flow_slug=self.executor.flow.slug, 102 ) 103 user_created = True 104 user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] 105 return user, user_created 106 107 def update_user(self, user: User): 108 """Update `user` with data from plan context 109 110 Only simple attributes are updated, nothing which requires a foreign key or m2m""" 111 data: dict = self.executor.plan.context[PLAN_CONTEXT_PROMPT] 112 # This is always sent back but not written to the user 113 data.pop("component", None) 114 for key, value in data.items(): 115 setter_name = f"set_{key}" 116 # The password is stored once the user is saved, see dispatch() 117 if key == "password": 118 continue 119 # Check if user has a setter for this key 120 if hasattr(user, setter_name): 121 setter = getattr(user, setter_name) 122 if callable(setter): 123 setter(value) 124 elif key in self.disallowed_user_attributes: 125 self.logger.info("discarding key", key=key) 126 continue 127 # For exact attributes match, update the dictionary in place 128 elif key == "attributes": 129 if isinstance(value, dict): 130 user.attributes.update(sanitize_dict(value)) 131 else: 132 raise ValidationError("Attempt to overwrite complete attributes") 133 # If using dot notation, use the correct helper to update the nested value 134 elif key.startswith("attributes.") or key.startswith("attributes_"): 135 UserWriteStageView.write_attribute(user, key, value) 136 # User has this key already 137 elif hasattr(user, key): 138 if isinstance(user, SimpleLazyObject): 139 user._setup() 140 user = user._wrapped 141 attr = getattr(type(user), key) 142 if isinstance(attr, property): 143 if not attr.fset: 144 self.logger.info("discarding key", key=key) 145 continue 146 setattr(user, key, value) 147 # If none of the cases above matched, we have an attribute that the user doesn't have, 148 # has no setter for, is not a nested attributes value and as such is invalid 149 else: 150 self.logger.info("discarding key", key=key) 151 continue 152 # Check if we're writing from a source, and save the source to the attributes 153 if PLAN_CONTEXT_SOURCES_CONNECTION in self.executor.plan.context: 154 if USER_ATTRIBUTE_SOURCES not in user.attributes or not isinstance( 155 user.attributes.get(USER_ATTRIBUTE_SOURCES), list 156 ): 157 user.attributes[USER_ATTRIBUTE_SOURCES] = [] 158 connection: UserSourceConnection = self.executor.plan.context[ 159 PLAN_CONTEXT_SOURCES_CONNECTION 160 ] 161 if connection.source.name not in user.attributes[USER_ATTRIBUTE_SOURCES]: 162 user.attributes[USER_ATTRIBUTE_SOURCES].append(connection.source.name) 163 164 @staticmethod 165 def user_state(user: User) -> dict[str, Any]: 166 """Snapshot of the user's concrete field values, used to detect whether 167 `update_user` actually changed anything. Only concrete fields are captured; 168 m2m relations (`groups`, `roles`) are handled separately and auto-managed 169 fields (`last_updated`) only change on save, so they never produce a false 170 positive when comparing before/after an update.""" 171 return deepcopy( 172 {field.attname: getattr(user, field.attname) for field in user._meta.concrete_fields} 173 ) 174 175 def dispatch(self, request: HttpRequest) -> HttpResponse: 176 """Save data in the current flow to the currently pending user. If no user is pending, 177 a new user is created.""" 178 if PLAN_CONTEXT_PROMPT not in self.executor.plan.context: 179 message = _("No Pending data.") 180 self.logger.debug(message) 181 return self.executor.stage_invalid(message) 182 data = self.executor.plan.context[PLAN_CONTEXT_PROMPT] 183 user, user_created = self.ensure_user() 184 if not user: 185 message = _("No user found and can't create new user.") 186 self.logger.info(message) 187 return self.executor.stage_invalid(message) 188 # Before we change anything, check if the user is the same as in the request 189 # and we're updating a password. In that case we need to update the session hash 190 # Also check that we're not currently impersonating, so we don't update the session 191 should_update_session = False 192 if ( 193 any("password" in x for x in data.keys()) 194 and self.request.user.pk == user.pk 195 and SESSION_KEY_IMPERSONATE_USER not in self.request.session 196 ): 197 should_update_session = True 198 # Snapshot the user before applying prompt data so we can tell whether this 199 # write actually changed anything. Newly created users are always written. 200 pre_update_state = None if user_created else self.user_state(user) 201 try: 202 self.update_user(user) 203 except ValidationError as exc: 204 self.logger.warning("failed to update user", exc=exc) 205 return self.executor.stage_invalid(_("Failed to update user. Please try again later.")) 206 # Extra check to prevent flows from saving a user with a blank username 207 if user.username == "": 208 self.logger.warning("Aborting write to empty username", user=user) 209 return self.executor.stage_invalid() 210 user_changed = user_created or pre_update_state != self.user_state(user) 211 writes_password = "password" in data 212 if not user_changed and not writes_password: 213 # Nothing changed on the user; skip the save (and the downstream 214 # `model_updated` event / provider sync it would otherwise trigger). 215 # Group membership is still reconciled below as it is idempotent. 216 self.logger.debug( 217 "No changes to user, skipping write", 218 user=user, 219 flow_slug=self.executor.flow.slug, 220 ) 221 try: 222 if writes_password and not user_created: 223 # Outside the transaction, so an LDAP or Kerberos source that refuses the 224 # password keeps the configuration error event it records. 225 PasswordDevice.set_password(user, data["password"], request=self.request) 226 with transaction.atomic(): 227 if user_changed: 228 user.save() 229 if writes_password and user_created: 230 # A new user's first password does not count as a password change. 231 PasswordDevice.set_password(user, data["password"], signal=False) 232 if self.executor.current_stage.create_users_group: 233 user.groups.add(self.executor.current_stage.create_users_group) 234 if PLAN_CONTEXT_GROUPS in self.executor.plan.context: 235 user.groups.add(*self.executor.plan.context[PLAN_CONTEXT_GROUPS]) 236 except (IntegrityError, ValueError, TypeError, InternalError, ValidationError) as exc: 237 # ValidationError: an LDAP or Kerberos source refused the password 238 self.logger.warning("Failed to save user", exc=exc) 239 return self.executor.stage_invalid(_("Failed to update user. Please try again later.")) 240 if not user_changed and not writes_password: 241 return self.executor.stage_ok() 242 user_write.send(sender=self, request=request, user=user, data=data, created=user_created) 243 # Check if the password has been updated, and update the session auth hash 244 if should_update_session: 245 update_session_auth_hash(self.request, user) 246 self.logger.debug("Updated session hash", user=user) 247 self.logger.debug( 248 "Updated existing user", 249 user=user, 250 flow_slug=self.executor.flow.slug, 251 ) 252 return self.executor.stage_ok()
35class UserWriteStageView(StageView): 36 """Finalize Enrollment flow by creating a user object.""" 37 38 def __init__(self, executor: FlowExecutorView, **kwargs): 39 super().__init__(executor, **kwargs) 40 self.disallowed_user_attributes = [ 41 "groups", 42 # Block attribute writes that would otherwise land on the model's 43 # primary key. An IdP that returns an `id` claim (mocksaml is one 44 # example) used to crash the enrollment flow with 45 # ValueError: Field 'id' expected a number but got '<hex>' 46 # because hasattr(user, "id") is true and setattr(user, "id", ...) 47 # was taken unchecked. See #21580. 48 "id", 49 "pk", 50 ] 51 52 @staticmethod 53 def write_attribute(user: User, key: str, value: Any): 54 """Allow use of attributes.foo.bar when writing to a user, with full 55 recursion""" 56 parts = key.replace("attributes_", "attributes.", 1).split(".") 57 if len(parts) < 1: # pragma: no cover 58 return 59 # Function will always be called with a key like attributes. 60 # this is just a sanity check to ensure that is removed 61 if parts[0] == "attributes": 62 parts = parts[1:] 63 set_path_in_dict(user.attributes, ".".join(parts), sanitize_item(value)) 64 65 def ensure_user(self) -> tuple[User | None, bool]: 66 """Ensure a user exists""" 67 user_created = False 68 path = self.executor.plan.context.get( 69 PLAN_CONTEXT_USER_PATH, self.executor.current_stage.user_path_template 70 ) 71 if path == "": 72 path = User.default_path() 73 74 try: 75 user_type = UserTypes( 76 self.executor.plan.context.get( 77 PLAN_CONTEXT_USER_TYPE, 78 self.executor.current_stage.user_type, 79 ) 80 ) 81 except ValueError: 82 user_type = self.executor.current_stage.user_type 83 if user_type == UserTypes.INTERNAL_SERVICE_ACCOUNT: 84 user_type = UserTypes.SERVICE_ACCOUNT 85 86 if not self.request.user.is_anonymous: 87 self.executor.plan.context.setdefault(PLAN_CONTEXT_PENDING_USER, self.request.user) 88 if ( 89 PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context 90 or self.executor.current_stage.user_creation_mode == UserCreationMode.ALWAYS_CREATE 91 ): 92 if self.executor.current_stage.user_creation_mode == UserCreationMode.NEVER_CREATE: 93 return None, False 94 self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = User( 95 is_active=not self.executor.current_stage.create_users_as_inactive, 96 path=path, 97 type=user_type, 98 ) 99 self.executor.plan.context[PLAN_CONTEXT_AUTHENTICATION_BACKEND] = BACKEND_INBUILT 100 self.logger.debug( 101 "Created new user", 102 flow_slug=self.executor.flow.slug, 103 ) 104 user_created = True 105 user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] 106 return user, user_created 107 108 def update_user(self, user: User): 109 """Update `user` with data from plan context 110 111 Only simple attributes are updated, nothing which requires a foreign key or m2m""" 112 data: dict = self.executor.plan.context[PLAN_CONTEXT_PROMPT] 113 # This is always sent back but not written to the user 114 data.pop("component", None) 115 for key, value in data.items(): 116 setter_name = f"set_{key}" 117 # The password is stored once the user is saved, see dispatch() 118 if key == "password": 119 continue 120 # Check if user has a setter for this key 121 if hasattr(user, setter_name): 122 setter = getattr(user, setter_name) 123 if callable(setter): 124 setter(value) 125 elif key in self.disallowed_user_attributes: 126 self.logger.info("discarding key", key=key) 127 continue 128 # For exact attributes match, update the dictionary in place 129 elif key == "attributes": 130 if isinstance(value, dict): 131 user.attributes.update(sanitize_dict(value)) 132 else: 133 raise ValidationError("Attempt to overwrite complete attributes") 134 # If using dot notation, use the correct helper to update the nested value 135 elif key.startswith("attributes.") or key.startswith("attributes_"): 136 UserWriteStageView.write_attribute(user, key, value) 137 # User has this key already 138 elif hasattr(user, key): 139 if isinstance(user, SimpleLazyObject): 140 user._setup() 141 user = user._wrapped 142 attr = getattr(type(user), key) 143 if isinstance(attr, property): 144 if not attr.fset: 145 self.logger.info("discarding key", key=key) 146 continue 147 setattr(user, key, value) 148 # If none of the cases above matched, we have an attribute that the user doesn't have, 149 # has no setter for, is not a nested attributes value and as such is invalid 150 else: 151 self.logger.info("discarding key", key=key) 152 continue 153 # Check if we're writing from a source, and save the source to the attributes 154 if PLAN_CONTEXT_SOURCES_CONNECTION in self.executor.plan.context: 155 if USER_ATTRIBUTE_SOURCES not in user.attributes or not isinstance( 156 user.attributes.get(USER_ATTRIBUTE_SOURCES), list 157 ): 158 user.attributes[USER_ATTRIBUTE_SOURCES] = [] 159 connection: UserSourceConnection = self.executor.plan.context[ 160 PLAN_CONTEXT_SOURCES_CONNECTION 161 ] 162 if connection.source.name not in user.attributes[USER_ATTRIBUTE_SOURCES]: 163 user.attributes[USER_ATTRIBUTE_SOURCES].append(connection.source.name) 164 165 @staticmethod 166 def user_state(user: User) -> dict[str, Any]: 167 """Snapshot of the user's concrete field values, used to detect whether 168 `update_user` actually changed anything. Only concrete fields are captured; 169 m2m relations (`groups`, `roles`) are handled separately and auto-managed 170 fields (`last_updated`) only change on save, so they never produce a false 171 positive when comparing before/after an update.""" 172 return deepcopy( 173 {field.attname: getattr(user, field.attname) for field in user._meta.concrete_fields} 174 ) 175 176 def dispatch(self, request: HttpRequest) -> HttpResponse: 177 """Save data in the current flow to the currently pending user. If no user is pending, 178 a new user is created.""" 179 if PLAN_CONTEXT_PROMPT not in self.executor.plan.context: 180 message = _("No Pending data.") 181 self.logger.debug(message) 182 return self.executor.stage_invalid(message) 183 data = self.executor.plan.context[PLAN_CONTEXT_PROMPT] 184 user, user_created = self.ensure_user() 185 if not user: 186 message = _("No user found and can't create new user.") 187 self.logger.info(message) 188 return self.executor.stage_invalid(message) 189 # Before we change anything, check if the user is the same as in the request 190 # and we're updating a password. In that case we need to update the session hash 191 # Also check that we're not currently impersonating, so we don't update the session 192 should_update_session = False 193 if ( 194 any("password" in x for x in data.keys()) 195 and self.request.user.pk == user.pk 196 and SESSION_KEY_IMPERSONATE_USER not in self.request.session 197 ): 198 should_update_session = True 199 # Snapshot the user before applying prompt data so we can tell whether this 200 # write actually changed anything. Newly created users are always written. 201 pre_update_state = None if user_created else self.user_state(user) 202 try: 203 self.update_user(user) 204 except ValidationError as exc: 205 self.logger.warning("failed to update user", exc=exc) 206 return self.executor.stage_invalid(_("Failed to update user. Please try again later.")) 207 # Extra check to prevent flows from saving a user with a blank username 208 if user.username == "": 209 self.logger.warning("Aborting write to empty username", user=user) 210 return self.executor.stage_invalid() 211 user_changed = user_created or pre_update_state != self.user_state(user) 212 writes_password = "password" in data 213 if not user_changed and not writes_password: 214 # Nothing changed on the user; skip the save (and the downstream 215 # `model_updated` event / provider sync it would otherwise trigger). 216 # Group membership is still reconciled below as it is idempotent. 217 self.logger.debug( 218 "No changes to user, skipping write", 219 user=user, 220 flow_slug=self.executor.flow.slug, 221 ) 222 try: 223 if writes_password and not user_created: 224 # Outside the transaction, so an LDAP or Kerberos source that refuses the 225 # password keeps the configuration error event it records. 226 PasswordDevice.set_password(user, data["password"], request=self.request) 227 with transaction.atomic(): 228 if user_changed: 229 user.save() 230 if writes_password and user_created: 231 # A new user's first password does not count as a password change. 232 PasswordDevice.set_password(user, data["password"], signal=False) 233 if self.executor.current_stage.create_users_group: 234 user.groups.add(self.executor.current_stage.create_users_group) 235 if PLAN_CONTEXT_GROUPS in self.executor.plan.context: 236 user.groups.add(*self.executor.plan.context[PLAN_CONTEXT_GROUPS]) 237 except (IntegrityError, ValueError, TypeError, InternalError, ValidationError) as exc: 238 # ValidationError: an LDAP or Kerberos source refused the password 239 self.logger.warning("Failed to save user", exc=exc) 240 return self.executor.stage_invalid(_("Failed to update user. Please try again later.")) 241 if not user_changed and not writes_password: 242 return self.executor.stage_ok() 243 user_write.send(sender=self, request=request, user=user, data=data, created=user_created) 244 # Check if the password has been updated, and update the session auth hash 245 if should_update_session: 246 update_session_auth_hash(self.request, user) 247 self.logger.debug("Updated session hash", user=user) 248 self.logger.debug( 249 "Updated existing user", 250 user=user, 251 flow_slug=self.executor.flow.slug, 252 ) 253 return self.executor.stage_ok()
Finalize Enrollment flow by creating a user object.
38 def __init__(self, executor: FlowExecutorView, **kwargs): 39 super().__init__(executor, **kwargs) 40 self.disallowed_user_attributes = [ 41 "groups", 42 # Block attribute writes that would otherwise land on the model's 43 # primary key. An IdP that returns an `id` claim (mocksaml is one 44 # example) used to crash the enrollment flow with 45 # ValueError: Field 'id' expected a number but got '<hex>' 46 # because hasattr(user, "id") is true and setattr(user, "id", ...) 47 # was taken unchecked. See #21580. 48 "id", 49 "pk", 50 ]
Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.
52 @staticmethod 53 def write_attribute(user: User, key: str, value: Any): 54 """Allow use of attributes.foo.bar when writing to a user, with full 55 recursion""" 56 parts = key.replace("attributes_", "attributes.", 1).split(".") 57 if len(parts) < 1: # pragma: no cover 58 return 59 # Function will always be called with a key like attributes. 60 # this is just a sanity check to ensure that is removed 61 if parts[0] == "attributes": 62 parts = parts[1:] 63 set_path_in_dict(user.attributes, ".".join(parts), sanitize_item(value))
Allow use of attributes.foo.bar when writing to a user, with full recursion
65 def ensure_user(self) -> tuple[User | None, bool]: 66 """Ensure a user exists""" 67 user_created = False 68 path = self.executor.plan.context.get( 69 PLAN_CONTEXT_USER_PATH, self.executor.current_stage.user_path_template 70 ) 71 if path == "": 72 path = User.default_path() 73 74 try: 75 user_type = UserTypes( 76 self.executor.plan.context.get( 77 PLAN_CONTEXT_USER_TYPE, 78 self.executor.current_stage.user_type, 79 ) 80 ) 81 except ValueError: 82 user_type = self.executor.current_stage.user_type 83 if user_type == UserTypes.INTERNAL_SERVICE_ACCOUNT: 84 user_type = UserTypes.SERVICE_ACCOUNT 85 86 if not self.request.user.is_anonymous: 87 self.executor.plan.context.setdefault(PLAN_CONTEXT_PENDING_USER, self.request.user) 88 if ( 89 PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context 90 or self.executor.current_stage.user_creation_mode == UserCreationMode.ALWAYS_CREATE 91 ): 92 if self.executor.current_stage.user_creation_mode == UserCreationMode.NEVER_CREATE: 93 return None, False 94 self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] = User( 95 is_active=not self.executor.current_stage.create_users_as_inactive, 96 path=path, 97 type=user_type, 98 ) 99 self.executor.plan.context[PLAN_CONTEXT_AUTHENTICATION_BACKEND] = BACKEND_INBUILT 100 self.logger.debug( 101 "Created new user", 102 flow_slug=self.executor.flow.slug, 103 ) 104 user_created = True 105 user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] 106 return user, user_created
Ensure a user exists
108 def update_user(self, user: User): 109 """Update `user` with data from plan context 110 111 Only simple attributes are updated, nothing which requires a foreign key or m2m""" 112 data: dict = self.executor.plan.context[PLAN_CONTEXT_PROMPT] 113 # This is always sent back but not written to the user 114 data.pop("component", None) 115 for key, value in data.items(): 116 setter_name = f"set_{key}" 117 # The password is stored once the user is saved, see dispatch() 118 if key == "password": 119 continue 120 # Check if user has a setter for this key 121 if hasattr(user, setter_name): 122 setter = getattr(user, setter_name) 123 if callable(setter): 124 setter(value) 125 elif key in self.disallowed_user_attributes: 126 self.logger.info("discarding key", key=key) 127 continue 128 # For exact attributes match, update the dictionary in place 129 elif key == "attributes": 130 if isinstance(value, dict): 131 user.attributes.update(sanitize_dict(value)) 132 else: 133 raise ValidationError("Attempt to overwrite complete attributes") 134 # If using dot notation, use the correct helper to update the nested value 135 elif key.startswith("attributes.") or key.startswith("attributes_"): 136 UserWriteStageView.write_attribute(user, key, value) 137 # User has this key already 138 elif hasattr(user, key): 139 if isinstance(user, SimpleLazyObject): 140 user._setup() 141 user = user._wrapped 142 attr = getattr(type(user), key) 143 if isinstance(attr, property): 144 if not attr.fset: 145 self.logger.info("discarding key", key=key) 146 continue 147 setattr(user, key, value) 148 # If none of the cases above matched, we have an attribute that the user doesn't have, 149 # has no setter for, is not a nested attributes value and as such is invalid 150 else: 151 self.logger.info("discarding key", key=key) 152 continue 153 # Check if we're writing from a source, and save the source to the attributes 154 if PLAN_CONTEXT_SOURCES_CONNECTION in self.executor.plan.context: 155 if USER_ATTRIBUTE_SOURCES not in user.attributes or not isinstance( 156 user.attributes.get(USER_ATTRIBUTE_SOURCES), list 157 ): 158 user.attributes[USER_ATTRIBUTE_SOURCES] = [] 159 connection: UserSourceConnection = self.executor.plan.context[ 160 PLAN_CONTEXT_SOURCES_CONNECTION 161 ] 162 if connection.source.name not in user.attributes[USER_ATTRIBUTE_SOURCES]: 163 user.attributes[USER_ATTRIBUTE_SOURCES].append(connection.source.name)
Update user with data from plan context
Only simple attributes are updated, nothing which requires a foreign key or m2m
165 @staticmethod 166 def user_state(user: User) -> dict[str, Any]: 167 """Snapshot of the user's concrete field values, used to detect whether 168 `update_user` actually changed anything. Only concrete fields are captured; 169 m2m relations (`groups`, `roles`) are handled separately and auto-managed 170 fields (`last_updated`) only change on save, so they never produce a false 171 positive when comparing before/after an update.""" 172 return deepcopy( 173 {field.attname: getattr(user, field.attname) for field in user._meta.concrete_fields} 174 )
Snapshot of the user's concrete field values, used to detect whether
update_user actually changed anything. Only concrete fields are captured;
m2m relations (groups, roles) are handled separately and auto-managed
fields (last_updated) only change on save, so they never produce a false
positive when comparing before/after an update.
176 def dispatch(self, request: HttpRequest) -> HttpResponse: 177 """Save data in the current flow to the currently pending user. If no user is pending, 178 a new user is created.""" 179 if PLAN_CONTEXT_PROMPT not in self.executor.plan.context: 180 message = _("No Pending data.") 181 self.logger.debug(message) 182 return self.executor.stage_invalid(message) 183 data = self.executor.plan.context[PLAN_CONTEXT_PROMPT] 184 user, user_created = self.ensure_user() 185 if not user: 186 message = _("No user found and can't create new user.") 187 self.logger.info(message) 188 return self.executor.stage_invalid(message) 189 # Before we change anything, check if the user is the same as in the request 190 # and we're updating a password. In that case we need to update the session hash 191 # Also check that we're not currently impersonating, so we don't update the session 192 should_update_session = False 193 if ( 194 any("password" in x for x in data.keys()) 195 and self.request.user.pk == user.pk 196 and SESSION_KEY_IMPERSONATE_USER not in self.request.session 197 ): 198 should_update_session = True 199 # Snapshot the user before applying prompt data so we can tell whether this 200 # write actually changed anything. Newly created users are always written. 201 pre_update_state = None if user_created else self.user_state(user) 202 try: 203 self.update_user(user) 204 except ValidationError as exc: 205 self.logger.warning("failed to update user", exc=exc) 206 return self.executor.stage_invalid(_("Failed to update user. Please try again later.")) 207 # Extra check to prevent flows from saving a user with a blank username 208 if user.username == "": 209 self.logger.warning("Aborting write to empty username", user=user) 210 return self.executor.stage_invalid() 211 user_changed = user_created or pre_update_state != self.user_state(user) 212 writes_password = "password" in data 213 if not user_changed and not writes_password: 214 # Nothing changed on the user; skip the save (and the downstream 215 # `model_updated` event / provider sync it would otherwise trigger). 216 # Group membership is still reconciled below as it is idempotent. 217 self.logger.debug( 218 "No changes to user, skipping write", 219 user=user, 220 flow_slug=self.executor.flow.slug, 221 ) 222 try: 223 if writes_password and not user_created: 224 # Outside the transaction, so an LDAP or Kerberos source that refuses the 225 # password keeps the configuration error event it records. 226 PasswordDevice.set_password(user, data["password"], request=self.request) 227 with transaction.atomic(): 228 if user_changed: 229 user.save() 230 if writes_password and user_created: 231 # A new user's first password does not count as a password change. 232 PasswordDevice.set_password(user, data["password"], signal=False) 233 if self.executor.current_stage.create_users_group: 234 user.groups.add(self.executor.current_stage.create_users_group) 235 if PLAN_CONTEXT_GROUPS in self.executor.plan.context: 236 user.groups.add(*self.executor.plan.context[PLAN_CONTEXT_GROUPS]) 237 except (IntegrityError, ValueError, TypeError, InternalError, ValidationError) as exc: 238 # ValidationError: an LDAP or Kerberos source refused the password 239 self.logger.warning("Failed to save user", exc=exc) 240 return self.executor.stage_invalid(_("Failed to update user. Please try again later.")) 241 if not user_changed and not writes_password: 242 return self.executor.stage_ok() 243 user_write.send(sender=self, request=request, user=user, data=data, created=user_created) 244 # Check if the password has been updated, and update the session auth hash 245 if should_update_session: 246 update_session_auth_hash(self.request, user) 247 self.logger.debug("Updated session hash", user=user) 248 self.logger.debug( 249 "Updated existing user", 250 user=user, 251 flow_slug=self.executor.flow.slug, 252 ) 253 return self.executor.stage_ok()
Save data in the current flow to the currently pending user. If no user is pending, a new user is created.