import requests from urllib.parse import urlencode, urlparse import os # Configuration details for Guru OAuth - Hardcoded values redirect_uri = 'https://us-west-2.console.aws.amazon.com/appflow/oauth' client_id = '' client_secret = '' auth_url = 'https://api.getguru.com/oauth/authorize' token_url = 'https://api.getguru.com/oauth/token' token_file_path = "" def get_authorization_code(): """Get authorization code by guiding the user to the authorization URL.""" params = { "client_id": client_id, "response_type": "code", "redirect_uri": redirect_uri, "scope": "read:*", # Guru API specific scope "state": "guru_auth_state" } # Generate the authorization URL authorization_request_url = auth_url + "?" + urlencode(params) print(f"Please open the following URL in your browser to grant permissions:") print(authorization_request_url) print("After granting permissions, you will be redirected to the provided redirect URI.") print("Copy and paste the full redirected URL here.") redirected_url = input("Enter the redirected URL: ") # Parse the authorization code from the redirected URL parsed_url = urlparse(redirected_url) query_params = dict(param.split('=') for param in parsed_url.query.split('&') if '=' in param) authorization_code = query_params.get("code") if not authorization_code: print("Authorization code not found in the redirected URL. Please ensure the URL is correct.") return None return authorization_code def get_access_token(authorization_code): """Exchange the authorization code for an access token and a refresh token.""" data = { "client_id": client_id, "grant_type": "authorization_code", "code": authorization_code, "redirect_uri": redirect_uri, "scope": "read:*", "client_secret": client_secret } response = requests.post(token_url, data=data) if response.status_code == 200: token_data = response.json() access_token = token_data.get('access_token') refresh_token = token_data.get('refresh_token') return token_data, access_token, refresh_token else: print("Error fetching tokens:", response.text) return None, None, None def refresh_access_token(refresh_token): """Use the refresh token to get a new access token.""" data = { "grant_type": "refresh_token", "client_id": client_id, "client_secret": client_secret, "refresh_token": refresh_token } response = requests.post(token_url, data=data) if response.status_code == 200: token_data = response.json() new_access_token = token_data.get('access_token') new_refresh_token = token_data.get('refresh_token', refresh_token) return token_data, new_access_token, new_refresh_token else: print("Error refreshing token:", response.text) return None, None, None def verify_token(access_token): """Verify that the token works by making a test API call to Guru.""" if not access_token: return False headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } try: # Try to get user info to verify the token works verify_url = "https://api.getguru.com/api/v1/whoami" response = requests.get(verify_url, headers=headers) response.raise_for_status() return True except requests.exceptions.RequestException as e: print(f"Token verification failed: {e}") return False def save_tokens_to_file(token_data, authorization_code, access_token, refresh_token): """Save the tokens and authorization code to a file.""" try: with open(token_file_path, "w") as file: file.write(f"Auth code: \n{authorization_code}\n\n") file.write(f"Access token: \n{access_token}\n\n") file.write(f"Refresh token: \n{refresh_token}\n\n") return True except Exception as e: print(f"Error saving tokens to file: {e}") return False if __name__ == "__main__": # Proceed directly with browser flow authorization_code = get_authorization_code() if not authorization_code: print("Failed to retrieve the authorization code. Exiting.") else: # Use the authorization code to fetch tokens token_data, access_token, refresh_token = get_access_token(authorization_code) if access_token and refresh_token: # Verify the token works if verify_token(access_token): # Save the tokens and authorization code to a file save_tokens_to_file(token_data, authorization_code, access_token, refresh_token) else: print("Token verification failed. The tokens may not be valid.") else: print("Failed to obtain tokens.")