forms.py 17 KB

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