forms.py 16 KB

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