forms.py 20 KB

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