PageRenderTime 58ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/auth/forms.py

https://bitbucket.org/rattray/anonbox
Python | 218 lines | 211 code | 4 blank | 3 comment | 3 complexity | 305c65e3c72444b3252158a6e030b18f MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  1. from django.contrib.auth.models import User
  2. from django.contrib.auth import authenticate
  3. from django.contrib.auth.tokens import default_token_generator
  4. from django.contrib.sites.models import get_current_site
  5. from django.template import Context, loader
  6. from django import forms
  7. from django.utils.translation import ugettext_lazy as _
  8. from django.utils.http import urlsafe_base64_encode
  9. class UserCreationForm(forms.ModelForm):
  10. """
  11. A form that creates a user, with no privileges, from the given username and password.
  12. """
  13. username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
  14. help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
  15. error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
  16. password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
  17. password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput,
  18. help_text = _("Enter the same password as above, for verification."))
  19. class Meta:
  20. model = User
  21. fields = ("username",)
  22. def clean_username(self):
  23. username = self.cleaned_data["username"]
  24. try:
  25. User.objects.get(username=username)
  26. except User.DoesNotExist:
  27. return username
  28. raise forms.ValidationError(_("A user with that username already exists."))
  29. def clean_password2(self):
  30. password1 = self.cleaned_data.get("password1", "")
  31. password2 = self.cleaned_data["password2"]
  32. if password1 != password2:
  33. raise forms.ValidationError(_("The two password fields didn't match."))
  34. return password2
  35. def save(self, commit=True):
  36. user = super(UserCreationForm, self).save(commit=False)
  37. user.set_password(self.cleaned_data["password1"])
  38. if commit:
  39. user.save()
  40. return user
  41. class UserChangeForm(forms.ModelForm):
  42. username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
  43. help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
  44. error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
  45. class Meta:
  46. model = User
  47. def __init__(self, *args, **kwargs):
  48. super(UserChangeForm, self).__init__(*args, **kwargs)
  49. f = self.fields.get('user_permissions', None)
  50. if f is not None:
  51. f.queryset = f.queryset.select_related('content_type')
  52. class AuthenticationForm(forms.Form):
  53. """
  54. Base class for authenticating users. Extend this to get a form that accepts
  55. username/password logins.
  56. """
  57. username = forms.CharField(label=_("Username"), max_length=30)
  58. password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
  59. def __init__(self, request=None, *args, **kwargs):
  60. """
  61. If request is passed in, the form will validate that cookies are
  62. enabled. Note that the request (a HttpRequest object) must have set a
  63. cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
  64. running this validation.
  65. """
  66. self.request = request
  67. self.user_cache = None
  68. super(AuthenticationForm, self).__init__(*args, **kwargs)
  69. def clean(self):
  70. username = self.cleaned_data.get('username')
  71. password = self.cleaned_data.get('password')
  72. if username and password:
  73. self.user_cache = authenticate(username=username, password=password)
  74. if self.user_cache is None:
  75. raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
  76. elif not self.user_cache.is_active:
  77. raise forms.ValidationError(_("This account is inactive."))
  78. self.check_for_test_cookie()
  79. return self.cleaned_data
  80. def check_for_test_cookie(self):
  81. if self.request and not self.request.session.test_cookie_worked():
  82. raise forms.ValidationError(
  83. _("Your Web browser doesn't appear to have cookies enabled. "
  84. "Cookies are required for logging in."))
  85. def get_user_id(self):
  86. if self.user_cache:
  87. return self.user_cache.id
  88. return None
  89. def get_user(self):
  90. return self.user_cache
  91. class PasswordResetForm(forms.Form):
  92. email = forms.EmailField(label=_("E-mail"), max_length=75)
  93. def clean_email(self):
  94. """
  95. Validates that an active user exists with the given e-mail address.
  96. """
  97. email = self.cleaned_data["email"]
  98. self.users_cache = User.objects.filter(
  99. email__iexact=email,
  100. is_active=True
  101. )
  102. if len(self.users_cache) == 0:
  103. raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?"))
  104. return email
  105. def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
  106. use_https=False, token_generator=default_token_generator, from_email=None, request=None):
  107. """
  108. Generates a one-use only link for resetting password and sends to the user
  109. """
  110. from django.core.mail import send_mail
  111. for user in self.users_cache:
  112. if not domain_override:
  113. current_site = get_current_site(request)
  114. site_name = current_site.name
  115. domain = current_site.domain
  116. else:
  117. site_name = domain = domain_override
  118. t = loader.get_template(email_template_name)
  119. c = {
  120. 'email': user.email,
  121. 'domain': domain,
  122. 'site_name': site_name,
  123. 'uid': urlsafe_base64_encode(str(user.id)),
  124. 'user': user,
  125. 'token': token_generator.make_token(user),
  126. 'protocol': use_https and 'https' or 'http',
  127. }
  128. send_mail(_("Password reset on %s") % site_name,
  129. t.render(Context(c)), from_email, [user.email])
  130. class SetPasswordForm(forms.Form):
  131. """
  132. A form that lets a user change set his/her password without
  133. entering the old password
  134. """
  135. new_password1 = forms.CharField(label=_("New password"), widget=forms.PasswordInput)
  136. new_password2 = forms.CharField(label=_("New password confirmation"), widget=forms.PasswordInput)
  137. def __init__(self, user, *args, **kwargs):
  138. self.user = user
  139. super(SetPasswordForm, self).__init__(*args, **kwargs)
  140. def clean_new_password2(self):
  141. password1 = self.cleaned_data.get('new_password1')
  142. password2 = self.cleaned_data.get('new_password2')
  143. if password1 and password2:
  144. if password1 != password2:
  145. raise forms.ValidationError(_("The two password fields didn't match."))
  146. return password2
  147. def save(self, commit=True):
  148. self.user.set_password(self.cleaned_data['new_password1'])
  149. if commit:
  150. self.user.save()
  151. return self.user
  152. class PasswordChangeForm(SetPasswordForm):
  153. """
  154. A form that lets a user change his/her password by entering
  155. their old password.
  156. """
  157. old_password = forms.CharField(label=_("Old password"), widget=forms.PasswordInput)
  158. def clean_old_password(self):
  159. """
  160. Validates that the old_password field is correct.
  161. """
  162. old_password = self.cleaned_data["old_password"]
  163. if not self.user.check_password(old_password):
  164. raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again."))
  165. return old_password
  166. PasswordChangeForm.base_fields.keyOrder = ['old_password', 'new_password1', 'new_password2']
  167. class AdminPasswordChangeForm(forms.Form):
  168. """
  169. A form used to change the password of a user in the admin interface.
  170. """
  171. password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
  172. password2 = forms.CharField(label=_("Password (again)"), widget=forms.PasswordInput)
  173. def __init__(self, user, *args, **kwargs):
  174. self.user = user
  175. super(AdminPasswordChangeForm, self).__init__(*args, **kwargs)
  176. def clean_password2(self):
  177. password1 = self.cleaned_data.get('password1')
  178. password2 = self.cleaned_data.get('password2')
  179. if password1 and password2:
  180. if password1 != password2:
  181. raise forms.ValidationError(_("The two password fields didn't match."))
  182. return password2
  183. def save(self, commit=True):
  184. """
  185. Saves the new password.
  186. """
  187. self.user.set_password(self.cleaned_data["password1"])
  188. if commit:
  189. self.user.save()
  190. return self.user