SWFUpload auth decorator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def flash_login_required(template):
    """
    Decorator to recognized a user  by its session
    when using SWFUpload and its cookie plugin.
    """
    def decorator(view_func):
        def newfn(request, *args, **kwargs):
            from django.contrib.sessions.models import Session
            from django.shortcuts import get_object_or_404, render_to_response
            from django.contrib.auth.models import User
            from django.template import RequestContext

            session = get_object_or_404(Session, session_key=request.POST.get('sessionid'))
            session_data = session.get_decoded()
            
            user_id = session_data['_auth_user_id']
            request.user = get_object_or_404(User, pk = user_id)

            # you can fill default value in context dict
            # it will be injected to the template after
            context = {}
            context['profile'] = request.user.get_profile()

            view_func(request, context, **kwargs)

            if context.has_key('redirect'):
                return HttpResponseRedirect(context['redirect'])
            return render_to_response(template, 
                                      context, 
                                      RequestContext(request))
        return newfn
    return decorator

# Example in a view 
#from common.decorators import flash_login_required
#
#@flash_login_required('clip/clip_uploaded.html')
#def clip_upload_item(request, context):
#    context['key'] = 'value'

More like this

  1. Cookieless Session Decorator by achimnol 3 years, 9 months ago
  2. HTTP basic auth decorator by bthomas 4 years, 3 months ago
  3. login_required decorator that doesn't redirect by brutasse 2 years, 3 months ago
  4. Unobtrusvie Foldable Admin Interface by whiteinge 5 years, 4 months ago
  5. Cookie based flash errors and notices (a la Rails) by alexk 4 years, 8 months ago

Comments

revolunet (on April 28, 2009):

nice tip, it works. but seems very unsecure to bypass the sessionid this way.

#

menendez (on June 29, 2009):

Lines 11 and 12 should be replaced with this so that it works with any session engine:

engine = import(settings.SESSION_ENGINE, {}, {}, ['']) session_data = engine.SessionStore(request.POST.get('sessionid'))

Line 5 can be removed.

#

(Forgotten your password?)