Login

Anonymous required decorator

Author:
Motanelu
Posted:
January 6, 2010
Language:
Python
Version:
1.1
Tags:
decorators acl
Score:
-1 (after 5 ratings)

A decorator that allows the programmer to restrict access to some views only to non logged-in users. For instance, if an user in logged in, it should be denied access to views like /accounts/register or /accounts/login.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.http import HttpResponseRedirect

def anonymous_required( view_function, redirect_to = None ):
    return AnonymousRequired( view_function, redirect_to )

class AnonymousRequired( object ):
    def __init__( self, view_function, redirect_to ):
        if redirect_to is None:
            from django.conf import settings
            redirect_to = settings.LOGIN_REDIRECT_URL
        self.view_function = view_function
        self.redirect_to = redirect_to

    def __call__( self, request, *args, **kwargs ):
        if request.user is not None and request.user.is_authenticated():
            return HttpResponseRedirect( self.redirect_to ) 
        return self.view_function( request, *args, **kwargs )

More like this

  1. anonymous_required decorator by yetty 1 year, 8 months ago
  2. Google Account authentication by Hangya 4 years, 7 months ago
  3. is_staff decorator by munhitsu 6 years, 7 months ago
  4. view by view basic authentication decorator by Scanner 7 years, 10 months ago
  5. Registering Facebook user by username before loggin in by zjor 1 year, 9 months ago

Comments

Motanelu (on February 11, 2010):

Fixed the condition.

#

Please login first before commenting.