본문 바로가기
IT/Django

Django, 사용자가 로그인 했는지 확인하는 decorator

by Cyber_ 2024. 4. 7.

0. 인증과 인가

  • 인증: 사용자의 신원을 증명하는 것
  • 인가: 인증과 달리 액세스 권한을 확인하는 프로세스
  • Django에서 권한 확인을 도와주는 데코레이터에 대해서 알아보자.

1. view.py

1) 적용된 데코레이터

  • @login_required(login_url='accounts:login')
    을 작성해주면된다.
.....
.....
from django.contrib.auth.decorators import login_required



@login_required(login_url='accounts:login')
def answer_create(request, question_id):
    """
    pybo 답변 등록
    """
    question = get_object_or_404(Question, pk=question_id)
    if request.method == "POST":
        form = AnswerForm(request.POST)
        if form.is_valid():
            answer = form.save(commit=False)
            answer.author = request.user
            answer.create_date = timezone.now()
            answer.question = question
            answer.save()
            return redirect('{}#answer_{}'.format(
                resolve_url('pybo:detail', question_id=question.id), answer.id))
    else:
        form = AnswerForm()
    context = {'question': question, 'form':form}
    return render(request, 'pybo/question_detail.html', context)

2) @login_required 설명

  • 아래는 login_required의 함수이다.
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
  • actual_decorator를 보면 user_passed_test로 넘어간다.
 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)
        def _wrapper_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 _wrapper_view

    return decorator
  • test_func: 사용자 객체를 인수로 받고, 사용자가 테스트를 통과하면 True를 반환하는 호출 가능한 함수
  • login_url: 사용자가 테스트를 통과하지 못했을 때 리디렉션될 로그인 URL, None일 경우 settigns의 LOGIN_URL을 사용
  • redirect_field_name: 리디렉션된 후 원래 페이지로 돌아갈 수 있도록 URL에 추가할 쿼리 파라미터 이름. 기본값은 REDIRECT_FIELD_NAME
  • _wrapper_view: 실제로 뷰 함수를 감싸는 함수, 요청과 추가 인수들을 받는다.

3) permission_reqired

  • decrator.py에는 위 두 함수를 제외하면 하나의 함수가 더있다.
  • 이 함수는 로그인을 확인하는 것이 아닌 특정 권한(perm)이 있는지 확인하는 함수다.
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


def permission_required(perm, login_url=None, raise_exception=False):
    """
    Decorator for views that checks whether a user has a particular permission
    enabled, redirecting to the log-in page if necessary.
    If the raise_exception parameter is given the PermissionDenied exception
    is raised.
    """

    def check_perms(user):
        if isinstance(perm, str):
            perms = (perm,)
        else:
            perms = perm
        # First check if the user has the permission (even anon users)
        if user.has_perms(perms):
            return True
        # In case the 403 handler should be called raise the exception
        if raise_exception:
            raise PermissionDenied
        # As the last resort, show the login form
        return False

    return user_passes_test(check_perms, login_url=login_url)