"""
@module de.stschnell
@version 0.1.0
@runtime python:3.10
@inputType in_url {string}
@inputType in_userName {string}
@inputType in_password {string}
@outputType Properties
"""
import base64
import json
import ssl
import urllib.request
def request(
url,
user = None,
password = None,
bearerToken = None,
method = "GET",
body = {},
contentType = "application/json;charset=utf-8",
accept = "application/json"
):
""" Executes a REST request
@param {string} url - URL to execute the request
@param {string} user
@param {string} password
@param {string} bearerToken
@param {string} method - Method of request, e.g. GET, POST, etc
@param {dictionary} body - Body of request
@param {string} contentType - MIME type of the body for the request
@param {string} accept - MIME type of response content
@returns {dictionary}
"""
returnValue = {}
try:
request = urllib.request.Request(
url = url,
method = method,
data = bytes(json.dumps(body).encode("utf-8"))
)
if user and password:
authorization = base64.b64encode(
bytes(user + ":" + password, "UTF-8")
).decode("UTF-8")
request.add_header(
"Authorization", "Basic " + authorization
)
if bearerToken:
request.add_header(
"Authorization", "Bearer " + bearerToken
)
request.add_header(
"Content-Type", contentType
)
request.add_header(
"Accept", accept
)
response = urllib.request.urlopen(
request,
context = ssl._create_unverified_context()
)
if response.getcode() == 200:
if "json" in accept:
returnValue = json.loads(response.read())
else:
returnValue = response.read()
except Exception as err:
raise Exception(f"An error occurred at request - {err}") \
from err
return returnValue
def getBearerToken(
url,
username,
password
):
""" Gets the Bearer token
@param {string} url
@param {string} username
@param {string} password
"""
returnValue = None
try:
login = {
"username": username,
"password": password
}
refreshToken = request(
url = url + "/csp/gateway/am/api/login?access_token",
method = "POST",
body = login
)["refresh_token"]
bearerToken = request(
url = url + "/iaas/api/login",
method = "POST",
body = { "refreshToken": refreshToken }
)["token"]
returnValue = bearerToken
except Exception as err:
raise ValueError(f"An error occurred at get Bearer token - {err}") \
from err
return returnValue
def handler(context, inputs):
""" Aria Automation standard handler, the main function.
"""
url = "https://auto.vcf.sddc.lab"
username = "holadmin@vcf.holo.lab"
password = "VMware123!"
# vcoUrl = inputs["in_url"]
# username = inputs["in_userName"]
# password = inputs["in_password"]
try:
bearerToken = getBearerToken(
url,
username,
password
)
outputs = {
"status": "done",
"error": None,
"result": bearerToken
}
except Exception as err:
outputs = {
"status": "incomplete",
"error": repr(err),
"result": None
}
return outputs
|