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:
<script type="text/javascript" src="/static/js/swfupload/swfupload.cookies.js"></script>
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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
nice tip, it works. but seems very unsecure to bypass the sessionid this way.
#
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.
#
Please login first before commenting.