in gitops/env/stage2/configs/mtk-connect/mtk-connect-post-key/configure-key.py [0:0]
def perform_api_request(operation=API_REQUEST_OPT["GET_VERSION"], is_delete_key_id=False):
"""
Sends request to api. Possible actions are listed in API_REQUEST_OPT.
Returns result flag: True if operation was succesfull.
"""
global KEY_VAL, OLD_KEY_VAL, OLD_KEY_ID_LS, USER_ID
result = False
try:
if operation == "GET_VERSION":
print("\nGet version of MTK Connect")
response_api = requests.get(API_REQUEST_OPT["GET_VERSION"], auth=(USERNAME, KEY_VAL))
elif operation == "GET_CURRENT_USER":
# Gets user data and stores value of the old key id, which will be used to delete the key
print("\nGet current user data")
response_api = requests.get(API_REQUEST_OPT["GET_CURRENT_USER"], auth=(USERNAME, KEY_VAL))
if is_delete_key_id and (response_api.status_code // 100 == 2):
# OLD_KEY_ID = get_key_id(response_api.json()["data"]["keys"], OLD_KEY_VAL)
OLD_KEY_ID_LS = get_keys_id_ls_to_delete(response_api.json()["data"]["keys"], KEY_VAL)
print(f"----\nKeys for deletion:\n{OLD_KEY_ID_LS}\n----")
elif operation == "CREATE_KEY":
print(f"\nCreate key for user id {USER_ID}")
# New key settings: name, expiration date.
# Current settings: name is empty, expiration date is set to 1 month after creation date (UTC+00:00 Timezone)
key_expiration_date = datetime.datetime.now(tz=datetime.timezone.utc) + relativedelta(months=1)
key_create_request_body = {
"name": "",
"expiryTime": f"{key_expiration_date.strftime('%Y-%m-%dT%H:%M:%SZ')}"
}
response_api = requests.post(API_REQUEST_OPT["CREATE_KEY"], auth=(USERNAME, KEY_VAL), json=key_create_request_body)
if response_api.status_code // 100 == 2:
OLD_KEY_VAL = KEY_VAL
KEY_VAL = response_api.json()["data"]["key"]
print(f"Thoreticaly key created. Is it saved? Key: {KEY_VAL}, old key: {OLD_KEY_VAL}")
elif operation == "DELETE_KEY":
print(f"\nDeleting keys id: {OLD_KEY_ID_LS}")
for delete_key_id in OLD_KEY_ID_LS:
response_api = requests.delete(API_REQUEST_OPT["DELETE_KEY"]+str(delete_key_id), auth=(USERNAME, KEY_VAL))
else:
print("There are no keys to delete.")
elif operation == "GET_USER_DETAILS":
print("\nRetreiving detail info for mtk-connect-admin user")
response_api = requests.get(API_REQUEST_OPT["GET_USER_DETAILS"], auth=(USERNAME, KEY_VAL))
if response_api.status_code // 100 == 2:
USER_ID = response_api.json()["data"][0]["id"]
else:
raise KeyError(f"Operation '{operation}' not found.")
except Exception as e:
print(f"Exception occured when requesting response from API. \n\t{e}")
else:
reponse_category = response_api.status_code // 100
if reponse_category == 2:
print(f"Operation done succesfully!")
result = True
elif reponse_category == 3:
print(f"Redirection!")
elif reponse_category == 4:
print(f"Client Error!")
elif reponse_category == 5:
print(f"Server Error!")
else:
print(f"There was a problem!")
print(f"Status code: {response_api.status_code} \nResponse from API: \n\t{response_api.text}")
print("Request to API finished")
return result