ehsan-dashboards/dashboards/exchange_oauth.py

47 lines
1.7 KiB
Python

import json
import urllib.parse
import requests
CALLBACK_URL = "http://localhost:1/?state=SZbomF7KmPAcC2UwDzA2Jw&iss=https://accounts.google.com&code=4/0AXlqoi6PM-5rtAKe96ord-kSdXNBEfOACew3ur96-0HYlT3eMriMgLRI92JNmXCv8lrubg&scope=email%20https://www.googleapis.com/auth/userinfo.email%20openid%20https://www.googleapis.com/auth/analytics.readonly%20https://www.googleapis.com/auth/tagmanager.readonly%20https://www.googleapis.com/auth/webmasters.readonly&authuser=0&prompt=consent"
with open('/workspace/personal/oauth_pending.json') as f:
pending = json.load(f)
parsed = urllib.parse.urlparse(CALLBACK_URL)
qs = urllib.parse.parse_qs(parsed.query)
code = qs.get('code', [None])[0]
state = qs.get('state', [None])[0]
if state != pending['state']:
print("State mismatch error!")
exit(1)
token_endpoint = "https://oauth2.googleapis.com/token"
data = {
'client_id': pending['client_id'],
'client_secret': pending['client_secret'],
'code': code,
'code_verifier': pending['code_verifier'],
'grant_type': 'authorization_code',
'redirect_uri': pending['redirect_uri']
}
resp = requests.post(token_endpoint, data=data)
if resp.status_code == 200:
tokens = resp.json()
# Save token
token_record = {
'client_id': pending['client_id'],
'client_secret': pending['client_secret'],
'token': tokens.get('access_token'),
'refresh_token': tokens.get('refresh_token'),
'token_uri': token_endpoint,
'scopes': pending['scopes']
}
with open('/workspace/personal/google_user_tokens.json', 'w') as f:
json.dump(token_record, f, indent=2)
print("TOKEN_SAVED_SUCCESS")
else:
print("Error exchanging token:", resp.status_code, resp.text)