Debian Codegraph @

django/contrib/auth/forms.py

raw
1 import logging
2 import unicodedata
3
4 from django import forms
5 from django.contrib.auth import authenticate, get_user_model, password_validation
6 from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX, identify_hasher
7 from django.contrib.auth.models import User
8 from django.contrib.auth.tokens import default_token_generator
9 from django.contrib.sites.shortcuts import get_current_site
10 from django.core.exceptions import ValidationError
11 from django.core.mail import EmailMultiAlternatives
12 from django.template import loader
13 from django.utils.encoding import force_bytes
14 from django.utils.http import urlsafe_base64_encode
15 from django.utils.text import capfirst
16 from django.utils.translation import gettext
17 from django.utils.translation import gettext_lazy as _
18 from django.views.decorators.debug import sensitive_variables
19
20 UserModel = get_user_model()
21 logger = logging.getLogger("django.contrib.auth")
22
23
24 def _unicode_ci_compare(s1, s2):
25 """
26 Perform case-insensitive comparison of two identifiers, using the
27 recommended algorithm from Unicode Technical Report 36, section
28 2.11.2(B)(2).
29 """
30 return (
31 unicodedata.normalize("NFKC", s1).casefold()
32 == unicodedata.normalize("NFKC", s2).casefold()
33 )
34
35
36 class ReadOnlyPasswordHashWidget(forms.Widget):
37 template_name = "auth/widgets/read_only_password_hash.html"
38 read_only = True
39
40 def get_context(self, name, value, attrs):
41 context = super().get_context(name, value, attrs)
42 usable_password = value and not value.startswith(UNUSABLE_PASSWORD_PREFIX)
43 summary = []
44 if usable_password:
45 try:
46 hasher = identify_hasher(value)
47 except ValueError:
48 summary.append(
49 {
50 "label": gettext(
51 "Invalid password format or unknown hashing algorithm."
52 )
53 }
54 )
55 else:
56 for key, value_ in hasher.safe_summary(value).items():
57 summary.append({"label": gettext(key), "value": value_})
58 else:
59 summary.append({"label": gettext("No password set.")})
60 context["summary"] = summary
61 context["button_label"] = (
62 _("Reset password") if usable_password else _("Set password")
63 )
64 return context
65
66 def id_for_label(self, id_):
67 return None
68
69
70 class ReadOnlyPasswordHashField(forms.Field):
71 widget = ReadOnlyPasswordHashWidget
72
73 def __init__(self, *args, **kwargs):
74 kwargs.setdefault("required", False)
75 kwargs.setdefault("disabled", True)
76 super().__init__(*args, **kwargs)
77
78
79 class UsernameField(forms.CharField):
80 def to_python(self, value):
81 value = super().to_python(value)
82 if self.max_length is not None and len(value) > self.max_length:
83 # Normalization can increase the string length (e.g.
84 # "ff" -> "ff", "½" -> "1⁄2") but cannot reduce it, so there is no
85 # point in normalizing invalid data. Moreover, Unicode
86 # normalization is very slow on Windows and can be a DoS attack
87 # vector.
88 return value
89 return unicodedata.normalize("NFKC", value)
90
91 def widget_attrs(self, widget):
92 return {
93 **super().widget_attrs(widget),
94 "autocapitalize": "none",
95 "autocomplete": "username",
96 }
97
98
99 class SetPasswordMixin:
100 """
101 Form mixin that validates and sets a password for a user.
102 """
103
104 error_messages = {
105 "password_mismatch": _("The two password fields didn’t match."),
106 }
107
108 @staticmethod
109 def create_password_fields(label1=_("Password"), label2=_("Password confirmation")):
110 password1 = forms.CharField(
111 label=label1,
112 required=True,
113 strip=False,
114 widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
115 help_text=password_validation.password_validators_help_text_html(),
116 )
117 password2 = forms.CharField(
118 label=label2,
119 required=True,
120 widget=forms.PasswordInput(attrs={"autocomplete": "new-password"}),
121 strip=False,
122 help_text=_("Enter the same password as before, for verification."),
123 )
124 return password1, password2
125
126 @sensitive_variables("password1", "password2")
127 def validate_passwords(
128 self,
129 password1_field_name="password1",
130 password2_field_name="password2",
131 ):
132 password1 = self.cleaned_data.get(password1_field_name)
133 password2 = self.cleaned_data.get(password2_field_name)
134
135 if password1 and password2 and password1 != password2:
136 error = ValidationError(
137 self.error_messages["password_mismatch"],
138 code="password_mismatch",
139 )
140 self.add_error(password2_field_name, error)
141
142 @sensitive_variables("password")
143 def validate_password_for_user(self, user, password_field_name="password2"):
144 password = self.cleaned_data.get(password_field_name)
145 if password:
146 try:
147 password_validation.validate_password(password, user)
148 except ValidationError as error:
149 self.add_error(password_field_name, error)
150
151 def set_password_and_save(self, user, password_field_name="password1", commit=True):
152 user.set_password(self.cleaned_data[password_field_name])
153 if commit:
154 user.save()
155 return user
156
157
158 class SetUnusablePasswordMixin:
159 """
160 Form mixin that allows setting an unusable password for a user.
161
162 This mixin should be used in combination with `SetPasswordMixin`.
163 """
164
165 usable_password_help_text = _(
166 "Whether the user will be able to authenticate using a password or not. "
167 "If disabled, they may still be able to authenticate using other backends, "
168 "such as Single Sign-On or LDAP."
169 )
170
171 @staticmethod
172 def create_usable_password_field(help_text=usable_password_help_text):
173 return forms.ChoiceField(
174 label=_("Password-based authentication"),
175 required=False,
176 initial="true",
177 choices={"true": _("Enabled"), "false": _("Disabled")},
178 widget=forms.RadioSelect(attrs={"class": "radiolist inline"}),
179 help_text=help_text,
180 )
181
182 @sensitive_variables("password1", "password2")
183 def validate_passwords(
184 self,
185 password1_field_name="password1",
186 password2_field_name="password2",
187 usable_password_field_name="usable_password",
188 ):
189 usable_password = (
190 self.cleaned_data.pop(usable_password_field_name, None) != "false"
191 )
192 self.cleaned_data["set_usable_password"] = usable_password
193
194 if not usable_password:
195 return
196
197 password1 = self.cleaned_data.get(password1_field_name)
198 password2 = self.cleaned_data.get(password2_field_name)
199
200 if not password1 and password1_field_name not in self.errors:
201 error = ValidationError(
202 self.fields[password1_field_name].error_messages["required"],
203 code="required",
204 )
205 self.add_error(password1_field_name, error)
206
207 if not password2 and password2_field_name not in self.errors:
208 error = ValidationError(
209 self.fields[password2_field_name].error_messages["required"],
210 code="required",
211 )
212 self.add_error(password2_field_name, error)
213
214 super().validate_passwords(password1_field_name, password2_field_name)
215
216 def validate_password_for_user(self, user, **kwargs):
217 if self.cleaned_data["set_usable_password"]:
218 super().validate_password_for_user(user, **kwargs)
219
220 def set_password_and_save(self, user, commit=True, **kwargs):
221 if self.cleaned_data["set_usable_password"]:
222 user = super().set_password_and_save(user, **kwargs, commit=commit)
223 else:
224 user.set_unusable_password()
225 if commit:
226 user.save()
227 return user
228
229
230 class BaseUserCreationForm(SetPasswordMixin, forms.ModelForm):
231 """
232 A form that creates a user, with no privileges, from the given username and
233 password.
234
235 This is the documented base class for customizing the user creation form.
236 It should be kept mostly unchanged to ensure consistency and compatibility.
237 """
238
239 password1, password2 = SetPasswordMixin.create_password_fields()
240
241 class Meta:
242 model = User
243 fields = ("username",)
244 field_classes = {"username": UsernameField}
245
246 def __init__(self, *args, **kwargs):
247 super().__init__(*args, **kwargs)
248 if self._meta.model.USERNAME_FIELD in self.fields:
249 self.fields[self._meta.model.USERNAME_FIELD].widget.attrs[
250 "autofocus"
251 ] = True
252
253 def clean(self):
254 self.validate_passwords()
255 return super().clean()
256
257 def _post_clean(self):
258 super()._post_clean()
259 # Validate the password after self.instance is updated with form data
260 # by super().
261 self.validate_password_for_user(self.instance)
262
263 def save(self, commit=True):
264 user = super().save(commit=False)
265 user = self.set_password_and_save(user, commit=commit)
266 if commit and hasattr(self, "save_m2m"):
267 self.save_m2m()
268 return user
269
270
271 class UserCreationForm(BaseUserCreationForm):
272 def clean_username(self):
273 """Reject usernames that differ only in case."""
274 username = self.cleaned_data.get("username")
275 if (
276 username
277 and self._meta.model.objects.filter(username__iexact=username).exists()
278 ):
279 self._update_errors(
280 ValidationError(
281 {
282 "username": self.instance.unique_error_message(
283 self._meta.model, ["username"]
284 )
285 }
286 )
287 )
288 else:
289 return username
290
291
292 class UserChangeForm(forms.ModelForm):
293 password = ReadOnlyPasswordHashField(
294 label=_("Password"),
295 help_text=_(
296 "Raw passwords are not stored, so there is no way to see "
297 "the user’s password."
298 ),
299 )
300
301 class Meta:
302 model = User
303 fields = "__all__"
304 field_classes = {"username": UsernameField}
305
306 def __init__(self, *args, **kwargs):
307 super().__init__(*args, **kwargs)
308 password = self.fields.get("password")
309 if password:
310 if self.instance and not self.instance.has_usable_password():
311 password.help_text = _(
312 "Enable password-based authentication for this user by setting a "
313 "password."
314 )
315 user_permissions = self.fields.get("user_permissions")
316 if user_permissions:
317 user_permissions.queryset = user_permissions.queryset.select_related(
318 "content_type"
319 )
320
321
322 class AuthenticationForm(forms.Form):
323 """
324 Base class for authenticating users. Extend this to get a form that accepts
325 username/password logins.
326 """
327
328 username = UsernameField(widget=forms.TextInput(attrs={"autofocus": True}))
329 password = forms.CharField(
330 label=_("Password"),
331 strip=False,
332 widget=forms.PasswordInput(attrs={"autocomplete": "current-password"}),
333 )
334
335 error_messages = {
336 "invalid_login": _(
337 "Please enter a correct %(username)s and password. Note that both "
338 "fields may be case-sensitive."
339 ),
340 "inactive": _("This account is inactive."),
341 }
342
343 def __init__(self, request=None, *args, **kwargs):
344 """
345 The 'request' parameter is set for custom auth use by subclasses.
346 The form data comes in via the standard 'data' kwarg.
347 """
348 self.request = request
349 self.user_cache = None
350 super().__init__(*args, **kwargs)
351
352 # Set the max length and label for the "username" field.
353 self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
354 username_max_length = self.username_field.max_length or 254
355 self.fields["username"].max_length = username_max_length
356 self.fields["username"].widget.attrs["maxlength"] = username_max_length
357 if self.fields["username"].label is None:
358 self.fields["username"].label = capfirst(self.username_field.verbose_name)
359
360 @sensitive_variables()
361 def clean(self):
362 username = self.cleaned_data.get("username")
363 password = self.cleaned_data.get("password")
364
365 if username is not None and password:
366 self.user_cache = authenticate(
367 self.request, username=username, password=password
368 )
369 if self.user_cache is None:
370 raise self.get_invalid_login_error()
371 else:
372 self.confirm_login_allowed(self.user_cache)
373
374 return self.cleaned_data
375
376 def confirm_login_allowed(self, user):
377 """
378 Controls whether the given User may log in. This is a policy setting,
379 independent of end-user authentication. This default behavior is to
380 allow login by active users, and reject login by inactive users.
381
382 If the given user cannot log in, this method should raise a
383 ``ValidationError``.
384
385 If the given user may log in, this method should return None.
386 """
387 if not user.is_active:
388 raise ValidationError(
389 self.error_messages["inactive"],
390 code="inactive",
391 )
392
393 def get_user(self):
394 return self.user_cache
395
396 def get_invalid_login_error(self):
397 return ValidationError(
398 self.error_messages["invalid_login"],
399 code="invalid_login",
400 params={"username": self.username_field.verbose_name},
401 )
402
403
404 class PasswordResetForm(forms.Form):
405 email = forms.EmailField(
406 label=_("Email"),
407 max_length=254,
408 widget=forms.EmailInput(attrs={"autocomplete": "email"}),
409 )
410
411 def send_mail(
412 self,
413 subject_template_name,
414 email_template_name,
415 context,
416 from_email,
417 to_email,
418 html_email_template_name=None,
419 ):
420 """
421 Send a django.core.mail.EmailMultiAlternatives to `to_email`.
422 """
423 subject = loader.render_to_string(subject_template_name, context)
424 # Email subject *must not* contain newlines
425 subject = "".join(subject.splitlines())
426 body = loader.render_to_string(email_template_name, context)
427
428 email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
429 if html_email_template_name is not None:
430 html_email = loader.render_to_string(html_email_template_name, context)
431 email_message.attach_alternative(html_email, "text/html")
432
433 try:
434 email_message.send()
435 except Exception:
436 logger.exception(
437 "Failed to send password reset email to %s", context["user"].pk
438 )
439
440 def get_users(self, email):
441 """Given an email, return matching user(s) who should receive a reset.
442
443 This allows subclasses to more easily customize the default policies
444 that prevent inactive users and users with unusable passwords from
445 resetting their password.
446 """
447 email_field_name = UserModel.get_email_field_name()
448 active_users = UserModel._default_manager.filter(
449 **{
450 "%s__iexact" % email_field_name: email,
451 "is_active": True,
452 }
453 )
454 return (
455 u
456 for u in active_users
457 if u.has_usable_password()
458 and _unicode_ci_compare(email, getattr(u, email_field_name))
459 )
460
461 def save(
462 self,
463 domain_override=None,
464 subject_template_name="registration/password_reset_subject.txt",
465 email_template_name="registration/password_reset_email.html",
466 use_https=False,
467 token_generator=default_token_generator,
468 from_email=None,
469 request=None,
470 html_email_template_name=None,
471 extra_email_context=None,
472 ):
473 """
474 Generate a one-use only link for resetting password and send it to the
475 user.
476 """
477 email = self.cleaned_data["email"]
478 if not domain_override:
479 current_site = get_current_site(request)
480 site_name = current_site.name
481 domain = current_site.domain
482 else:
483 site_name = domain = domain_override
484 email_field_name = UserModel.get_email_field_name()
485 for user in self.get_users(email):
486 user_email = getattr(user, email_field_name)
487 user_pk_bytes = force_bytes(UserModel._meta.pk.value_to_string(user))
488 context = {
489 "email": user_email,
490 "domain": domain,
491 "site_name": site_name,
492 "uid": urlsafe_base64_encode(user_pk_bytes),
493 "user": user,
494 "token": token_generator.make_token(user),
495 "protocol": "https" if use_https else "http",
496 **(extra_email_context or {}),
497 }
498 self.send_mail(
499 subject_template_name,
500 email_template_name,
501 context,
502 from_email,
503 user_email,
504 html_email_template_name=html_email_template_name,
505 )
506
507
508 class SetPasswordForm(SetPasswordMixin, forms.Form):
509 """
510 A form that lets a user set their password without entering the old
511 password
512 """
513
514 new_password1, new_password2 = SetPasswordMixin.create_password_fields(
515 label1=_("New password"), label2=_("New password confirmation")
516 )
517
518 def __init__(self, user, *args, **kwargs):
519 self.user = user
520 super().__init__(*args, **kwargs)
521
522 def clean(self):
523 self.validate_passwords("new_password1", "new_password2")
524 self.validate_password_for_user(self.user, "new_password2")
525 return super().clean()
526
527 def save(self, commit=True):
528 return self.set_password_and_save(self.user, "new_password1", commit=commit)
529
530
531 class PasswordChangeForm(SetPasswordForm):
532 """
533 A form that lets a user change their password by entering their old
534 password.
535 """
536
537 error_messages = {
538 **SetPasswordForm.error_messages,
539 "password_incorrect": _(
540 "Your old password was entered incorrectly. Please enter it again."
541 ),
542 }
543 old_password = forms.CharField(
544 label=_("Old password"),
545 strip=False,
546 widget=forms.PasswordInput(
547 attrs={"autocomplete": "current-password", "autofocus": True}
548 ),
549 )
550
551 field_order = ["old_password", "new_password1", "new_password2"]
552
553 @sensitive_variables("old_password")
554 def clean_old_password(self):
555 """
556 Validate that the old_password field is correct.
557 """
558 old_password = self.cleaned_data["old_password"]
559 if not self.user.check_password(old_password):
560 raise ValidationError(
561 self.error_messages["password_incorrect"],
562 code="password_incorrect",
563 )
564 return old_password
565
566
567 class AdminPasswordChangeForm(SetUnusablePasswordMixin, SetPasswordMixin, forms.Form):
568 """
569 A form used to change the password of a user in the admin interface.
570 """
571
572 required_css_class = "required"
573 usable_password_help_text = SetUnusablePasswordMixin.usable_password_help_text + (
574 '<ul id="id_unusable_warning" class="messagelist"><li class="warning">'
575 "If disabled, the current password for this user will be lost.</li></ul>"
576 )
577 password1, password2 = SetPasswordMixin.create_password_fields()
578
579 def __init__(self, user, *args, **kwargs):
580 self.user = user
581 super().__init__(*args, **kwargs)
582 self.fields["password1"].widget.attrs["autofocus"] = True
583 if self.user.has_usable_password():
584 self.fields["password1"].required = False
585 self.fields["password2"].required = False
586 self.fields["usable_password"] = (
587 SetUnusablePasswordMixin.create_usable_password_field(
588 self.usable_password_help_text
589 )
590 )
591
592 def clean(self):
593 self.validate_passwords()
594 self.validate_password_for_user(self.user)
595 return super().clean()
596
597 def save(self, commit=True):
598 """Save the new password."""
599 return self.set_password_and_save(self.user, commit=commit)
600
601 @property
602 def changed_data(self):
603 data = super().changed_data
604 if "set_usable_password" in data or "password1" in data and "password2" in data:
605 return ["password"]
606 return []
607
608
609 class AdminUserCreationForm(SetUnusablePasswordMixin, UserCreationForm):
610
611 usable_password = SetUnusablePasswordMixin.create_usable_password_field()
612
613 def __init__(self, *args, **kwargs):
614 super().__init__(*args, **kwargs)
615 self.fields["password1"].required = False
616 self.fields["password2"].required = False