PageRenderTime 100ms CodeModel.GetById 56ms app.highlight 40ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/auth/forms.py

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