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

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

fixes a few issues and changes the user add view into newforms

  • 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/admin.py

     
    11from django.contrib.auth.forms import UserCreationForm
    22from django.contrib.auth.models import User, Group
    33from django.core.exceptions import PermissionDenied
    4 from django import oldforms, template
     4from django import template
    55from django.shortcuts import render_to_response
    66from django.http import HttpResponseRedirect
    77from django.utils.translation import ugettext, ugettext_lazy as _
     
    2727    def add_view(self, request):
    2828        if not self.has_change_permission(request):
    2929            raise PermissionDenied
    30         manipulator = UserCreationForm()
    3130        if request.method == 'POST':
    32             new_data = request.POST.copy()
    33             errors = manipulator.get_validation_errors(new_data)
    34             if not errors:
    35                 new_user = manipulator.save(new_data)
     31            form = UserCreationForm(request.POST)
     32            if form.is_valid():
     33                new_user = form.save()
    3634                msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user}
    3735                if "_addanother" in request.POST:
    3836                    request.user.message_set.create(message=msg)
     
    4139                    request.user.message_set.create(message=msg + ' ' + ugettext("You may edit it again below."))
    4240                    return HttpResponseRedirect('../%s/' % new_user.id)
    4341        else:
    44             errors = new_data = {}
    45         form = oldforms.FormWrapper(manipulator, new_data, errors)
     42            form = UserCreationForm()
    4643        return render_to_response('admin/auth/user/add_form.html', {
    4744            'title': _('Add user'),
    4845            'form': form,
  • django/contrib/auth/views.py

     
    11from django.contrib.auth.forms import AuthenticationForm
    22from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm, AdminPasswordChangeForm
    33from django.core.exceptions import PermissionDenied
    4 from django import oldforms
    54from django.shortcuts import render_to_response, get_object_or_404
    65from django.template import RequestContext
    76from django.contrib.sites.models import Site, RequestSite
     
    1413
    1514def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
    1615    "Displays the login form and handles the login action."
    17     manipulator = AuthenticationForm(request)
    1816    redirect_to = request.REQUEST.get(redirect_field_name, '')
    19     if request.POST:
    20         errors = manipulator.get_validation_errors(request.POST)
    21         if not errors:
     17    if request.method == 'POST':
     18        form = AuthenticationForm(request.POST)
     19        if form.is_valid():
    2220            # Light security check -- make sure redirect_to isn't garbage.
    2321            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
    2422                from django.conf import settings
    2523                redirect_to = settings.LOGIN_REDIRECT_URL
    2624            from django.contrib.auth import login
    27             login(request, manipulator.get_user())
    28             request.session.delete_test_cookie()
     25            login(request, form.get_user())           
     26            if request.session.test_cookie_worked():
     27                request.session.delete_test_cookie()
    2928            return HttpResponseRedirect(redirect_to)
    3029    else:
    31         errors = {}
     30        form = AuthenticationForm(request=request)
    3231    request.session.set_test_cookie()
    3332
    3433    if Site._meta.installed:
     
    3736        current_site = RequestSite(request)
    3837
    3938    return render_to_response(template_name, {
    40         'form': oldforms.FormWrapper(manipulator, request.POST, errors),
     39        'form': form,
    4140        redirect_field_name: redirect_to,
    4241        'site_name': current_site.name,
    4342    }, context_instance=RequestContext(request))
     
    6867
    6968def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html',
    7069        email_template_name='registration/password_reset_email.html'):
    71     new_data, errors = {}, {}
    72     form = PasswordResetForm()
    7370    if request.POST:
    74         new_data = request.POST.copy()
    75         errors = form.get_validation_errors(new_data)
    76         if not errors:
     71        form = PasswordResetForm(request.POST)
     72        if form.is_valid():
    7773            if is_admin_site:
    7874                form.save(domain_override=request.META['HTTP_HOST'])
    7975            else:
    8076                form.save(email_template_name=email_template_name)
    8177            return HttpResponseRedirect('%sdone/' % request.path)
    82     return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
     78    else:
     79        form = PasswordResetForm()     
     80    return render_to_response(template_name, {'form': form},
    8381        context_instance=RequestContext(request))
    8482
    8583def password_reset_done(request, template_name='registration/password_reset_done.html'):
     
    8785
    8886def password_change(request, template_name='registration/password_change_form.html'):
    8987    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)
     88    if request.method == 'POST':
     89        form = PasswordChangeForm(request.POST, request.user)
     90        if form.is_valid():
     91            form.save()
    9692            return HttpResponseRedirect('%sdone/' % request.path)
    97     return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
     93    else:
     94        form = PasswordChangeForm(user=request.user)
     95    return render_to_response(template_name, {'form': form},
    9896        context_instance=RequestContext(request))
    9997password_change = login_required(password_change)
    10098
     
    105103    if not request.user.has_perm('auth.change_user'):
    106104        raise PermissionDenied
    107105    user = get_object_or_404(User, pk=id)
    108     manipulator = AdminPasswordChangeForm(user)
    109106    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)
     107        form = AdminPasswordChangeForm(request.POST, user)
     108        if form.is_valid():
    114109            msg = _('Password changed successfully.')
    115110            request.user.message_set.create(message=msg)
    116111            return HttpResponseRedirect('..')
    117112    else:
    118         errors = new_data = {}
    119     form = oldforms.FormWrapper(manipulator, new_data, errors)
     113        form = AdminPasswordChangeForm(None,user)
    120114    return render_to_response('admin/auth/user/change_password.html', {
    121115        'title': _('Change password: %s') % escape(user.username),
    122116        'form': form,
  • django/contrib/auth/models.py

     
    365365    def is_authenticated(self):
    366366        return False
    367367
    368 # Register the admin options for these models.
    369 from django.contrib.auth import admin
  • 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

     
    340340    tstromberg@google.com
    341341    Makoto Tsuyuki <mtsuyuki@gmail.com>
    342342    tt@gurgle.no
     343    Greg Turner <http://gregturner.org>
    343344    Amit Upadhyay
    344345    Geert Vanderkelen
    345346    I.S. van Oostveen <v.oostveen@idca.nl>
Back to Top