Skip to content

Instantly share code, notes, and snippets.

@ekimekim
Created November 30, 2020 12:17
Show Gist options
  • Save ekimekim/c050acc5deee3b1f4d492d2176b3d4ad to your computer and use it in GitHub Desktop.
Save ekimekim/c050acc5deee3b1f4d492d2176b3d4ad to your computer and use it in GitHub Desktop.
from urllib import urlencode
import requests
import argh
def build_url(base, **kwargs):
return '{}?{}'.format(base, urlencode(kwargs))
@argh.arg('scopes', nargs='*')
def get_refresh_token(client_id, client_secret, scopes):
auth_url = build_url('https://accounts.google.com/o/oauth2/v2/auth',
scope=' '.join(scopes),
response_type='code',
redirect_uri='urn:ietf:wg:oauth:2.0:oob',
client_id=client_id,
)
print "Visit this URL:", auth_url
code = raw_input("Paste the code given: ")
resp = requests.post('https://www.googleapis.com/oauth2/v4/token', data={
'code': code,
'client_id': client_id,
'client_secret': client_secret,
'grant_type': 'authorization_code',
'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
})
resp.raise_for_status()
print "Refresh token:", resp.json()['refresh_token']
def get_access_token(client_id, client_secret, refresh_token):
resp = requests.post('https://www.googleapis.com/oauth2/v4/token', data={
'client_id': client_id,
'client_secret': client_secret,
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
})
resp.raise_for_status()
data = resp.json()
print 'Access token expires in {}s: {}'.format(data['expires_in'], data['access_token'])
if __name__ == '__main__':
argh.dispatch_commands([get_refresh_token, get_access_token])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment