forms.py 15 KB

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