PageRenderTime 52ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/auth/forms.py

https://github.com/rohanza/django
Python | 215 lines | 208 code | 4 blank | 3 comment | 3 complexity | 8c21ede5f0eb4447cda8a76785c9085e MD5 | raw file
  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 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. 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 a user exists with the given e-mail address.
  96. """
  97. email = self.cleaned_data["email"]
  98. self.users_cache = User.objects.filter(email__iexact=email)
  99. if len(self.users_cache) == 0:
  100. raise forms.ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?"))
  101. return email
  102. def save(self, domain_override=None, email_template_name='registration/password_reset_email.html',
  103. use_https=False, token_generator=default_token_generator, from_email=None, request=None):
  104. """
  105. Generates a one-use only link for resetting password and sends to the user
  106. """
  107. from django.core.mail import send_mail
  108. for user in self.users_cache:
  109. if not domain_override:
  110. current_site = get_current_site(request)
  111. site_name = current_site.name
  112. domain = current_site.domain
  113. else:
  114. site_name = domain = domain_override
  115. t = loader.get_template(email_template_name)
  116. c = {
  117. 'email': user.email,
  118. 'domain': domain,
  119. 'site_name': site_name,
  120. 'uid': int_to_base36(user.id),
  121. 'user': user,
  122. 'token': token_generator.make_token(user),
  123. 'protocol': use_https and 'https' or 'http',
  124. }
  125. send_mail(_("Password reset on %s") % site_name,
  126. t.render(Context(c)), from_email, [user.email])
  127. class SetPasswordForm(forms.Form):
  128. """
  129. A form that lets a user change set his/her password without
  130. entering the old password
  131. """
  132. new_password1 = forms.CharField(label=_("New password"), widget=forms.PasswordInput)
  133. new_password2 = forms.CharField(label=_("New password confirmation"), widget=forms.PasswordInput)
  134. def __init__(self, user, *args, **kwargs):
  135. self.user = user
  136. super(SetPasswordForm, self).__init__(*args, **kwargs)
  137. def clean_new_password2(self):
  138. password1 = self.cleaned_data.get('new_password1')
  139. password2 = self.cleaned_data.get('new_password2')
  140. if password1 and password2:
  141. if password1 != password2:
  142. raise forms.ValidationError(_("The two password fields didn't match."))
  143. return password2
  144. def save(self, commit=True):
  145. self.user.set_password(self.cleaned_data['new_password1'])
  146. if commit:
  147. self.user.save()
  148. return self.user
  149. class PasswordChangeForm(SetPasswordForm):
  150. """
  151. A form that lets a user change his/her password by entering
  152. their old password.
  153. """
  154. old_password = forms.CharField(label=_("Old password"), widget=forms.PasswordInput)
  155. def clean_old_password(self):
  156. """
  157. Validates that the old_password field is correct.
  158. """
  159. old_password = self.cleaned_data["old_password"]
  160. if not self.user.check_password(old_password):
  161. raise forms.ValidationError(_("Your old password was entered incorrectly. Please enter it again."))
  162. return old_password
  163. PasswordChangeForm.base_fields.keyOrder = ['old_password', 'new_password1', 'new_password2']
  164. class AdminPasswordChangeForm(forms.Form):
  165. """
  166. A form used to change the password of a user in the admin interface.
  167. """
  168. password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
  169. password2 = forms.CharField(label=_("Password (again)"), widget=forms.PasswordInput)
  170. def __init__(self, user, *args, **kwargs):
  171. self.user = user
  172. super(AdminPasswordChangeForm, self).__init__(*args, **kwargs)
  173. def clean_password2(self):
  174. password1 = self.cleaned_data.get('password1')
  175. password2 = self.cleaned_data.get('password2')
  176. if password1 and password2:
  177. if password1 != password2:
  178. raise forms.ValidationError(_("The two password fields didn't match."))
  179. return password2
  180. def save(self, commit=True):
  181. """
  182. Saves the new password.
  183. """
  184. self.user.set_password(self.cleaned_data["password1"])
  185. if commit:
  186. self.user.save()
  187. return self.user