Debian Codegraph @

lib/ansible/plugins/httpapi/__init__.py

raw
1 # (c) 2018 Red Hat Inc.
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 from __future__ import annotations
5
6 from abc import abstractmethod
7
8 from ansible.plugins import AnsiblePlugin
9
10
11 class HttpApiBase(AnsiblePlugin):
12 def __init__(self, connection):
13 super(HttpApiBase, self).__init__()
14
15 self.connection = connection
16 self._become = False
17 self._become_pass = ''
18
19 def set_become(self, become_context):
20 self._become = become_context.become
21 self._become_pass = getattr(become_context, 'become_pass') or ''
22
23 def login(self, username, password):
24 """Call a defined login endpoint to receive an authentication token.
25
26 This should only be implemented if the API has a single endpoint which
27 can turn HTTP basic auth into a token which can be reused for the rest
28 of the calls for the session.
29 """
30 pass
31
32 def logout(self):
33 """ Call to implement session logout.
34
35 Method to clear session gracefully e.g. tokens granted in login
36 need to be revoked.
37 """
38 pass
39
40 def update_auth(self, response, response_text):
41 """Return per-request auth token.
42
43 The response should be a dictionary that can be plugged into the
44 headers of a request. The default implementation uses cookie data.
45 If no authentication data is found, return None
46 """
47 cookie = response.info().get('Set-Cookie')
48 if cookie:
49 return {'Cookie': cookie}
50
51 return None
52
53 def handle_httperror(self, exc):
54 """Overridable method for dealing with HTTP codes.
55
56 This method will attempt to handle known cases of HTTP status codes.
57 If your API uses status codes to convey information in a regular way,
58 you can override this method to handle it appropriately.
59
60 :returns:
61 * True if the code has been handled in a way that the request
62 may be resent without changes.
63 * False if the error cannot be handled or recovered from by the
64 plugin. This will result in the HTTPError being raised as an
65 exception for the caller to deal with as appropriate (most likely
66 by failing).
67 * Any other value returned is taken as a valid response from the
68 server without making another request. In many cases, this can just
69 be the original exception.
70 """
71 if exc.code == 401:
72 if self.connection._auth:
73 # Stored auth appears to be invalid, clear and retry
74 self.connection._auth = None
75 self.login(self.connection.get_option('remote_user'), self.connection.get_option('password'))
76 return True
77 else:
78 # Unauthorized and there's no token. Return an error
79 return False
80
81 return exc
82
83 @abstractmethod
84 def send_request(self, data, **message_kwargs):
85 """Prepares and sends request(s) to device."""
86 pass