Welcome, guest | Sign In | My Account | Store | Cart

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.

Python, 30 lines
 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
#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")

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.

2 comments

Thomas Guettler 13 years, 4 months ago  # | flag

Please use 4 spaces for indentation.

hari Kumar 10 years ago  # | flag

Thanks.........

Created by Jian Ding Chen on Mon, 23 Oct 2006 (PSF)
Python recipes (4591)
Jian Ding Chen's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks