Revision b6496f0c snf-astakos-app/astakos/im/views/decorators.py

b/snf-astakos-app/astakos/im/views/decorators.py
33 33

  
34 34
from functools import wraps
35 35

  
36
from django.utils.http import urlquote
36 37
from django.contrib import messages
37
from django.contrib.auth.decorators import login_required
38 38
from django.core.exceptions import PermissionDenied
39 39
from django.core.urlresolvers import reverse
40 40
from django.http import HttpResponse, HttpResponseRedirect
41
from django.utils.decorators import available_attrs
41 42
from django.utils.http import urlencode
42 43

  
43 44
from astakos.im import auth_providers as auth
44 45
from astakos.im.cookie import CookieHandler
45 46

  
47
REDIRECT_FIELD_NAME = 'next'
48

  
49

  
50
def user_passes_test(test_func, login_url=None,
51
                     redirect_field_name=REDIRECT_FIELD_NAME):
52
    """
53
    Decorator for views that checks that the user passes the given test,
54
    redirecting to the log-in page if necessary. The test should be a callable
55
    that takes the user object and returns True if the user passes.
56
    """
57
    if not login_url:
58
        from django.conf import settings
59
        login_url = settings.LOGIN_URL
60

  
61
    def decorator(view_func):
62
        def _wrapped_view(request, *args, **kwargs):
63
            if test_func(request.user):
64
                return view_func(request, *args, **kwargs)
65
            path = urlquote(request.get_full_path())
66
            tup = reverse('login'), redirect_field_name, path
67
            return HttpResponseRedirect('%s?%s=%s' % tup)
68
        return wraps(view_func,
69
                     assigned=available_attrs(view_func))(_wrapped_view)
70
    return decorator
71

  
72

  
73
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME,
74
                   login_url=None):
75
    """
76
    Decorator for views that checks that the user is logged in, redirecting
77
    to the log-in page if necessary.
78
    """
79
    actual_decorator = user_passes_test(
80
        lambda u: u.is_authenticated(),
81
        redirect_field_name=redirect_field_name,
82

  
83
    )
84
    if function:
85
        return actual_decorator(function)
86
    return actual_decorator
87

  
46 88

  
47 89
def cookie_fix(func):
48 90
    """
......
71 113

  
72 114
def requires_auth_provider(provider_id, **perms):
73 115
    """
116
    View requires specified authentication module to be enabled in
117
    ASTAKOS_IM_MODULES setting.
74 118
    """
75 119
    def decorator(func, *args, **kwargs):
76 120
        @wraps(func)

Also available in: Unified diff