Ticket #6318: auth.diff

File auth.diff, 20.2 KB (added by Shabda <shabda.raaj@…>, 8 years ago)

Patch modifying contrib/auth/views.py and contrib/auth/forms.py

  • django/contrib/auth/forms.py

     
     1from django import newforms as forms
     2import re
     3from django.newforms import ValidationError
    14from django.contrib.auth.models import User
    25from django.contrib.auth import authenticate
    36from django.contrib.sites.models import Site
     
    25from django.template import Context, loader
    3 from django.core import validators
    4 from django import oldforms
    56from django.utils.translation import ugettext as _
    67
    7 class UserCreationForm(oldforms.Manipulator):
    8     "A form that creates a user, with no privileges, from the given username and password."
    9     def __init__(self):
    10         self.fields = (
    11             oldforms.TextField(field_name='username', length=30, max_length=30, is_required=True,
    12                 validator_list=[validators.isAlphaNumeric, self.isValidUsername]),
    13             oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
    14             oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
    15                 validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
    16         )
     8class UserCreationForm(forms.Form):
     9    """A form that creates a user, with no privileges, from the given username and password."""
     10    username = forms.CharField(max_length = 30, required = True)
     11    password1 = forms.CharField(max_length = 30, required = True, widget = forms.PasswordInput)
     12    password2 = forms.CharField(max_length = 30, required = True, widget = forms.PasswordInput)
    1713
    18     def isValidUsername(self, field_data, all_data):
     14    def clean_username (self):
     15        alnum_re = re.compile(r'^\w+$')
     16        if not alnum_re.search(self.cleaned_data['username']):
     17            raise ValidationError("This value must contain only letters, numbers and underscores.")
     18        self.isValidUsername()
     19        return self.cleaned_data['username']
     20
     21    def clean (self):
     22        if self.cleaned_data['password1'] != self.cleaned_data['password2']:
     23            raise ValidationError(_("The two password fields didn't match."))
     24        return super(forms.Form, self).clean()
     25       
     26    def isValidUsername(self):
    1927        try:
    20             User.objects.get(username=field_data)
     28            User.objects.get(username=self.cleaned_data['username'])
    2129        except User.DoesNotExist:
    2230            return
    23         raise validators.ValidationError, _('A user with that username already exists.')
     31        raise ValidationError(_('A user with that username already exists.'))
    2432
    25     def save(self, new_data):
    26         "Creates the user."
    27         return User.objects.create_user(new_data['username'], '', new_data['password1'])
    28 
    29 class AuthenticationForm(oldforms.Manipulator):
     33class AuthenticationForm(forms.Form):
    3034    """
    3135    Base class for authenticating users. Extend this to get a form that accepts
    3236    username/password logins.
    3337    """
    34     def __init__(self, request=None):
    35         """
    36         If request is passed in, the manipulator will validate that cookies are
    37         enabled. Note that the request (a HttpRequest object) must have set a
    38         cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
    39         running this validator.
    40         """
     38    username = forms.CharField(required = True, max_length = 30)
     39    password = forms.CharField(required = True, max_length = 30, widget = forms.PasswordInput)
     40    def set_request (self, request):
    4141        self.request = request
    42         self.fields = [
    43             oldforms.TextField(field_name="username", length=15, max_length=30, is_required=True,
    44                 validator_list=[self.isValidUser, self.hasCookiesEnabled]),
    45             oldforms.PasswordField(field_name="password", length=15, max_length=30, is_required=True),
    46         ]
    47         self.user_cache = None
     42       
     43       
     44    def clean (self):
     45        user = authenticate(username=self.cleaned_data['username'], password=self.cleaned_data['password'])
     46        if self.request and not self.request.session.test_cookie_worked():
     47            raise ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))
     48        if user is None:
     49            raise ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
     50        elif not user.is_active:
     51            raise ValidationError(_("This account is inactive."))
     52        else:
     53            self.user = user
     54        return super(forms.Form, self).clean()
    4855
    49     def hasCookiesEnabled(self, field_data, all_data):
    50         if self.request and not self.request.session.test_cookie_worked():
    51             raise validators.ValidationError, _("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in.")
     56class PasswordResetForm(forms.Form):
     57    """A form that lets a user request a password reset"""
     58    email = forms.EmailField(required = True)
    5259
    53     def isValidUser(self, field_data, all_data):
    54         username = field_data
    55         password = all_data.get('password', None)
    56         self.user_cache = authenticate(username=username, password=password)
    57         if self.user_cache is None:
    58             raise validators.ValidationError, _("Please enter a correct username and password. Note that both fields are case-sensitive.")
    59         elif not self.user_cache.is_active:
    60             raise validators.ValidationError, _("This account is inactive.")
     60    def clean_email (self):
     61        try:
     62           self.user = User.objects.get(email__iexact=self.cleaned_data['email'])
     63        except User.DoesNotExist:
     64            print '***'
     65            raise ValidationError(_("That e-mail address doesn't have an associated user account. Are you sure you've registered?"))
     66        return self.cleaned_data['email']
    6167
    62     def get_user_id(self):
    63         if self.user_cache:
    64             return self.user_cache.id
    65         return None
    66 
    67     def get_user(self):
    68         return self.user_cache
    69 
    70 class PasswordResetForm(oldforms.Manipulator):
    71     "A form that lets a user request a password reset"
    72     def __init__(self):
    73         self.fields = (
    74             oldforms.EmailField(field_name="email", length=40, is_required=True,
    75                 validator_list=[self.isValidUserEmail]),
    76         )
    77 
    78     def isValidUserEmail(self, new_data, all_data):
    79         "Validates that a user exists with the given e-mail address"
    80         self.users_cache = list(User.objects.filter(email__iexact=new_data))
    81         if len(self.users_cache) == 0:
    82             raise validators.ValidationError, _("That e-mail address doesn't have an associated user account. Are you sure you've registered?")
    83 
    8468    def save(self, domain_override=None, email_template_name='registration/password_reset_email.html'):
    8569        "Calculates a new password randomly and sends it to the user"
    8670        from django.core.mail import send_mail
    87         for user in self.users_cache:
    88             new_pass = User.objects.make_random_password()
    89             user.set_password(new_pass)
    90             user.save()
    91             if not domain_override:
    92                 current_site = Site.objects.get_current()
    93                 site_name = current_site.name
    94                 domain = current_site.domain
    95             else:
    96                 site_name = domain = domain_override
    97             t = loader.get_template(email_template_name)
    98             c = {
    99                 'new_password': new_pass,
    100                 'email': user.email,
    101                 'domain': domain,
    102                 'site_name': site_name,
    103                 'user': user,
    104                 }
    105             send_mail(_('Password reset on %s') % site_name, t.render(Context(c)), None, [user.email])
     71        user = self.user
     72        new_pass = User.objects.make_random_password()
     73        user.set_password(new_pass)
     74        user.save()
     75        if not domain_override:
     76            current_site = Site.objects.get_current()
     77            site_name = current_site.name
     78            domain = current_site.domain
     79        else:
     80            site_name = domain = domain_override
     81        t = loader.get_template(email_template_name)
     82        c = {
     83        'new_password': new_pass,
     84        'email': user.email,
     85        'domain': domain,
     86        'site_name': site_name,
     87        'user': user,
     88        }
     89        send_mail(_('Password reset on %s') % site_name, t.render(Context(c)), None, [user.email])
    10690
    107 class PasswordChangeForm(oldforms.Manipulator):
    108     "A form that lets a user change his password."
    109     def __init__(self, user):
     91class PasswordChangeForm(forms.Form):
     92    """A form that lets a user change his password."""
     93    old_password = forms.CharField(widget=forms.PasswordInput, required = True, max_length = 30)
     94    new_password1 = forms.CharField(widget=forms.PasswordInput, required = True, max_length = 30)
     95    new_password2 = forms.CharField(widget=forms.PasswordInput, required = True, max_length = 30)
     96
     97    def set_user (self, user):
    11098        self.user = user
    111         self.fields = (
    112             oldforms.PasswordField(field_name="old_password", length=30, max_length=30, is_required=True,
    113                 validator_list=[self.isValidOldPassword]),
    114             oldforms.PasswordField(field_name="new_password1", length=30, max_length=30, is_required=True,
    115                 validator_list=[validators.AlwaysMatchesOtherField('new_password2', _("The two 'new password' fields didn't match."))]),
    116             oldforms.PasswordField(field_name="new_password2", length=30, max_length=30, is_required=True),
    117         )
    11899
    119     def isValidOldPassword(self, new_data, all_data):
    120         "Validates that the old_password field is correct."
    121         if not self.user.check_password(new_data):
    122             raise validators.ValidationError, _("Your old password was entered incorrectly. Please enter it again.")
     100    def clean_old_password (self):
     101        if not self.user.check_password(self.cleaned_data['old_password']):
     102            raise ValidationError(_("Your old password was entered incorrectly. Please enter it again."))
     103        return self.cleaned_data['old_password']
    123104
    124     def save(self, new_data):
     105    def clean (self):
     106         if self.cleaned_data['new_password1'] != self.cleaned_data['new_password2']:
     107             raise ValidationError(_("The two new password fields didn't match."))
     108         return super(forms.Form, self).clean()
     109
     110    def save (self, new_password):
    125111        "Saves the new password."
    126         self.user.set_password(new_data['new_password1'])
     112        self.user.set_password(new_password)
    127113        self.user.save()
    128114
    129 class AdminPasswordChangeForm(oldforms.Manipulator):
    130     "A form used to change the password of a user in the admin interface."
    131     def __init__(self, user):
     115class AdminPasswordChangeForm(forms.Form):
     116    """A form used to change the password of a user in the admin interface."""
     117    password1 = forms.CharField(widget = forms.PasswordInput, max_length = 30, required = True)
     118    password2 = forms.CharField(widget = forms.PasswordInput, max_length = 30, required = True)
     119   
     120    def set_user (self, user):
    132121        self.user = user
    133         self.fields = (
    134             oldforms.PasswordField(field_name='password1', length=30, max_length=60, is_required=True),
    135             oldforms.PasswordField(field_name='password2', length=30, max_length=60, is_required=True,
    136                 validator_list=[validators.AlwaysMatchesOtherField('password1', _("The two password fields didn't match."))]),
    137         )
     122       
     123    def clean (self):
     124        if self.cleaned_data['password1'] != self.cleaned_data['password2']:
     125            raise ValidationError(_("The two password fields didn't match."))
     126        return super(forms.Form, self).clean()
    138127
    139     def save(self, new_data):
    140         "Saves the new password."
    141         self.user.set_password(new_data['password1'])
    142         self.user.save()
     128    def save(self):
     129        self.user.set_password(self.cleaned_data['password1'])
     130        self.user.save()     
     131     
     132 No newline at end of file
  • django/contrib/auth/views.py

     
    1 from django.contrib.auth.forms import AuthenticationForm
    2 from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm, AdminPasswordChangeForm
    3 from django.core.exceptions import PermissionDenied
    4 from django import oldforms
     1import forms
    52from django.shortcuts import render_to_response, get_object_or_404
     3from django.http import HttpResponse, HttpResponseRedirect
     4from django.contrib.auth.models import User
     5from django.contrib.auth import REDIRECT_FIELD_NAME
    66from django.template import RequestContext
    77from django.contrib.sites.models import Site, RequestSite
    8 from django.http import HttpResponseRedirect
    9 from django.contrib.auth.decorators import login_required
    10 from django.contrib.auth import REDIRECT_FIELD_NAME
    11 from django.utils.html import escape
    128from django.utils.translation import ugettext as _
    13 from django.contrib.auth.models import User
     9from django.contrib.auth.decorators import login_required
     10from django.core.exceptions import PermissionDenied
    1411
     12
     13def user_creation (request, template_name='registration/create_user.html'):
     14    if request.method == 'POST':
     15       user_creation_form = forms.UserCreationForm(request.POST)
     16       if user_creation_form.is_valid():
     17          username = user_creation_form.cleaned_data['username']
     18          password = user_creation_form.cleaned_data['password1']
     19          User.objects.create_user(username, '', password)
     20          return HttpResponseRedirect('.')       
     21    elif request.method == 'GET':
     22       user_creation_form = forms.UserCreationForm()
     23    return render_to_response(template_name, {'form':user_creation_form}, context_instance=RequestContext(request))
     24
    1525def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME):
    16     "Displays the login form and handles the login action."
    17     manipulator = AuthenticationForm(request)
     26    """Displays the login form and handles the login action."""
    1827    redirect_to = request.REQUEST.get(redirect_field_name, '')
    19     if request.POST:
    20         errors = manipulator.get_validation_errors(request.POST)
    21         if not errors:
     28    if Site._meta.installed:
     29        current_site = Site.objects.get_current()
     30    else:
     31        current_site = RequestSite(request)
     32    if request.method == 'POST':
     33       login_form = forms.AuthenticationForm(request.POST)
     34       login_form.set_request(request)
     35       if login_form.is_valid():
    2236            # Light security check -- make sure redirect_to isn't garbage.
    2337            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
    2438                from django.conf import settings
    2539                redirect_to = settings.LOGIN_REDIRECT_URL
    2640            from django.contrib.auth import login
    27             login(request, manipulator.get_user())
     41            user = login_form.user
     42            login(request, user)
    2843            request.session.delete_test_cookie()
    2944            return HttpResponseRedirect(redirect_to)
    30     else:
    31         errors = {}
     45    elif request.method == 'GET':
     46        login_form = forms.AuthenticationForm()
    3247    request.session.set_test_cookie()
    33 
    34     if Site._meta.installed:
    35         current_site = Site.objects.get_current()
    36     else:
    37         current_site = RequestSite(request)
    38 
    3948    return render_to_response(template_name, {
    40         'form': oldforms.FormWrapper(manipulator, request.POST, errors),
     49        'form': login_form,
    4150        redirect_field_name: redirect_to,
    4251        'site_name': current_site.name,
    4352    }, context_instance=RequestContext(request))
     
    6877
    6978def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html',
    7079        email_template_name='registration/password_reset_email.html'):
    71     new_data, errors = {}, {}
    72     form = PasswordResetForm()
    73     if request.POST:
    74         new_data = request.POST.copy()
    75         errors = form.get_validation_errors(new_data)
    76         if not errors:
     80    if request.method == 'POST':
     81       form = forms.PasswordResetForm(request.POST)
     82       if form.is_valid():
    7783            if is_admin_site:
    7884                form.save(domain_override=request.META['HTTP_HOST'])
    7985            else:
    8086                form.save(email_template_name=email_template_name)
    81             return HttpResponseRedirect('%sdone/' % request.path)
    82     return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
    83         context_instance=RequestContext(request))
     87            return HttpResponseRedirect('%sdone/' % request.path)       
     88    elif request.method == 'GET':
     89        form = forms.PasswordResetForm()
     90    print template_name
     91    return render_to_response(template_name, {'form': form}, context_instance=RequestContext(request))
    8492
    85 def password_reset_done(request, template_name='registration/password_reset_done.html'):
    86     return render_to_response(template_name, context_instance=RequestContext(request))
     93def index(request):
     94    return render_to_response('registration/password_reset_form.html', {}, context_instance=RequestContext(request))
    8795
    8896def password_change(request, template_name='registration/password_change_form.html'):
    89     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)
    96             return HttpResponseRedirect('%sdone/' % request.path)
    97     return render_to_response(template_name, {'form': oldforms.FormWrapper(form, new_data, errors)},
     97    if request.method == 'POST':
     98        form = forms.PasswordChangeForm(request.POST)
     99        form.set_user(request.user)
     100        if form.is_valid():
     101            form.save(form.cleaned_data['new_password1'])
     102            return HttpResponseRedirect('%sdone/' % request.path)       
     103    if request.method == 'GET':
     104        form = forms.PasswordChangeForm()
     105    return render_to_response(template_name, {'form': form},
    98106        context_instance=RequestContext(request))
    99107password_change = login_required(password_change)
    100108
    101 def password_change_done(request, template_name='registration/password_change_done.html'):
    102     return render_to_response(template_name, context_instance=RequestContext(request))
    103 
    104109def user_change_password(request, id):
    105110    if not request.user.has_perm('auth.change_user'):
    106         raise PermissionDenied
     111        raise PermissionDenied   
    107112    user = get_object_or_404(User, pk=id)
    108     manipulator = AdminPasswordChangeForm(user)
    109113    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)
     114        form = forms.AdminPasswordChangeForm(request.POST)
     115        form.set_user(user)
     116        if form.is_valid():
     117            new_user = form.save()
    114118            msg = _('Password changed successfully.')
    115119            request.user.message_set.create(message=msg)
    116120            return HttpResponseRedirect('..')
    117     else:
    118         errors = new_data = {}
    119     form = oldforms.FormWrapper(manipulator, new_data, errors)
    120     return render_to_response('admin/auth/user/change_password.html', {
    121         'title': _('Change password: %s') % escape(user.username),
    122         'form': form,
    123         'is_popup': '_popup' in request.REQUEST,
    124         'add': True,
    125         'change': False,
    126         'has_delete_permission': False,
    127         'has_change_permission': True,
    128         'has_absolute_url': False,
    129         'opts': User._meta,
    130         'original': user,
    131         'show_save': True,
    132     }, context_instance=RequestContext(request))
     121    elif request.method == 'GET':
     122        form = forms.AdminPasswordChangeForm()
     123    return render_to_response('admin/auth/user/change_password.html', {'title': _('Change password: %s') % user.username, 'form': form, 'is_popup': '_popup' in request.REQUEST, 'add': True, 'change': False, 'has_delete_permission': False, 'has_change_permission': True, 'has_absolute_url': False, 'opts': User._meta, 'original': user, 'show_save': True, }, context_instance=RequestContext(request))
     124 No newline at end of file
Back to Top