PageRenderTime 18ms CodeModel.GetById 10ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/admin/forms.py

https://code.google.com/p/mango-py/
Python | 43 lines | 31 code | 6 blank | 6 comment | 9 complexity | 97ca54703215ef8ddb18750b49775b37 MD5 | raw file
 1from django import forms
 2
 3from django.contrib.auth import authenticate
 4from django.contrib.auth.forms import AuthenticationForm
 5from django.contrib.auth.models import User
 6
 7from django.utils.translation import ugettext_lazy, ugettext as _
 8
 9ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. "
10                              "Note that both fields are case-sensitive.")
11
12class AdminAuthenticationForm(AuthenticationForm):
13    """
14    A custom authentication form used in the admin app.
15
16    """
17    this_is_the_login_form = forms.BooleanField(widget=forms.HiddenInput, initial=1,
18        error_messages={'required': ugettext_lazy("Please log in again, because your session has expired.")})
19
20    def clean(self):
21        username = self.cleaned_data.get('username')
22        password = self.cleaned_data.get('password')
23        message = ERROR_MESSAGE
24
25        if username and password:
26            self.user_cache = authenticate(username=username, password=password)
27            if self.user_cache is None:
28                if u'@' in username:
29                    # Mistakenly entered e-mail address instead of username? Look it up.
30                    try:
31                        user = User.objects.get(email=username)
32                    except (User.DoesNotExist, User.MultipleObjectsReturned):
33                        # Nothing to do here, moving along.
34                        pass
35                    else:
36                        if user.check_password(password):
37                            message = _("Your e-mail address is not your username."
38                                        " Try '%s' instead.") % user.username
39                raise forms.ValidationError(message)
40            elif not self.user_cache.is_active or not self.user_cache.is_staff:
41                raise forms.ValidationError(message)
42        self.check_for_test_cookie()
43        return self.cleaned_data