Fetches OAuth access token from the OAuth Auth Server using client_id and client_secret. If however, the oauth_mock_response is set, then it returns the contents of the file passed as parameter for oauth_mock_response_cmd.
(self)
| 1940 | return True |
| 1941 | |
| 1942 | def oauth_get_access_token(self): |
| 1943 | """Fetches OAuth access token from the OAuth Auth Server |
| 1944 | using client_id and client_secret. If however, the |
| 1945 | oauth_mock_response is set, then it returns the contents |
| 1946 | of the file passed as parameter for oauth_mock_response_cmd. |
| 1947 | """ |
| 1948 | json_body = dict() |
| 1949 | if self.use_oauth and self.oauth is None: |
| 1950 | if self.oauth_server is None: |
| 1951 | print("Error: OAuth Server is empty") |
| 1952 | sys.exit(1) |
| 1953 | if self.oauth_endpoint is None: |
| 1954 | print("Error: OAuth endpoint is empty") |
| 1955 | sys.exit(1) |
| 1956 | if self.oauth_client_id is None: |
| 1957 | print("Error: OAuth Client id is empty") |
| 1958 | sys.exit(1) |
| 1959 | |
| 1960 | # If client secret is not provided through a command, then request it from user |
| 1961 | if self.oauth_client_secret is None: |
| 1962 | self.oauth_client_secret = getpass.getpass("Enter OAuth Client Secret: ") |
| 1963 | |
| 1964 | # Fetch the access tokens first using client id and client secret |
| 1965 | if self.oauth_mock_response is None: |
| 1966 | try: |
| 1967 | # Retreive the oauth access token from the OAuth Server |
| 1968 | conn = http_client.HTTPSConnection(self.oauth_server, timeout=10) |
| 1969 | payload = "{\"client_id\":\"" + self.oauth_client_id + \ |
| 1970 | "\",\"client_secret\":\"" + self.oauth_client_secret + \ |
| 1971 | "\",\"audience\":\"https://" + self.oauth_server + \ |
| 1972 | "/api/v2/\",\"grant_type\":\"client_credentials\"}" |
| 1973 | headers = {'content-type': "application/json", "charset": "utf-8"} |
| 1974 | conn.request("POST", self.oauth_endpoint, payload.encode('utf-8'), headers) |
| 1975 | res = conn.getresponse() |
| 1976 | if (res.status != 200): |
| 1977 | print("HTTP error: ", res.status, res.read().decode("utf-8")) |
| 1978 | sys.exit(1) |
| 1979 | data = res.read() |
| 1980 | json_body = json.loads(data.decode("utf-8")) |
| 1981 | except Exception as e: |
| 1982 | print("Error getting OAuth access tokens", e) |
| 1983 | sys.exit(1) |
| 1984 | finally: |
| 1985 | if conn: |
| 1986 | conn.close() |
| 1987 | else: |
| 1988 | # Fetch mock response |
| 1989 | json_body = json.loads(self.oauth_mock_response) |
| 1990 | |
| 1991 | if "access_token" in json_body.keys(): |
| 1992 | self.oauth = json_body["access_token"] |
| 1993 | else: |
| 1994 | print("Error: OAuth access token not found in json payload") |
| 1995 | sys.exit(1) |
| 1996 | |
| 1997 | |
| 1998 | TIPS = [ |