• Home
  • New Entries
  • Popular Entries
  • Submit a Story
  • About

Django AJAX authentication ...

Ajax is very fundamental tool for any RIA. Django makes it rather easy to interact with Ajax, specially if you’re using some of the common JavaScript frameworks like jQuery, Dojotoolkit or Ext-JS.

To make things easy Let’s start by copying and modifying existing decorators from Django sources:

01 from django.http import HttpResponseRedirect, HttpResponse
02 from django.utils.http import urlquote
03 from django.utils.functional import wraps
04 from django.utils.decorators import auto_adapt_to_methods
05 from django.contrib.auth import REDIRECT_FIELD_NAME
06 
07 def user_passes_test_with_ajax(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
08     """
09     Decorator for views that checks that the user passes the given test,
10     redirecting to the log-in page if necessary. The test should be a callable
11     that takes the user object and returns True if the user passes.
12 
13     Returns special response to ajax calls instead of blind redirecting.
14     """
15     if not login_url:
16         from django.conf import settings
17         login_url = settings.LOGIN_URL
18 
19     def decorator(view_func):
20         def _wrapped_view(request, *args, **kwargs):
21             if test_func(request.user):
22                 return view_func(request, *args, **kwargs)
23             path = urlquote(request.get_full_path())
24             tup = login_url, redirect_field_name, path
25             # Hook in ajax
26             if not request.is_ajax():
27                 return HttpResponseRedirect(\%s?%s=%s % tup)
28             else:
29                 # In case of ajax we send 401 - unauthorized HTTP response
30                 return HttpResponse(\%s?%s=%s % tup, status=401)
31 
32         return wraps(view_func)(_wrapped_view)
33     return auto_adapt_to_methods(decorator)
34 
35 def login_required_with_ajax(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
36     """
37     Decorator for views that checks that the user is logged in, redirecting
38     to the log-in page if necessary.
39 
40     Takes account ajax handling with redirections
41     """
42     actual_decorator = user_passes_test_with_ajax(
43         lambda u: u.is_authenticated(),
44         redirect_field_name=redirect_field_name
45     )
46     if function:
47         return actual_decorator(function)
48     return actual_decorator

Then in a view code you just need to use our magical decorator:

1 from decorators import login_required_with_ajax
2 from django.http import HttpResponse
3 
4 @login_required_with_ajax
5 def test(request):
6     return HttpResponse("Success!")

And for the last thing we need hookup in JavaScript. I made example with jQuery:

01 <DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
02 <html>
03     <head>
04         <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
05         <title>AJAX authentication test</title>
06         <script type="text/<span class="><!--mce:0--></script>
07         <script type="text/javascript">
08             function test_ajax() {
09                 $.ajax({
10                     url : /testview/,
11                     success : function (data, textStatus, request) {
12                         $(#_result).html(data);
13                     },
14                     error: function(request, textStatus, errorThrown){
15                         if (request.status == 401) {
16                             // Redirect to login
17                             window.location = request.responseText;
18                         }
19                     }
20                 });
21             }
22         </script>
23     </head>
24     <body>
25         <button type="button" onclick="test_ajax()">Test Ajax</button>
26         <div>Result was:<span id="_result">[Not tested yet]</span></div>
27     </body>
28 </html>

 Original Source:
http://drpinkpony.wordpress.com/2010/02/02/django-ajax-authentication/

AddThis Social Bookmark Button

Posted at 09:26:47 am | Permalink | Posted in Ajax  Toolkits  

Related Stuff

  • MooV: Using cutting edge Video phones and Software Video Phones - coupling all that with VoIP and empowering the disabled.

  • Moo Telecom: VoIP communications made easy - Ring anyway with the fun and ease of using a normal phone

  • TagR:Mobile Social Network with Real Time Locations Based services, and Ambience Intelligence, VoiP, IM, Skype, Googletalk, Mapping, Flickr, Events, Calendaring, Scheduling, SecondLife Support

  • ClearSMS : ClearSMS is a Web-based application that lets you send bulk SMS messages to your customers, contacts, or just about anyone.

  • Jajah:jah is a VoIP (Voice over IP) provider, founded by Austrians Roman Scharf and Daniel Mattes in 2005[1]. The Jajah headquarters are located in Mountain View, CA, USA, and Luxembourg. Jajah maintains a development centre in Israel.

  • Skype: It’s free to download and free to call other people on Skype. Skype the number one voice over ip software

  • PrivatePhone: a free local phone number with voicemail and messages you can check online or from any phone.

Top Stuff

MessengerFX

e-messenger

ILoveIM

Top 20 Ruby CMS

eBuddy

MSN Web Messenger



About Ajaxlines

Ajaxlines is a project focused on providing its audience with a database of most of Ajax related articles, resources, tutorials and services from around the world.

Its purpose is to showcase the power of Ajax and to act as a portal to the Ajax development community.


Search


Topics

  • .Net (164)
  • Ajax (82)
  • Ajax Games (10)
  • Articles (95)
  • Bookmarking (35)
  • Calendar (20)
  • Chat (45)
  • ColdFusion (3)
  • CSS (75)
  • Email (23)
  • Facebook (83)
  • Flash (19)
  • Google (54)
  • Html (27)
  • Image (11)
  • International Calls & VOIP (7)
  • Java (54)
  • Javascript (265)
  • jQuery (159)
  • JSON (61)
  • Perl (2)
  • PHP (156)
  • Presentation (19)
  • Python (3)
  • Resources (2)
  • RSS (8)
  • Ruby (31)
  • Storage (4)
  • Toolkits (103)
  • Tutorials (217)
  • UI (11)
  • Utilities (174)
  • Web2.0 (18)
  • XmlHttpRequest (28)
  • YUI (12)

© 2006 www.ajaxlines.com. All Rights Reserved. Powered by IRange