import base64
import requests
import json


def retrieve_appdevtools_access_token(username, password, auth_endpoint):
    """
    Retrieve access token for appdev tools

    Args:
        username: username
        password: password
        auth_endpoint: authorization endpoint

    Returns: token
    """
    # Form credentials request
    credentials = "{0}:{1}".format(username, password)
    base_encoded_credential = base64.b64encode(bytes(credentials, "utf-8")).decode().replace('\n', '')
    # Form application headers
    headers = {
        "content-type": "application/json",
        "Authorization": "Basic {}".format(base_encoded_credential)
    }
    # Form login request
    login_request = {
        "username": username,
        "password": password
    }
    # Issue request, skip SSL validation
    response = requests.post(url=auth_endpoint, json=login_request,
                             headers=headers, verify=True)
    # Get access token
    return json.loads(response.text)["token"]