54 lines
1.6 KiB
Python
54 lines
1.6 KiB
Python
from ansible.module_utils.six.moves.urllib.error import HTTPError
|
|
from ansible_collections.ansible.netcommon.plugins.plugin_utils.httpapi_base import (
|
|
HttpApiBase,
|
|
)
|
|
|
|
import json
|
|
|
|
|
|
class HttpApi(HttpApiBase):
|
|
def login(self, username, password):
|
|
"""
|
|
Log in to the rest api.
|
|
Return True if the connection has succeeded and False otherwise.
|
|
"""
|
|
data = {"userName": username, "password": password}
|
|
response = self.send_request("login-sessions", data, method="POST")
|
|
|
|
if response.status_code != 201:
|
|
return AnsibleAuthentificationFailure(message="Plop!")
|
|
|
|
data = response.json()
|
|
if not "cookie" in data:
|
|
return False
|
|
|
|
self.headers["cookie"] = data["cookie"]
|
|
return True
|
|
|
|
def logout(self):
|
|
"""
|
|
Log out of the rest api.
|
|
Return True if connection has succeeded and False otherwise
|
|
"""
|
|
response = self.delete("/login-sessions")
|
|
if response.status_code != 204:
|
|
return False
|
|
self.headers.pop("cookie")
|
|
return True
|
|
|
|
def send_request(self, path, data, method="GET"):
|
|
headers = {"Content-Type": "application/json"}
|
|
api = self.connection.get_option("api")
|
|
uri = f"/rest/{api}/{path}"
|
|
|
|
if not data:
|
|
data = {}
|
|
|
|
content = json.dumps(data)
|
|
|
|
try:
|
|
response, content = self.connection.send(uri, content, method=method, headers=headers)
|
|
except HTTPError as exc:
|
|
return exc.code, exc.read()
|
|
|
|
return response.read()
|