PageRenderTime 2ms CodeModel.GetById 37ms app.highlight 8ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/itemisApp.gae/src/django/contrib/auth/forms.py

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