Ticket #6083: auth-uses-newforms.diff

File auth-uses-newforms.diff, 20.5 KB (added by cogat, 7 years ago)
  • django/contrib/comments/views/comments.py

     
    77from django.template import RequestContext
    88from django.contrib.comments.models import Comment, FreeComment, RATINGS_REQUIRED, RATINGS_OPTIONAL, IS_PUBLIC
    99from django.contrib.contenttypes.models import ContentType
    10 from django.contrib.auth.forms import AuthenticationForm
    1110from django.http import HttpResponseRedirect
    1211from django.utils.text import normalize_newlines
    1312from django.conf import settings
     
    1716
    1817COMMENTS_PER_PAGE = 20
    1918
     19
     20class AuthenticationForm(oldforms.Manipulator):
     21    """
     22    Oldforms-based Base class for authenticating users, extended by contrib.comments
     23    """
     24    def __init__(self, request=None):
     25        """
     26        If request is passed in, the manipulator will validate that cookies are
     27        enabled. Note that the request (a HttpRequest object) must have set a
     28        cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
     29        running this validator.
     30        """
     31        self.request = request
     32        self.fields = [
     33            oldforms.TextField(field_name="username", length=15, max_length=30, is_required=True,
     34                validator_list=[self.isValidUser, self.hasCookiesEnabled]),
     35            oldforms.PasswordField(field_name="password", length=15, max_length=30, is_required=True),
     36        ]
     37        self.user_cache = None
     38
     39    def hasCookiesEnabled(self, field_data, all_data):
     40        if self.request and not self.request.session.test_cookie_worked():
     41            raise validators.ValidationError, _("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in.")
     42
     43    def isValidUser(self, field_data, all_data):
     44        username = field_data
     45        password = all_data.get('password', None)
     46        self.user_cache = authenticate(username=username, password=password)
     47        if self.user_cache is None:
     48            raise validators.ValidationError, _("Please enter a correct username and password. Note that both fields are case-sensitive.")
     49        elif not self.user_cache.is_active:
     50            raise validators.ValidationError, _("This account is inactive.")
     51
     52    def get_user_id(self):
     53        if self.user_cache:
     54            return self.user_cache.id
     55        return None
     56
     57    def get_user(self):
     58        return self.user_cache
     59
    2060class PublicCommentManipulator(AuthenticationForm):
    2161    "Manipulator that handles public registered comments"
    2262    def __init__(self, user, ratings_required, ratings_range, num_rating_choices):
  • django/contrib/admin/views/auth.py

     
    1111def user_add_stage(request):
    1212    if not request.user.has_perm('auth.change_user'):
    1313        raise PermissionDenied
    14     manipulator = UserCreationForm()
    1514    if request.method == 'POST':
    16         new_data = request.POST.copy()
    17         errors = manipulator.get_validation_errors(new_data)
    18         if not errors:
    19             new_user = manipulator.save(new_data)
     15        form = UserCreationForm(request.POST)
     16        if form.is_valid():
     17            new_user = form.save()
    2018            msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user}
    2119            if "_addanother" in request.POST:
    2220                request.user.message_set.create(message=msg)
     
    2523                request.user.message_set.create(message=msg + ' ' + _("You may edit it again below."))
    2624                return HttpResponseRedirect('../%s/' % new_user.id)
    2725    else:
    28         errors = new_data = {}
    29     form = oldforms.FormWrapper(manipulator, new_data, errors)
     26        form = UserCreationForm()
    3027    return render_to_response('admin/auth/user/add_form.html', {
    3128        'title': _('Add user'),
    3229        'form': form,
     
    4946    if not request.user.has_perm('auth.change_user'):
    5047        raise PermissionDenied
    5148    user = get_object_or_404(User, pk=id)
    52     manipulator = AdminPasswordChangeForm(user)
    5349    if request.method == 'POST':
    54         new_data = request.POST.copy()
    55         errors = manipulator.get_validation_errors(new_data)
    56         if not errors:
    57             new_user = manipulator.save(new_data)
     50        form = AdminPasswordChangeForm(request_post=request.POST, user=user)
     51        if form.is_valid():
     52            new_user = form.save()
    5853            msg = _('Password changed successfully.')
    5954            request.user.message_set.create(message=msg)
    6055            return HttpResponseRedirect('..')
    6156    else:
    62         errors = new_data = {}
    63     form = oldforms.FormWrapper(manipulator, new_data, errors)
     57        form = AdminPasswordChangeForm(user=user)
    6458    return render_to_response('admin/auth/user/change_password.html', {
    6559        'title': _('Change password: %s') % escape(user.username),
    6660        'form': form,
  • django/contrib/auth/views.py

     
    11from django.contrib.auth.forms import AuthenticationForm
    22from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm
    3 from django import oldforms
    43from django.shortcuts import render_to_response
    54from django.template import RequestContext
    65from django.contrib.sites.models import Site, RequestSite
     
    1110
    1211def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
    1312    "Displays the login form and handles the login action."
    14     manipulator = AuthenticationForm(request)
    1513    redirect_to = request.REQUEST.get(redirect_field_name, '')
    16     if request.POST:
    17         errors = manipulator.get_validation_errors(request.POST)
    18         if not errors:
     14    if request.method == 'POST':
     15        form = AuthenticationForm(request.POST)
     16        if form.is_valid():
    1917            # Light security check -- make sure redirect_to isn't garbage.
    2018            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
    2119                from django.conf import settings
    2220                redirect_to = settings.LOGIN_REDIRECT_URL
    2321            from django.contrib.auth import login
    24             login(request, manipulator.get_user())
     22            login(request, form.get_user())
    2523            request.session.delete_test_cookie()
    2624            return HttpResponseRedirect(redirect_to)
    2725    else:
    28         errors = {}
     26        form = AuthenticationForm(request=request)
    2927    request.session.set_test_cookie()
    3028
    3129    if Site._meta.installed:
     
    3432        current_site = RequestSite(request)
    3533
    3634    return render_to_response(template_name, {
    37         'form': oldforms.FormWrapper(manipulator, request.POST, errors),
     35        'form': form,
    3836        redirect_field_name: redirect_to,
    3937        'site_name': current_site.name,
    4038    }, context_instance=RequestContext(request))
     
    6563
    6664def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html',
    6765        email_template_name='registration/password_reset_email.html'):
    68     new_data, errors = {}, {}
    69     form = PasswordResetForm()
    7066    if request.POST:
    71         new_data = request.POST.copy()
    72         errors = form.get_validation_errors(new_data)
    73         if not errors:
     67        form = PasswordResetForm(request.POST)
     68        if form.is_valid():
    7469            if is_admin_site:
    7570                form.save(domain_override=request.META['HTTP_HOST'])
    7671            else:
    7772                form.save(email_template_name=email_template_name)
    7873            return HttpResponseRedirect('%sdone/' % request.path)
    79     return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
     74    else:
     75        form = PasswordResetForm()     
     76    return render_to_response(template_name, {'form': form},
    8077        context_instance=RequestContext(request))
    8178
    8279def password_reset_done(request, template_name='registration/password_reset_done.html'):
     
    8481
    8582def password_change(request, template_name='registration/password_change_form.html'):
    8683    new_data, errors = {}, {}
    87     form = PasswordChangeForm(request.user)
    88     if request.POST:
    89         new_data = request.POST.copy()
    90         errors = form.get_validation_errors(new_data)
    91         if not errors:
    92             form.save(new_data)
     84    if request.method == 'POST':
     85        form = PasswordChangeForm(request.POST, request.user)
     86        if form.is_valid():
     87            form.save()
    9388            return HttpResponseRedirect('%sdone/' % request.path)
    94     return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
     89    else:
     90        form = PasswordChangeForm(user=request.user)
     91    return render_to_response(template_name, {'form': form},
    9592        context_instance=RequestContext(request))
    9693password_change = login_required(password_change)
    9794
  • django/contrib/auth/forms.py

     
    22from django.contrib.auth import authenticate
    33from django.contrib.sites.models import Site
    44from django.template import Context, loader
    5 from django.core import validators
    6 from django import oldforms
     5from django import newforms as forms
    76from django.utils.translation import ugettext as _
     7import re
    88
    9 class UserCreationForm(oldforms.Manipulator):
     9class UserCreationForm(forms.Form):
    1010    "A form that creates a user, with no privileges, from the given username and password."
    11     def __init__(self):
    12         self.fields = (
    13             oldforms.TextField(field_name='username', length=30, max_length=30, is_required=True,
    14                 validator_list=[validators.isAlphaNumeric, self.isValidUsername]),
    15             oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
    16             oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
    17                 validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
    18         )
     11    username=forms.CharField(label=_("username"), max_length=30, required=True)
     12    password1 = forms.CharField(label=_("password"), max_length=30, required=True, widget=forms.PasswordInput)
     13    password2 = forms.CharField(label=_("password (again)"), max_length=30, required=True, widget=forms.PasswordInput)
    1914
    20     def isValidUsername(self, field_data, all_data):
     15    #Following regex and error is borrowed from django.core.validators for backwards compatability for now (including i18n), but in anticipation of them being passed as parameters (or overridden).
     16    username_re = re.compile(r'^\w+$')
     17    username_re_validation_text = "This value must contain only letters, numbers and underscores."
     18
     19    def clean_password2(self):
     20        if self._errors: return
     21        if not self.cleaned_data['password1'] == self.cleaned_data['password2']:   
     22            raise forms.ValidationError, _("The two 'password' fields didn't match.")
     23        return self.cleaned_data['password2']
     24
     25    def clean_username(self):
     26        if not self.username_re.search(self.cleaned_data['username']):
     27            raise forms.ValidationError, _(self.username_re_validation_text)
    2128        try:
    22             User.objects.get(username=field_data)
     29            user = User.objects.get(username__exact=self.cleaned_data['username'])
    2330        except User.DoesNotExist:
    24             return
    25         raise validators.ValidationError, _('A user with that username already exists.')
    26 
    27     def save(self, new_data):
     31                return self.cleaned_data['username']
     32        raise forms.ValidationError, _('A user with that username already exists.')
     33       
     34    def save(self):
    2835        "Creates the user."
    29         return User.objects.create_user(new_data['username'], '', new_data['password1'])
     36        return User.objects.create_user(self.cleaned_data['username'], '', self.cleaned_data['password1'])
    3037
    31 class AuthenticationForm(oldforms.Manipulator):
     38class AuthenticationForm(forms.Form):
    3239    """
    3340    Base class for authenticating users. Extend this to get a form that accepts
    3441    username/password logins.
    3542    """
    36     def __init__(self, request=None):
     43    username = forms.CharField(label=_("username"), max_length=30, required=True)
     44    password = forms.CharField(label=_("password"), max_length=30, required=True, widget=forms.PasswordInput)
     45   
     46    def __init__(self, request_post=None, request=None):
    3747        """
    3848        If request is passed in, the manipulator will validate that cookies are
    3949        enabled. Note that the request (a HttpRequest object) must have set a
     
    4151        running this validator.
    4252        """
    4353        self.request = request
    44         self.fields = [
    45             oldforms.TextField(field_name="username", length=15, max_length=30, is_required=True,
    46                 validator_list=[self.isValidUser, self.hasCookiesEnabled]),
    47             oldforms.PasswordField(field_name="password", length=15, max_length=30, is_required=True),
    48         ]
    4954        self.user_cache = None
     55        super(AuthenticationForm, self).__init__(request_post)
    5056
    51     def hasCookiesEnabled(self, field_data, all_data):
     57    def clean(self):
     58        """
     59        Test that cookies are enabled and that self.username is a valid user with the right password.
     60        """
     61        if self._errors: return
    5262        if self.request and not self.request.session.test_cookie_worked():
    5363            raise validators.ValidationError, _("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in.")
    54 
    55     def isValidUser(self, field_data, all_data):
    56         username = field_data
    57         password = all_data.get('password', None)
     64        username = self.cleaned_data['username']
     65        password = self.cleaned_data['password']
    5866        self.user_cache = authenticate(username=username, password=password)
    5967        if self.user_cache is None:
    60             raise validators.ValidationError, _("Please enter a correct username and password. Note that both fields are case-sensitive.")
     68            raise forms.ValidationError, _("Please enter a correct username and password. Note that both fields are case-sensitive.")
    6169        elif not self.user_cache.is_active:
    62             raise validators.ValidationError, _("This account is inactive.")
     70            raise forms.ValidationError, _("This account is inactive.")
     71        return self.cleaned_data
    6372
    6473    def get_user_id(self):
    6574        if self.user_cache:
     
    6978    def get_user(self):
    7079        return self.user_cache
    7180
    72 class PasswordResetForm(oldforms.Manipulator):
     81class PasswordResetForm(forms.Form):
    7382    "A form that lets a user request a password reset"
    74     def __init__(self):
    75         self.fields = (
    76             oldforms.EmailField(field_name="email", length=40, is_required=True,
    77                 validator_list=[self.isValidUserEmail]),
    78         )
    79 
    80     def isValidUserEmail(self, new_data, all_data):
     83    email = forms.EmailField(label=_("email"), max_length=40, required=True)
     84   
     85    def clean_email(self):
    8186        "Validates that a user exists with the given e-mail address"
    82         self.users_cache = list(User.objects.filter(email__iexact=new_data))
     87        self.users_cache = list(User.objects.filter(email__iexact=self.cleaned_data['email']))
    8388        if len(self.users_cache) == 0:
    84             raise validators.ValidationError, _("That e-mail address doesn't have an associated user account. Are you sure you've registered?")
     89            raise forms.ValidationError, _("That e-mail address doesn't have an associated user account. Are you sure you've registered?")
     90        return self.cleaned_data['email']
    8591
    8692    def save(self, domain_override=None, email_template_name='registration/password_reset_email.html'):
    8793        "Calculates a new password randomly and sends it to the user"
     
    106112                }
    107113            send_mail(_('Password reset on %s') % site_name, t.render(Context(c)), None, [user.email])
    108114
    109 class PasswordChangeForm(oldforms.Manipulator):
    110     "A form that lets a user change his password."
    111     def __init__(self, user):
     115class PasswordChangeForm(forms.Form):
     116    "A form that lets a user change his or her password."
     117    old_password = forms.CharField(label=_("old password"), max_length=30, required=True, widget=forms.PasswordInput)
     118    new_password1 = forms.CharField(label=_("new password"), max_length=30, required=True, widget=forms.PasswordInput)
     119    new_password2 = forms.CharField(label=_("new password again"), max_length=30, required=True, widget=forms.PasswordInput)
     120
     121    def __init__(self, request_post=None, user=None):
    112122        self.user = user
    113         self.fields = (
    114             oldforms.PasswordField(field_name="old_password", length=30, max_length=30, is_required=True,
    115                 validator_list=[self.isValidOldPassword]),
    116             oldforms.PasswordField(field_name="new_password1", length=30, max_length=30, is_required=True,
    117                 validator_list=[validators.AlwaysMatchesOtherField('new_password2', _("The two 'new password' fields didn't match."))]),
    118             oldforms.PasswordField(field_name="new_password2", length=30, max_length=30, is_required=True),
    119         )
     123        super(PasswordChangeForm,self).__init__(request_post)
     124       
     125    def clean_new_password2(self):
     126        if self._errors: return
     127        if not self.cleaned_data['new_password1'] == self.cleaned_data['new_password2']:   
     128            raise forms.ValidationError, _("The two 'new password' fields didn't match.")
     129        return self.cleaned_data['new_password2']
    120130
    121     def isValidOldPassword(self, new_data, all_data):
     131    def clean_old_password(self):
    122132        "Validates that the old_password field is correct."
    123         if not self.user.check_password(new_data):
    124             raise validators.ValidationError, _("Your old password was entered incorrectly. Please enter it again.")
     133        if not self.user.check_password(self.cleaned_data['old_password']):
     134            raise forms.ValidationError, _("Your old password was entered incorrectly. Please enter it again.")
     135        return self.cleaned_data['old_password']
    125136
    126     def save(self, new_data):
     137    def save(self):
    127138        "Saves the new password."
    128         self.user.set_password(new_data['new_password1'])
     139        self.user.set_password(self.cleaned_data['new_password1'])
    129140        self.user.save()
    130141
    131 class AdminPasswordChangeForm(oldforms.Manipulator):
    132     "A form used to change the password of a user in the admin interface."
    133     def __init__(self, user):
     142class AdminPasswordChangeForm(forms.Form):
     143    "A form used to change the password of a user in the admin interface - it is not necessary to know the old password."
     144    new_password1 = forms.CharField(label=_("new password"), max_length=30, required=True, widget=forms.PasswordInput)
     145    new_password2 = forms.CharField(label=_("new password again"), max_length=30, required=True, widget=forms.PasswordInput)
     146
     147    def __init__(self, request_post=None, user=None):
    134148        self.user = user
    135         self.fields = (
    136             oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
    137             oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
    138                 validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
    139         )
     149        super(AdminPasswordChangeForm,self).__init__(request_post)
    140150
    141     def save(self, new_data):
     151    def clean_new_password2(self):
     152        if self._errors: return
     153        if not self.cleaned_data['new_password1'] == self.cleaned_data['new_password2']:   
     154            raise forms.ValidationError, _("The two 'new password' fields didn't match.")
     155        return self.cleaned_data['new_password2']
     156
     157    def save(self):
    142158        "Saves the new password."
    143         self.user.set_password(new_data['password1'])
     159        self.user.set_password(self.cleaned_data['new_password1'])
    144160        self.user.save()
  • AUTHORS

     
    325325    tstromberg@google.com
    326326    Makoto Tsuyuki <mtsuyuki@gmail.com>
    327327    tt@gurgle.no
     328    Greg Turner <http://gregturner.org>
    328329    Amit Upadhyay
    329330    Geert Vanderkelen
    330331    viestards.lists@gmail.com
Back to Top