如何在Django中编写装饰器来检查两个不同的条件并相应地重定向?

时间:2015-09-01 11:57:22

标签: python django authentication decorator

在我的项目中,一旦注册,用户必须先创建Profile才能访问网站的其余部分。我希望装扮@profile_decorator代替@login_decorator

如果用户

  1. 未登录,重定向到login URL
  2. 已登录,但没有profile,重定向到create profile URL
  3. 已登录,已profile,允许继续查看
  4. 这来自django.contrib.auth.decorators

    from functools import wraps
    
    from django.conf import settings
    from django.contrib.auth import REDIRECT_FIELD_NAME
    from django.shortcuts import resolve_url
    from django.utils.decorators import available_attrs
    from django.utils.six.moves.urllib.parse import urlparse
    
    
    def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
        """
        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):
            @wraps(view_func, assigned=available_attrs(view_func))
            def _wrapped_view(request, *args, **kwargs):
                if test_func(request.user):
                    return view_func(request, *args, **kwargs)
                path = request.build_absolute_uri()
                resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
                # If the login url is the same scheme and net location then just
                # use the path as the "next" url.
                login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
                current_scheme, current_netloc = urlparse(path)[:2]
                if ((not login_scheme or login_scheme == current_scheme) and
                        (not login_netloc or login_netloc == current_netloc)):
                    path = request.get_full_path()
                from django.contrib.auth.views import redirect_to_login
                return redirect_to_login(
                    path, resolved_login_url, redirect_field_name)
            return _wrapped_view
        return decorator
    
    
    def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
        """
        Decorator for views that checks that the user is logged in, redirecting
        to the log-in page if necessary.
        """
        actual_decorator = user_passes_test(
            lambda u: u.is_authenticated(),
            login_url=login_url,
            redirect_field_name=redirect_field_name
        )
        if function:
            return actual_decorator(function)
        return actual_decorator
    

    这是我到目前为止所做的:

    from django.contrib.auth import REDIRECT_FIELD_NAME
    from django.contrib.auth.decorators import user_passes_test
    
    from django.conf.settings import CREATE_PROFILE_REDIRECT_URL
    
    from .models import Profile
    
    
    def profile_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
        """
        Decorator for views that checks that the user is logged in and has created
        a profile, redirecting to the log-in page if necessary.
        """
        actual_decorator = user_passes_test(
            test_func,
            login_url=login_url,
            redirect_field_name=redirect_field_name
        )
        if function:
            return actual_decorator(function)
        return actual_decorator
    
    
    def test_func(u):
        if u.is_authenticated():
            if Profile.objects.filter(user=u).exists():
                return True
        return False
    

    现在我很困惑,意识到我不知道这对1.2.的反应如何。

    编辑: login_required装饰器具有我想要保留的其他功能 - 它会将用户重定向回他们在成功登录后尝试访问的原始页面。对不起,本来应该说。

2 个答案:

答案 0 :(得分:4)

我不认为你试图使用user_passes_test装饰器来帮助自己。如果你自己从头开始创建装饰器,你会发现这更容易。

def profile_required(view_func):
    def wrapped(request, *args, **kwargs):
        if request.user.is_anonymous():
            path = request.build_absolute_uri()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(path, LOGIN_URL)
        else:
            try:
                profile = request.user.profile
            except Profile.DoesNotExist:
                return redirect(CREATE_PROFILE_REDIRECT_URL)
            else:
                return view_func(request, *args, **kwargs)
    return wrapped

答案 1 :(得分:0)

这应该有效

from functools import wraps

def profile_required(view_func):
  def _decorator(request, *args, **kwargs):
    if request.user.is_anonymous():
        return redirect(LOGIN_URL)
    else:
        try:
            profile = Profile.object.get(user=request.user)
        except Profile.DoesNotExist:
            return redirect('userprofile_url')

    response = view_func(request, *args, **kwargs)

    return response
return wraps(view_func)(_decorator)


@profile_required
def your_func(request):
   # do something