ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: custom django login_required decorator
Submitter: Jian Ding Chen (other recipes)
Last Updated: 2006/10/24
Version no: 1.1
Category: Web

 

Not Rated yet


Description:

I found django's auth module is too complex for my needs, instead I wrote a relative simple one, but I miss the login_required decorator in django auth module, so I decide to write a new one.

Source: Text Source

#the decorator
def myuser_login_required(f):
        def wrap(request, *args, **kwargs):
                #this check the session if userid key exist, if not it will redirect to login page
                if 'userid' not in request.session.keys():
                        return HttpResponseRedirect("/mysite/login")
                return f(request, *args, **kwargs)
        wrap.__doc__=f.__doc__
        wrap.__name__=f.__name__
        return wrap

#how you use this decorator is simple, same as the @login_required decorator
@myuser_login_required
def myuser_create(request):
         #blahblah here's how you create your user....
         #and you can make sure your user already logined.

#remember to register session id in your login function
#this is just a naive sample
import md5
def my_login(request):
         if request.POST:
                   try:
                          m = myuser.objects.filter(userid__exact=request.POST['userid'])
                          if str(m.get().password) == md5.md5(request.POST["password"]).hexdigest():
                                     request.session['userid'] = str(m.get().userid)
                          else:
                                     raise
                   except:
                                      return HttpResponseRedirect("/mysite/login")

Discussion:

I didn't find an elegent way to extends the auth module and the login_required decorator, so instead, I write my simple one. The way how I redirect the web page is naive but it already fits my need.



Add comment

No comments.



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. IPy Notify

4. Changing return value ...

5. Quantum Superposition

6. Pickle objects under ...

7. Generalized delegates ...

8. Reorder a sequence (uses ...

9. Setting Win32 System ...

10. ObjectMerger




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.