Ticket #6083: auth-uses-newforms.diff
File auth-uses-newforms.diff, 20.5 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/views/auth.py
11 11 def user_add_stage(request): 12 12 if not request.user.has_perm('auth.change_user'): 13 13 raise PermissionDenied 14 manipulator = UserCreationForm()15 14 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() 20 18 msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': 'user', 'obj': new_user} 21 19 if "_addanother" in request.POST: 22 20 request.user.message_set.create(message=msg) … … 25 23 request.user.message_set.create(message=msg + ' ' + _("You may edit it again below.")) 26 24 return HttpResponseRedirect('../%s/' % new_user.id) 27 25 else: 28 errors = new_data = {} 29 form = oldforms.FormWrapper(manipulator, new_data, errors) 26 form = UserCreationForm() 30 27 return render_to_response('admin/auth/user/add_form.html', { 31 28 'title': _('Add user'), 32 29 'form': form, … … 49 46 if not request.user.has_perm('auth.change_user'): 50 47 raise PermissionDenied 51 48 user = get_object_or_404(User, pk=id) 52 manipulator = AdminPasswordChangeForm(user)53 49 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() 58 53 msg = _('Password changed successfully.') 59 54 request.user.message_set.create(message=msg) 60 55 return HttpResponseRedirect('..') 61 56 else: 62 errors = new_data = {} 63 form = oldforms.FormWrapper(manipulator, new_data, errors) 57 form = AdminPasswordChangeForm(user=user) 64 58 return render_to_response('admin/auth/user/change_password.html', { 65 59 'title': _('Change password: %s') % escape(user.username), 66 60 'form': form, -
django/contrib/auth/views.py
1 1 from django.contrib.auth.forms import AuthenticationForm 2 2 from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm 3 from django import oldforms4 3 from django.shortcuts import render_to_response 5 4 from django.template import RequestContext 6 5 from django.contrib.sites.models import Site, RequestSite … … 11 10 12 11 def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME): 13 12 "Displays the login form and handles the login action." 14 manipulator = AuthenticationForm(request)15 13 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(): 19 17 # Light security check -- make sure redirect_to isn't garbage. 20 18 if not redirect_to or '//' in redirect_to or ' ' in redirect_to: 21 19 from django.conf import settings 22 20 redirect_to = settings.LOGIN_REDIRECT_URL 23 21 from django.contrib.auth import login 24 login(request, manipulator.get_user())22 login(request, form.get_user()) 25 23 request.session.delete_test_cookie() 26 24 return HttpResponseRedirect(redirect_to) 27 25 else: 28 errors = {}26 form = AuthenticationForm(request=request) 29 27 request.session.set_test_cookie() 30 28 31 29 if Site._meta.installed: … … 34 32 current_site = RequestSite(request) 35 33 36 34 return render_to_response(template_name, { 37 'form': oldforms.FormWrapper(manipulator, request.POST, errors),35 'form': form, 38 36 redirect_field_name: redirect_to, 39 37 'site_name': current_site.name, 40 38 }, context_instance=RequestContext(request)) … … 65 63 66 64 def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html', 67 65 email_template_name='registration/password_reset_email.html'): 68 new_data, errors = {}, {}69 form = PasswordResetForm()70 66 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(): 74 69 if is_admin_site: 75 70 form.save(domain_override=request.META['HTTP_HOST']) 76 71 else: 77 72 form.save(email_template_name=email_template_name) 78 73 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}, 80 77 context_instance=RequestContext(request)) 81 78 82 79 def password_reset_done(request, template_name='registration/password_reset_done.html'): … … 84 81 85 82 def password_change(request, template_name='registration/password_change_form.html'): 86 83 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() 93 88 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}, 95 92 context_instance=RequestContext(request)) 96 93 password_change = login_required(password_change) 97 94 -
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 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): 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_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): 142 158 "Saves the new password." 143 self.user.set_password( new_data['password1'])159 self.user.set_password(self.cleaned_data['new_password1']) 144 160 self.user.save() -
AUTHORS
325 325 tstromberg@google.com 326 326 Makoto Tsuyuki <mtsuyuki@gmail.com> 327 327 tt@gurgle.no 328 Greg Turner <http://gregturner.org> 328 329 Amit Upadhyay 329 330 Geert Vanderkelen 330 331 viestards.lists@gmail.com