SWFUpload auth decorator

I use this snippet to simplify my auth system with flash uploader SWFUpload. flash_login_required ensures that the user is authenticated and inject the context dictionnary into the specified template. To redirect a user, just set the variable context['redirect'] with an url.

Remember to include the cookie js in your template to get the sessionid variable POSTed to your view:

defflash_login_required(template):""" Decorator to recognized a user by its session when using SWFUpload and its cookie plugin. """defdecorator(view_func):defnewfn(request,*args,**kwargs):fromdjango.contrib.sessions.modelsimportSessionfromdjango.shortcutsimportget_object_or_404,render_to_responsefromdjango.contrib.auth.modelsimportUserfromdjango.templateimportRequestContextsession=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 aftercontext={}context['profile']=request.user.get_profile()view_func(request,context,**kwargs)ifcontext.has_key('redirect'):returnHttpResponseRedirect(context['redirect'])returnrender_to_response(template,context,RequestContext(request))returnnewfnreturndecorator# 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'