code_junkie

Django authentication and Ajax - URLs that require login

Nov 12th, 2011
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. def ajax_login_required(view_func):
  2. def wrap(request, *args, **kwargs):
  3. if request.user.is_authenticated():
  4. return view_func(request, *args, **kwargs)
  5. json = simplejson.dumps({ 'not_authenticated': True })
  6. return HttpResponse(json, mimetype='application/json')
  7. wrap.__doc__ = view_func.__doc__
  8. wrap.__dict__ = view_func.__dict__
  9. return wrap
  10.  
  11. @ajax_login_required
  12. def ajax_update_module(request, module_slug, action):
  13. # Etc ...
  14. return HttpResponse(json, mimetype='application/json')
  15.  
  16. $.post('/restricted-url/', data, function(json) {
  17. if (json.not_authenticated) {
  18. alert('Not authorized.'); // Or something in a message DIV
  19. return;
  20. }
  21. // Etc ...
  22. });
  23.  
  24. <a href="{{link}}" onclick="return login_popup()">
Add Comment
Please, Sign In to add comment