PageRenderTime 1ms CodeModel.GetById 70ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/auth/views.py

https://github.com/eric-brechemier/django
Python | 191 lines | 164 code | 16 blank | 11 comment | 19 complexity | 46a197bf77221591888b7969f7cf3cd5 MD5 | raw file
  1import re
  2from django.conf import settings
  3from django.contrib.auth import REDIRECT_FIELD_NAME
  4# Avoid shadowing the login() view below.
  5from django.contrib.auth import login as auth_login
  6from django.contrib.auth.decorators import login_required
  7from django.contrib.auth.forms import AuthenticationForm
  8from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm, PasswordChangeForm
  9from django.contrib.auth.tokens import default_token_generator
 10from django.views.decorators.csrf import csrf_protect
 11from django.core.urlresolvers import reverse
 12from django.shortcuts import render_to_response, get_object_or_404
 13from django.contrib.sites.models import Site, RequestSite
 14from django.http import HttpResponseRedirect, Http404
 15from django.template import RequestContext
 16from django.utils.http import urlquote, base36_to_int
 17from django.utils.translation import ugettext as _
 18from django.contrib.auth.models import User
 19from django.views.decorators.cache import never_cache
 20
 21@csrf_protect
 22@never_cache
 23def login(request, template_name='registration/login.html',
 24          redirect_field_name=REDIRECT_FIELD_NAME,
 25          authentication_form=AuthenticationForm):
 26    """Displays the login form and handles the login action."""
 27
 28    redirect_to = request.REQUEST.get(redirect_field_name, '')
 29    
 30    if request.method == "POST":
 31        form = authentication_form(data=request.POST)
 32        if form.is_valid():
 33            # Light security check -- make sure redirect_to isn't garbage.
 34            if not redirect_to or ' ' in redirect_to:
 35                redirect_to = settings.LOGIN_REDIRECT_URL
 36            
 37            # Heavier security check -- redirects to http://example.com should 
 38            # not be allowed, but things like /view/?param=http://example.com 
 39            # should be allowed. This regex checks if there is a '//' *before* a
 40            # question mark.
 41            elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
 42                    redirect_to = settings.LOGIN_REDIRECT_URL
 43            
 44            # Okay, security checks complete. Log the user in.
 45            auth_login(request, form.get_user())
 46
 47            if request.session.test_cookie_worked():
 48                request.session.delete_test_cookie()
 49
 50            return HttpResponseRedirect(redirect_to)
 51
 52    else:
 53        form = authentication_form(request)
 54    
 55    request.session.set_test_cookie()
 56    
 57    if Site._meta.installed:
 58        current_site = Site.objects.get_current()
 59    else:
 60        current_site = RequestSite(request)
 61    
 62    return render_to_response(template_name, {
 63        'form': form,
 64        redirect_field_name: redirect_to,
 65        'site': current_site,
 66        'site_name': current_site.name,
 67    }, context_instance=RequestContext(request))
 68
 69def logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME):
 70    "Logs out the user and displays 'You are logged out' message."
 71    from django.contrib.auth import logout
 72    logout(request)
 73    if next_page is None:
 74        redirect_to = request.REQUEST.get(redirect_field_name, '')
 75        if redirect_to:
 76            return HttpResponseRedirect(redirect_to)
 77        else:
 78            return render_to_response(template_name, {
 79                'title': _('Logged out')
 80            }, context_instance=RequestContext(request))
 81    else:
 82        # Redirect to this page until the session has been cleared.
 83        return HttpResponseRedirect(next_page or request.path)
 84
 85def logout_then_login(request, login_url=None):
 86    "Logs out the user if he is logged in. Then redirects to the log-in page."
 87    if not login_url:
 88        login_url = settings.LOGIN_URL
 89    return logout(request, login_url)
 90
 91def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
 92    "Redirects the user to the login page, passing the given 'next' page"
 93    if not login_url:
 94        login_url = settings.LOGIN_URL
 95    return HttpResponseRedirect('%s?%s=%s' % (login_url, urlquote(redirect_field_name), urlquote(next)))
 96
 97# 4 views for password reset:
 98# - password_reset sends the mail
 99# - password_reset_done shows a success message for the above
100# - password_reset_confirm checks the link the user clicked and 
101#   prompts for a new password
102# - password_reset_complete shows a success message for the above
103
104@csrf_protect
105def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html',
106        email_template_name='registration/password_reset_email.html',
107        password_reset_form=PasswordResetForm, token_generator=default_token_generator,
108        post_reset_redirect=None, from_email=None):
109    if post_reset_redirect is None:
110        post_reset_redirect = reverse('django.contrib.auth.views.password_reset_done')
111    if request.method == "POST":
112        form = password_reset_form(request.POST)
113        if form.is_valid():
114            opts = {}
115            opts['use_https'] = request.is_secure()
116            opts['token_generator'] = token_generator
117            opts['from_email'] = from_email
118            if is_admin_site:
119                opts['domain_override'] = request.META['HTTP_HOST']
120            else:
121                opts['email_template_name'] = email_template_name
122                if not Site._meta.installed:
123                    opts['domain_override'] = RequestSite(request).domain
124            form.save(**opts)
125            return HttpResponseRedirect(post_reset_redirect)
126    else:
127        form = password_reset_form()
128    return render_to_response(template_name, {
129        'form': form,
130    }, context_instance=RequestContext(request))
131
132def password_reset_done(request, template_name='registration/password_reset_done.html'):
133    return render_to_response(template_name, context_instance=RequestContext(request))
134
135# Doesn't need csrf_protect since no-one can guess the URL
136def password_reset_confirm(request, uidb36=None, token=None, template_name='registration/password_reset_confirm.html',
137                           token_generator=default_token_generator, set_password_form=SetPasswordForm,
138                           post_reset_redirect=None):
139    """
140    View that checks the hash in a password reset link and presents a
141    form for entering a new password.
142    """
143    assert uidb36 is not None and token is not None # checked by URLconf
144    if post_reset_redirect is None:
145        post_reset_redirect = reverse('django.contrib.auth.views.password_reset_complete')
146    try:
147        uid_int = base36_to_int(uidb36)
148    except ValueError:
149        raise Http404
150
151    user = get_object_or_404(User, id=uid_int)
152    context_instance = RequestContext(request)
153
154    if token_generator.check_token(user, token):
155        context_instance['validlink'] = True
156        if request.method == 'POST':
157            form = set_password_form(user, request.POST)
158            if form.is_valid():
159                form.save()
160                return HttpResponseRedirect(post_reset_redirect)
161        else:
162            form = set_password_form(None)
163    else:
164        context_instance['validlink'] = False
165        form = None
166    context_instance['form'] = form
167    return render_to_response(template_name, context_instance=context_instance)
168
169def password_reset_complete(request, template_name='registration/password_reset_complete.html'):
170    return render_to_response(template_name, context_instance=RequestContext(request,
171                                                                             {'login_url': settings.LOGIN_URL}))
172
173@csrf_protect
174@login_required
175def password_change(request, template_name='registration/password_change_form.html',
176                    post_change_redirect=None, password_change_form=PasswordChangeForm):
177    if post_change_redirect is None:
178        post_change_redirect = reverse('django.contrib.auth.views.password_change_done')
179    if request.method == "POST":
180        form = password_change_form(user=request.user, data=request.POST)
181        if form.is_valid():
182            form.save()
183            return HttpResponseRedirect(post_change_redirect)
184    else:
185        form = password_change_form(user=request.user)
186    return render_to_response(template_name, {
187        'form': form,
188    }, context_instance=RequestContext(request))
189
190def password_change_done(request, template_name='registration/password_change_done.html'):
191    return render_to_response(template_name, context_instance=RequestContext(request))