PageRenderTime 59ms CodeModel.GetById 25ms app.highlight 29ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/auth/forms.py

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