from functools import wraps

from kfet.auth.backends import AccountBackend


def kfet_password_auth(view_func):
    def get_kfet_password(request):
        return request.META.get("HTTP_KFETPASSWORD") or request.POST.get("KFETPASSWORD")

    @wraps(view_func)
    def _wrapped_view(request, *args, **kwargs):
        if request.method == "POST":
            temp_request_user = AccountBackend().authenticate(
                request, kfet_password=get_kfet_password(request)
            )

            if temp_request_user:
                request.real_user = request.user
                request.user = temp_request_user

        return view_func(request, *args, **kwargs)

    return _wrapped_view
