forms.py 20 KB

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