Ticket #6083: auth-uses-newforms-3.diff

File auth-uses-newforms-3.diff, 20.0 KB (added by Michael Newman <newmaniese@…>, 16 years ago)

Fixed reference to comments.auth.py and added fix to admin.templates.admin.auth.user.change_password.html for new forms and slight change to the way contrib.auth.forms.AdminPasswordChangeForm cleans the form, and changed auth.views.py to use AdminPasswordChangeForm instead of the now nonexistent old form way

  • 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/templates/admin/auth/user/change_password.html

     
    2727<p>{% blocktrans with original.username|escape as username %}Enter a new password for the user <strong>{{ username }}</strong>.{% endblocktrans %}</p>
    2828
    2929<fieldset class="module aligned">
    30 
     30{% if form.non_field_errors %}
     31{{form.non_field_errors}}
     32{% endif %}
    3133<div class="form-row">
    32   {{ form.password1.html_error_list }}
     34  {% if form.password1.errors %}
     35  {{ form.password1.errors }}
     36  {% endif %}
    3337  <label for="id_password1" class="required">{% trans 'Password' %}:</label> {{ form.password1 }}
    3438</div>
    3539
    3640<div class="form-row">
    37   {{ form.password2.html_error_list }}
     41  {% if form.password2.errors %}
     42  {{ form.password2.errors }}
     43  {% endif %}
    3844  <label for="id_password2" class="required">{% trans 'Password (again)' %}:</label> {{ form.password2 }}
    3945  <p class="help">{% trans 'Enter the same password as above, for verification.' %}</p>
    4046</div>
  • django/contrib/auth/views.py

     
    1414
    1515def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
    1616    "Displays the login form and handles the login action."
    17     manipulator = AuthenticationForm(request)
    1817    redirect_to = request.REQUEST.get(redirect_field_name, '')
    19     if request.POST:
    20         errors = manipulator.get_validation_errors(request.POST)
    21         if not errors:
     18    if request.method == 'POST':
     19        form = AuthenticationForm(request.POST)
     20        if form.is_valid():
    2221            # Light security check -- make sure redirect_to isn't garbage.
    2322            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
    2423                from django.conf import settings
    2524                redirect_to = settings.LOGIN_REDIRECT_URL
    2625            from django.contrib.auth import login
    27             login(request, manipulator.get_user())
    28             request.session.delete_test_cookie()
     26            login(request, form.get_user())           
     27            if request.session.test_cookie_worked():
     28                request.session.delete_test_cookie()
    2929            return HttpResponseRedirect(redirect_to)
    3030    else:
    31         errors = {}
     31        form = AuthenticationForm(request=request)
    3232    request.session.set_test_cookie()
    3333
    3434    if Site._meta.installed:
     
    3737        current_site = RequestSite(request)
    3838
    3939    return render_to_response(template_name, {
    40         'form': oldforms.FormWrapper(manipulator, request.POST, errors),
     40        'form': form,
    4141        redirect_field_name: redirect_to,
    4242        'site_name': current_site.name,
    4343    }, context_instance=RequestContext(request))
     
    6868
    6969def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html',
    7070        email_template_name='registration/password_reset_email.html'):
    71     new_data, errors = {}, {}
    72     form = PasswordResetForm()
    7371    if request.POST:
    74         new_data = request.POST.copy()
    75         errors = form.get_validation_errors(new_data)
    76         if not errors:
     72        form = PasswordResetForm(request.POST)
     73        if form.is_valid():
    7774            if is_admin_site:
    7875                form.save(domain_override=request.META['HTTP_HOST'])
    7976            else:
    8077                form.save(email_template_name=email_template_name)
    8178            return HttpResponseRedirect('%sdone/' % request.path)
    82     return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
     79    else:
     80        form = PasswordResetForm()     
     81    return render_to_response(template_name, {'form': form},
    8382        context_instance=RequestContext(request))
    8483
    8584def password_reset_done(request, template_name='registration/password_reset_done.html'):
     
    8786
    8887def password_change(request, template_name='registration/password_change_form.html'):
    8988    new_data, errors = {}, {}
    90     form = PasswordChangeForm(request.user)
    91     if request.POST:
    92         new_data = request.POST.copy()
    93         errors = form.get_validation_errors(new_data)
    94         if not errors:
    95             form.save(new_data)
     89    if request.method == 'POST':
     90        form = PasswordChangeForm(request.POST, request.user)
     91        if form.is_valid():
     92            form.save()
    9693            return HttpResponseRedirect('%sdone/' % request.path)
    97     return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
     94    else:
     95        form = PasswordChangeForm(user=request.user)
     96    return render_to_response(template_name, {'form': form},
    9897        context_instance=RequestContext(request))
    9998password_change = login_required(password_change)
    10099
     
    105104    if not request.user.has_perm('auth.change_user'):
    106105        raise PermissionDenied
    107106    user = get_object_or_404(User, pk=id)
    108     manipulator = AdminPasswordChangeForm(user)
    109107    if request.method == 'POST':
    110         new_data = request.POST.copy()
    111         errors = manipulator.get_validation_errors(new_data)
    112         if not errors:
    113             new_user = manipulator.save(new_data)
     108        form = AdminPasswordChangeForm(request.POST, user)
     109        if form.is_valid():
    114110            msg = _('Password changed successfully.')
    115111            request.user.message_set.create(message=msg)
    116112            return HttpResponseRedirect('..')
    117113    else:
    118         errors = new_data = {}
    119     form = oldforms.FormWrapper(manipulator, new_data, errors)
     114        form = AdminPasswordChangeForm(None,user)
    120115    return render_to_response('admin/auth/user/change_password.html', {
    121116        'title': _('Change password: %s') % escape(user.username),
    122117        'form': form,
  • 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    password1 = forms.CharField(label=_("new password"), max_length=30, required=True, widget=forms.PasswordInput)
     145    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(self):
     152        if self._errors: return
     153        if self.cleaned_data['password1'] == self.cleaned_data['password2']:   
     154            return self.cleaned_data
     155        raise forms.ValidationError, _("The two 'new password' fields didn't match.")
     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['password1'])
    144160        self.user.save()
  • AUTHORS

     
    335335    tstromberg@google.com
    336336    Makoto Tsuyuki <mtsuyuki@gmail.com>
    337337    tt@gurgle.no
     338    Greg Turner <http://gregturner.org>
    338339    Amit Upadhyay
    339340    Geert Vanderkelen
    340341    I.S. van Oostveen <v.oostveen@idca.nl>
Back to Top