thirdparty/google_appengine/lib/django/django/contrib/admin/views/decorators.py
changeset 2864 2e0b0af889be
parent 109 620f9b141567
equal deleted inserted replaced
2862:27971a13089f 2864:2e0b0af889be
     1 from django import http, template
     1 from django import http, template
     2 from django.conf import settings
     2 from django.conf import settings
     3 from django.contrib.auth.models import User
     3 from django.contrib.auth.models import User
     4 from django.contrib.auth import authenticate, login
     4 from django.contrib.auth import authenticate, login
     5 from django.shortcuts import render_to_response
     5 from django.shortcuts import render_to_response
       
     6 from django.utils.html import escape
     6 from django.utils.translation import gettext_lazy
     7 from django.utils.translation import gettext_lazy
     7 import base64, datetime, md5
     8 import base64, datetime
     8 import cPickle as pickle
       
     9 
     9 
    10 ERROR_MESSAGE = gettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.")
    10 ERROR_MESSAGE = gettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.")
    11 LOGIN_FORM_KEY = 'this_is_the_login_form'
    11 LOGIN_FORM_KEY = 'this_is_the_login_form'
    12 
    12 
    13 def _display_login_form(request, error_message=''):
    13 def _display_login_form(request, error_message=''):
    14     request.session.set_test_cookie()
    14     request.session.set_test_cookie()
    15     if request.POST and request.POST.has_key('post_data'):
       
    16         # User has failed login BUT has previously saved post data.
       
    17         post_data = request.POST['post_data']
       
    18     elif request.POST:
       
    19         # User's session must have expired; save their post data.
       
    20         post_data = _encode_post_data(request.POST)
       
    21     else:
       
    22         post_data = _encode_post_data({})
       
    23     return render_to_response('admin/login.html', {
    15     return render_to_response('admin/login.html', {
    24         'title': _('Log in'),
    16         'title': _('Log in'),
    25         'app_path': request.path,
    17         'app_path': escape(request.path),
    26         'post_data': post_data,
       
    27         'error_message': error_message
    18         'error_message': error_message
    28     }, context_instance=template.RequestContext(request))
    19     }, context_instance=template.RequestContext(request))
    29 
       
    30 def _encode_post_data(post_data):
       
    31     pickled = pickle.dumps(post_data)
       
    32     pickled_md5 = md5.new(pickled + settings.SECRET_KEY).hexdigest()
       
    33     return base64.encodestring(pickled + pickled_md5)
       
    34 
       
    35 def _decode_post_data(encoded_data):
       
    36     encoded_data = base64.decodestring(encoded_data)
       
    37     pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
       
    38     if md5.new(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
       
    39         from django.core.exceptions import SuspiciousOperation
       
    40         raise SuspiciousOperation, "User may have tampered with session cookie."
       
    41     return pickle.loads(pickled)
       
    42 
    20 
    43 def staff_member_required(view_func):
    21 def staff_member_required(view_func):
    44     """
    22     """
    45     Decorator for views that checks that the user is logged in and is a staff
    23     Decorator for views that checks that the user is logged in and is a staff
    46     member, displaying the login page if necessary.
    24     member, displaying the login page if necessary.
    47     """
    25     """
    48     def _checklogin(request, *args, **kwargs):
    26     def _checklogin(request, *args, **kwargs):
    49         if request.user.is_authenticated() and request.user.is_staff:
    27         if request.user.is_authenticated() and request.user.is_staff:
    50             # The user is valid. Continue to the admin page.
    28             # The user is valid. Continue to the admin page.
    51             if request.POST.has_key('post_data'):
       
    52                 # User must have re-authenticated through a different window
       
    53                 # or tab.
       
    54                 request.POST = _decode_post_data(request.POST['post_data'])
       
    55             return view_func(request, *args, **kwargs)
    29             return view_func(request, *args, **kwargs)
    56 
    30 
    57         assert hasattr(request, 'session'), "The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
    31         assert hasattr(request, 'session'), "The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
    58 
    32 
    59         # If this isn't already the login page, display it.
    33         # If this isn't already the login page, display it.
    60         if not request.POST.has_key(LOGIN_FORM_KEY):
    34         if not request.POST.has_key(LOGIN_FORM_KEY):
    61             if request.POST:
    35             if request.POST:
    62                 message = _("Please log in again, because your session has expired. Don't worry: Your submission has been saved.")
    36                 message = _("Please log in again, because your session has expired.")
    63             else:
    37             else:
    64                 message = ""
    38                 message = ""
    65             return _display_login_form(request, message)
    39             return _display_login_form(request, message)
    66 
    40 
    67         # Check that the user accepts cookies.
    41         # Check that the user accepts cookies.
    90             if user.is_active and user.is_staff:
    64             if user.is_active and user.is_staff:
    91                 login(request, user)
    65                 login(request, user)
    92                 # TODO: set last_login with an event.
    66                 # TODO: set last_login with an event.
    93                 user.last_login = datetime.datetime.now()
    67                 user.last_login = datetime.datetime.now()
    94                 user.save()
    68                 user.save()
    95                 if request.POST.has_key('post_data'):
    69                 return http.HttpResponseRedirect(request.path)
    96                     post_data = _decode_post_data(request.POST['post_data'])
       
    97                     if post_data and not post_data.has_key(LOGIN_FORM_KEY):
       
    98                         # overwrite request.POST with the saved post_data, and continue
       
    99                         request.POST = post_data
       
   100                         request.user = user
       
   101                         return view_func(request, *args, **kwargs)
       
   102                     else:
       
   103                         request.session.delete_test_cookie()
       
   104                         return http.HttpResponseRedirect(request.path)
       
   105             else:
    70             else:
   106                 return _display_login_form(request, ERROR_MESSAGE)
    71                 return _display_login_form(request, ERROR_MESSAGE)
   107 
    72 
   108     return _checklogin
    73     return _checklogin