app/django/contrib/admin/views/decorators.py
changeset 54 03e267d67478
child 323 ff1a9aa48cfd
equal deleted inserted replaced
53:57b4279d8c4e 54:03e267d67478
       
     1 import base64
       
     2 import md5
       
     3 import cPickle as pickle
       
     4 try:
       
     5     from functools import wraps
       
     6 except ImportError:
       
     7     from django.utils.functional import wraps  # Python 2.3, 2.4 fallback.
       
     8 
       
     9 from django import http, template
       
    10 from django.conf import settings
       
    11 from django.contrib.auth.models import User
       
    12 from django.contrib.auth import authenticate, login
       
    13 from django.shortcuts import render_to_response
       
    14 from django.utils.translation import ugettext_lazy, ugettext as _
       
    15 from django.utils.safestring import mark_safe
       
    16 
       
    17 ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. Note that both fields are case-sensitive.")
       
    18 LOGIN_FORM_KEY = 'this_is_the_login_form'
       
    19 
       
    20 def _display_login_form(request, error_message=''):
       
    21     request.session.set_test_cookie()
       
    22     if request.POST and 'post_data' in request.POST:
       
    23         # User has failed login BUT has previously saved post data.
       
    24         post_data = request.POST['post_data']
       
    25     elif request.POST:
       
    26         # User's session must have expired; save their post data.
       
    27         post_data = _encode_post_data(request.POST)
       
    28     else:
       
    29         post_data = _encode_post_data({})
       
    30     return render_to_response('admin/login.html', {
       
    31         'title': _('Log in'),
       
    32         'app_path': request.path,
       
    33         'post_data': post_data,
       
    34         'error_message': error_message
       
    35     }, context_instance=template.RequestContext(request))
       
    36 
       
    37 def _encode_post_data(post_data):
       
    38     pickled = pickle.dumps(post_data)
       
    39     pickled_md5 = md5.new(pickled + settings.SECRET_KEY).hexdigest()
       
    40     return base64.encodestring(pickled + pickled_md5)
       
    41 
       
    42 def _decode_post_data(encoded_data):
       
    43     encoded_data = base64.decodestring(encoded_data)
       
    44     pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
       
    45     if md5.new(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
       
    46         from django.core.exceptions import SuspiciousOperation
       
    47         raise SuspiciousOperation, "User may have tampered with session cookie."
       
    48     return pickle.loads(pickled)
       
    49 
       
    50 def staff_member_required(view_func):
       
    51     """
       
    52     Decorator for views that checks that the user is logged in and is a staff
       
    53     member, displaying the login page if necessary.
       
    54     """
       
    55     def _checklogin(request, *args, **kwargs):
       
    56         if request.user.is_authenticated() and request.user.is_staff:
       
    57             # The user is valid. Continue to the admin page.
       
    58             if 'post_data' in request.POST:
       
    59                 # User must have re-authenticated through a different window
       
    60                 # or tab.
       
    61                 request.POST = _decode_post_data(request.POST['post_data'])
       
    62             return view_func(request, *args, **kwargs)
       
    63 
       
    64         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'."
       
    65 
       
    66         # If this isn't already the login page, display it.
       
    67         if LOGIN_FORM_KEY not in request.POST:
       
    68             if request.POST:
       
    69                 message = _("Please log in again, because your session has expired. Don't worry: Your submission has been saved.")
       
    70             else:
       
    71                 message = ""
       
    72             return _display_login_form(request, message)
       
    73 
       
    74         # Check that the user accepts cookies.
       
    75         if not request.session.test_cookie_worked():
       
    76             message = _("Looks like your browser isn't configured to accept cookies. Please enable cookies, reload this page, and try again.")
       
    77             return _display_login_form(request, message)
       
    78 
       
    79         # Check the password.
       
    80         username = request.POST.get('username', None)
       
    81         password = request.POST.get('password', None)
       
    82         user = authenticate(username=username, password=password)
       
    83         if user is None:
       
    84             message = ERROR_MESSAGE
       
    85             if '@' in username:
       
    86                 # Mistakenly entered e-mail address instead of username? Look it up.
       
    87                 users = list(User.objects.filter(email=username))
       
    88                 if len(users) == 1:
       
    89                     message = _("Your e-mail address is not your username. Try '%s' instead.") % users[0].username
       
    90                 else:
       
    91                     # Either we cannot find the user, or if more than 1 
       
    92                     # we cannot guess which user is the correct one.
       
    93                     message = _("Usernames cannot contain the '@' character.")
       
    94             return _display_login_form(request, message)
       
    95 
       
    96         # The user data is correct; log in the user in and continue.
       
    97         else:
       
    98             if user.is_active and user.is_staff:
       
    99                 login(request, user)
       
   100                 # TODO: set last_login with an event.
       
   101                 if 'post_data' in request.POST:
       
   102                     post_data = _decode_post_data(request.POST['post_data'])
       
   103                     if post_data and LOGIN_FORM_KEY not in post_data:
       
   104                         # overwrite request.POST with the saved post_data, and continue
       
   105                         request.POST = post_data
       
   106                         request.user = user
       
   107                         return view_func(request, *args, **kwargs)
       
   108                     else:
       
   109                         request.session.delete_test_cookie()
       
   110                         return http.HttpResponseRedirect(request.path)
       
   111             else:
       
   112                 return _display_login_form(request, ERROR_MESSAGE)
       
   113 
       
   114     return wraps(view_func)(_checklogin)