PageRenderTime 55ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/desktop/core/ext-py/Django/django/contrib/auth/forms.py

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