Masquerade as a particular user and redirect based on the
    REDIRECT_FIELD_NAME parameter, or the LOGIN_REDIRECT_URL.

    Callers can either pass the pk of the user in the URL itself, or as a POST
    param.

def cloak(request, pk=None):
    """
    Masquerade as a particular user and redirect based on the
    REDIRECT_FIELD_NAME parameter, or the LOGIN_REDIRECT_URL.

    Callers can either pass the pk of the user in the URL itself, or as a POST
    param.
    """
    pk = request.POST.get('pk', pk)
    if pk is None:
        return HttpResponse("You need to pass a pk POST parameter, or include it in the URL")

    user = get_object_or_404(get_user_model(), pk=pk)

    if not can_cloak_as(request.user, user):
        return HttpResponseForbidden("You are not allowed to cloak as this user")

    request.session[SESSION_USER_KEY] = user.pk
    # save the referer information so when uncloaking, we can redirect the user
    # back to where they were
    request.session[SESSION_REDIRECT_KEY] = request.META.get("HTTP_REFERER", settings.LOGIN_REDIRECT_URL)

    # redirect the cloaked user to the URL specified in the "next" parameter,
    # or to the default redirect URL
    return HttpResponseRedirect(request.POST.get(REDIRECT_FIELD_NAME, settings.LOGIN_REDIRECT_URL))