Skip to content

get_token

Get token helper function. Retrieve the Keycloak token on local machine.

get_token()

Retrieves token if it exists or returns None if no token exists.

Returns:

Type Description
Optional[str]

Either the Keycloak token, if it exists, or None if it does not exist.

Source code in dapla_team_cli/auth/services/get_token.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def get_token() -> Optional[str]:
    """Retrieves token if it exists or returns None if no token exists.

    Returns:
        Either the Keycloak token, if it exists, or None if it does not exist.
    """
    # Taken from dapla-toolbelt
    if os.getenv("NB_USER") == "jovyan":
        hub = HubAuth()
        response = requests.get(
            os.environ["LOCAL_USER_PATH"],
            headers={"Authorization": f"token {hub.api_token}"},
            cert=(str(hub.certfile), str(hub.keyfile)),
            verify=str(hub.client_ca),
            allow_redirects=False,
            timeout=10,
        )
        if response.status_code != 200:
            logger.debug(
                "status code %d fetching token | reason: %s | response body: %s",
                response.status_code,
                response.reason,
                response.content.decode("utf-8"),
            )
            print("Error fetching token.")
            typer.Abort()
        token = str(response.json()["access_token"])
        if not token:
            logger.debug(
                "successful response fetching token, but token missing | response body: %s", response.content.decode("utf-8")
            )
            print("Token missing from auth response.")
            typer.Abort()
        return token

    config_folder_path = get_config_folder_path()
    config_file_path = config_folder_path + "/dapla-cli-keycloak-token.json"

    keycloak_token = None
    if os.path.isfile(config_file_path):
        with open(config_file_path, encoding="UTF-8") as f:
            data = json.loads(f.read())
            keycloak_token = data["keycloak_token"]

    if keycloak_token is None:
        logger.debug("keycloak token not set")

    return keycloak_token