import json

from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse

from tauth.settings import config


def is_logged_in(request: WSGIRequest) -> HttpResponse:
    try:
        if request.GET.get("token") == config["services"][request.GET.get("service")]["token"]:
            return HttpResponse(
                json.dumps({
                    "success": True,
                    "auth": request.user.is_authenticated
                }),
                content_type="application/json"
            )
    except KeyError:
        ...

    return HttpResponse(
        json.dumps({
            "success": False
        }),
        content_type="application/json",
        status=401
    )
