PageRenderTime 134ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/auth/forms.py

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