PageRenderTime 180ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/django/branches/soc2009/model-validation/django/contrib/auth/forms.py

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