forms.py 15 KB

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