Ticket #6083: auth-uses-newforms-3.diff
File auth-uses-newforms-3.diff, 20.0 KB (added by , 17 years ago) |
---|
-
django/contrib/comments/views/comments.py
7 7 from django.template import RequestContext 8 8 from django.contrib.comments.models import Comment, FreeComment, RATINGS_REQUIRED, RATINGS_OPTIONAL, IS_PUBLIC 9 9 from django.contrib.contenttypes.models import ContentType 10 from django.contrib.auth.forms import AuthenticationForm11 10 from django.http import HttpResponseRedirect 12 11 from django.utils.text import normalize_newlines 13 12 from django.conf import settings … … 17 16 18 17 COMMENTS_PER_PAGE = 20 19 18 19 20 class 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 20 60 class PublicCommentManipulator(AuthenticationForm): 21 61 "Manipulator that handles public registered comments" 22 62 def __init__(self, user, ratings_required, ratings_range, num_rating_choices): -
django/contrib/admin/templates/admin/auth/user/change_password.html
27 27 <p>{% blocktrans with original.username|escape as username %}Enter a new password for the user <strong>{{ username }}</strong>.{% endblocktrans %}</p> 28 28 29 29 <fieldset class="module aligned"> 30 30 {% if form.non_field_errors %} 31 {{form.non_field_errors}} 32 {% endif %} 31 33 <div class="form-row"> 32 {{ form.password1.html_error_list }} 34 {% if form.password1.errors %} 35 {{ form.password1.errors }} 36 {% endif %} 33 37 <label for="id_password1" class="required">{% trans 'Password' %}:</label> {{ form.password1 }} 34 38 </div> 35 39 36 40 <div class="form-row"> 37 {{ form.password2.html_error_list }} 41 {% if form.password2.errors %} 42 {{ form.password2.errors }} 43 {% endif %} 38 44 <label for="id_password2" class="required">{% trans 'Password (again)' %}:</label> {{ form.password2 }} 39 45 <p class="help">{% trans 'Enter the same password as above, for verification.' %}</p> 40 46 </div> -
django/contrib/auth/views.py
14 14 15 15 def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME): 16 16 "Displays the login form and handles the login action." 17 manipulator = AuthenticationForm(request)18 17 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(): 22 21 # Light security check -- make sure redirect_to isn't garbage. 23 22 if not redirect_to or '//' in redirect_to or ' ' in redirect_to: 24 23 from django.conf import settings 25 24 redirect_to = settings.LOGIN_REDIRECT_URL 26 25 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() 29 29 return HttpResponseRedirect(redirect_to) 30 30 else: 31 errors = {}31 form = AuthenticationForm(request=request) 32 32 request.session.set_test_cookie() 33 33 34 34 if Site._meta.installed: … … 37 37 current_site = RequestSite(request) 38 38 39 39 return render_to_response(template_name, { 40 'form': oldforms.FormWrapper(manipulator, request.POST, errors),40 'form': form, 41 41 redirect_field_name: redirect_to, 42 42 'site_name': current_site.name, 43 43 }, context_instance=RequestContext(request)) … … 68 68 69 69 def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html', 70 70 email_template_name='registration/password_reset_email.html'): 71 new_data, errors = {}, {}72 form = PasswordResetForm()73 71 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(): 77 74 if is_admin_site: 78 75 form.save(domain_override=request.META['HTTP_HOST']) 79 76 else: 80 77 form.save(email_template_name=email_template_name) 81 78 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}, 83 82 context_instance=RequestContext(request)) 84 83 85 84 def password_reset_done(request, template_name='registration/password_reset_done.html'): … … 87 86 88 87 def password_change(request, template_name='registration/password_change_form.html'): 89 88 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() 96 93 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}, 98 97 context_instance=RequestContext(request)) 99 98 password_change = login_required(password_change) 100 99 … … 105 104 if not request.user.has_perm('auth.change_user'): 106 105 raise PermissionDenied 107 106 user = get_object_or_404(User, pk=id) 108 manipulator = AdminPasswordChangeForm(user)109 107 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(): 114 110 msg = _('Password changed successfully.') 115 111 request.user.message_set.create(message=msg) 116 112 return HttpResponseRedirect('..') 117 113 else: 118 errors = new_data = {} 119 form = oldforms.FormWrapper(manipulator, new_data, errors) 114 form = AdminPasswordChangeForm(None,user) 120 115 return render_to_response('admin/auth/user/change_password.html', { 121 116 'title': _('Change password: %s') % escape(user.username), 122 117 'form': form, -
django/contrib/auth/forms.py
2 2 from django.contrib.auth import authenticate 3 3 from django.contrib.sites.models import Site 4 4 from django.template import Context, loader 5 from django.core import validators 6 from django import oldforms 5 from django import newforms as forms 7 6 from django.utils.translation import ugettext as _ 7 import re 8 8 9 class UserCreationForm( oldforms.Manipulator):9 class UserCreationForm(forms.Form): 10 10 "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) 19 14 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) 21 28 try: 22 User.objects.get(username=field_data)29 user = User.objects.get(username__exact=self.cleaned_data['username']) 23 30 except User.DoesNotExist: 24 return25 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): 28 35 "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']) 30 37 31 class AuthenticationForm( oldforms.Manipulator):38 class AuthenticationForm(forms.Form): 32 39 """ 33 40 Base class for authenticating users. Extend this to get a form that accepts 34 41 username/password logins. 35 42 """ 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): 37 47 """ 38 48 If request is passed in, the manipulator will validate that cookies are 39 49 enabled. Note that the request (a HttpRequest object) must have set a … … 41 51 running this validator. 42 52 """ 43 53 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 ]49 54 self.user_cache = None 55 super(AuthenticationForm, self).__init__(request_post) 50 56 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 52 62 if self.request and not self.request.session.test_cookie_worked(): 53 63 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'] 58 66 self.user_cache = authenticate(username=username, password=password) 59 67 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.") 61 69 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 63 72 64 73 def get_user_id(self): 65 74 if self.user_cache: … … 69 78 def get_user(self): 70 79 return self.user_cache 71 80 72 class PasswordResetForm( oldforms.Manipulator):81 class PasswordResetForm(forms.Form): 73 82 "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): 81 86 "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'])) 83 88 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'] 85 91 86 92 def save(self, domain_override=None, email_template_name='registration/password_reset_email.html'): 87 93 "Calculates a new password randomly and sends it to the user" … … 106 112 } 107 113 send_mail(_('Password reset on %s') % site_name, t.render(Context(c)), None, [user.email]) 108 114 109 class PasswordChangeForm(oldforms.Manipulator): 110 "A form that lets a user change his password." 111 def __init__(self, user): 115 class 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): 112 122 self.user = user 113 s elf.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'] 120 130 121 def isValidOldPassword(self, new_data, all_data):131 def clean_old_password(self): 122 132 "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'] 125 136 126 def save(self , new_data):137 def save(self): 127 138 "Saves the new password." 128 self.user.set_password( new_data['new_password1'])139 self.user.set_password(self.cleaned_data['new_password1']) 129 140 self.user.save() 130 141 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): 142 class 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): 134 148 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) 140 150 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): 142 158 "Saves the new password." 143 self.user.set_password( new_data['password1'])159 self.user.set_password(self.cleaned_data['password1']) 144 160 self.user.save() -
AUTHORS
335 335 tstromberg@google.com 336 336 Makoto Tsuyuki <mtsuyuki@gmail.com> 337 337 tt@gurgle.no 338 Greg Turner <http://gregturner.org> 338 339 Amit Upadhyay 339 340 Geert Vanderkelen 340 341 I.S. van Oostveen <v.oostveen@idca.nl>