Login

Decorator to logout user based on a test and/or redirect to another url

Author:
vemubalu
Posted:
December 8, 2010
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

This decorator is for views that one wants only users of the site to logout based on few conditions

Just add the decorator and it should logout anyuser who doestnot match the condition

btw I borrowed the code from django`s source code

 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
### Decorator to logout the admin from the regular pages
try:
    from functools import update_wrapper, wraps
except ImportError:
    from django.utils.functional import update_wrapper, wraps  # Python 2.4 fallback.


from django.http import HttpResponseRedirect
from django.utils.decorators import available_attrs
from django.utils.http import urlquote


def logout_user_and_redirect_on_test(test_func, redirect_url = None ):
    """ 
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """
    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            from django.contrib.auth import logout
            logout(request)
            
            if redirect_url:
                return HttpResponseRedirect(redirect_url)
            else :
                return HttpResponseRedirect(request.path)                
        return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
    return decorator

#---------------------------

def logout_admin(user):
    if user.is_authenticated and (user.is_staff or user.is_superuser):
        return False
    else :         
        return True

def logout_non_xxxxxx(user):
    try :
        if user.is_authenticated and user.xxxx_related.xxxr:
            return False
        else :         
            return True
    except :
        return False

############# sample view

@logout_user_and_redirect_on_test(logout_non_xxxxxx,'/')
@logout_user_and_redirect_on_test(logout_admin)
def some_view(request):
     return HttpResponse('Hello World')

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.