Ticket #6318: auth.diff
File auth.diff, 20.2 KB (added by , 17 years ago) |
---|
-
django/contrib/auth/forms.py
1 from django import newforms as forms 2 import re 3 from django.newforms import ValidationError 1 4 from django.contrib.auth.models import User 2 5 from django.contrib.auth import authenticate 3 6 from django.contrib.sites.models import Site … … 2 5 from django.template import Context, loader 3 from django.core import validators4 from django import oldforms5 6 from django.utils.translation import ugettext as _ 6 7 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 ) 8 class 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) 17 13 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): 19 27 try: 20 User.objects.get(username= field_data)28 User.objects.get(username=self.cleaned_data['username']) 21 29 except User.DoesNotExist: 22 30 return 23 raise validators.ValidationError, _('A user with that username already exists.')31 raise ValidationError(_('A user with that username already exists.')) 24 32 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): 33 class AuthenticationForm(forms.Form): 30 34 """ 31 35 Base class for authenticating users. Extend this to get a form that accepts 32 36 username/password logins. 33 37 """ 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): 41 41 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() 48 55 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.")56 class PasswordResetForm(forms.Form): 57 """A form that lets a user request a password reset""" 58 email = forms.EmailField(required = True) 52 59 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'] 61 67 62 def get_user_id(self):63 if self.user_cache:64 return self.user_cache.id65 return None66 67 def get_user(self):68 return self.user_cache69 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 84 68 def save(self, domain_override=None, email_template_name='registration/password_reset_email.html'): 85 69 "Calculates a new password randomly and sends it to the user" 86 70 from django.core.mail import send_mail 87 for user in self.users_cache:88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 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]) 106 90 107 class PasswordChangeForm(oldforms.Manipulator): 108 "A form that lets a user change his password." 109 def __init__(self, user): 91 class 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): 110 98 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 )118 99 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'] 123 104 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): 125 111 "Saves the new password." 126 self.user.set_password(new_ data['new_password1'])112 self.user.set_password(new_password) 127 113 self.user.save() 128 114 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): 115 class 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): 132 121 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() 138 127 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 1 import forms 5 2 from django.shortcuts import render_to_response, get_object_or_404 3 from django.http import HttpResponse, HttpResponseRedirect 4 from django.contrib.auth.models import User 5 from django.contrib.auth import REDIRECT_FIELD_NAME 6 6 from django.template import RequestContext 7 7 from django.contrib.sites.models import Site, RequestSite 8 from django.http import HttpResponseRedirect9 from django.contrib.auth.decorators import login_required10 from django.contrib.auth import REDIRECT_FIELD_NAME11 from django.utils.html import escape12 8 from django.utils.translation import ugettext as _ 13 from django.contrib.auth.models import User 9 from django.contrib.auth.decorators import login_required 10 from django.core.exceptions import PermissionDenied 14 11 12 13 def 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 15 25 def 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.""" 18 27 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(): 22 36 # Light security check -- make sure redirect_to isn't garbage. 23 37 if not redirect_to or '//' in redirect_to or ' ' in redirect_to: 24 38 from django.conf import settings 25 39 redirect_to = settings.LOGIN_REDIRECT_URL 26 40 from django.contrib.auth import login 27 login(request, manipulator.get_user()) 41 user = login_form.user 42 login(request, user) 28 43 request.session.delete_test_cookie() 29 44 return HttpResponseRedirect(redirect_to) 30 el se:31 errors = {}45 elif request.method == 'GET': 46 login_form = forms.AuthenticationForm() 32 47 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 39 48 return render_to_response(template_name, { 40 'form': oldforms.FormWrapper(manipulator, request.POST, errors),49 'form': login_form, 41 50 redirect_field_name: redirect_to, 42 51 'site_name': current_site.name, 43 52 }, context_instance=RequestContext(request)) … … 68 77 69 78 def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html', 70 79 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(): 77 83 if is_admin_site: 78 84 form.save(domain_override=request.META['HTTP_HOST']) 79 85 else: 80 86 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)) 84 92 85 def password_reset_done(request, template_name='registration/password_reset_done.html'):86 return render_to_response( template_name, context_instance=RequestContext(request))93 def index(request): 94 return render_to_response('registration/password_reset_form.html', {}, context_instance=RequestContext(request)) 87 95 88 96 def 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}, 98 106 context_instance=RequestContext(request)) 99 107 password_change = login_required(password_change) 100 108 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 104 109 def user_change_password(request, id): 105 110 if not request.user.has_perm('auth.change_user'): 106 raise PermissionDenied 111 raise PermissionDenied 107 112 user = get_object_or_404(User, pk=id) 108 manipulator = AdminPasswordChangeForm(user)109 113 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() 114 118 msg = _('Password changed successfully.') 115 119 request.user.message_set.create(message=msg) 116 120 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