You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

386 lines
14 KiB

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