Skip to content

Commit

Permalink
Read access_token from credentials file if present.
Browse files Browse the repository at this point in the history
  • Loading branch information
cdanielw committed Nov 24, 2022
1 parent e308d8c commit 239d092
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
8 changes: 7 additions & 1 deletion python/ee/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from . import ee_exception

from google.oauth2.credentials import Credentials
from .oauth import AccessTokenCredentials

# OAuth2 credentials object. This may be set by ee.Initialize().
_credentials = None
Expand Down Expand Up @@ -218,7 +219,12 @@ def get_persistent_credentials():
OAuth2Credentials built from persistently stored refresh_token
"""
try:
return Credentials(None, **oauth.get_credentials_arguments())
credentials = json.load(open(oauth.get_credentials_path()))
access_token = credentials.get('access_token')
if access_token:
return AccessTokenCredentials()
else:
return Credentials(None, **oauth.get_credentials_arguments())
except IOError:
raise ee_exception.EEException(
'Please authorize access to your Earth Engine account by '
Expand Down
28 changes: 28 additions & 0 deletions python/ee/oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import webbrowser

from google.auth import _cloud_sdk
from google.oauth2.credentials import Credentials

import six
from six.moves import input
from six.moves.urllib import parse
Expand Down Expand Up @@ -463,3 +465,29 @@ def display_instructions(self, quiet=None):
else:
_display_auth_instructions_with_print(self.auth_url, coda)
return True

class AccessTokenCredentials(Credentials):
def __init__(self, credentials_path=get_credentials_path()):
self.credentials_path = credentials_path
super(AccessTokenCredentials, self).__init__(self._read_access_token(credentials_path))

@staticmethod
def create(credentials_path=get_credentials_path()):
if os.path.exists(credentials_path) and AccessTokenCredentials._read_access_token(credentials_path):
return AccessTokenCredentials(credentials_path)
else:
return None
@staticmethod
def _read_access_token(credentials_path):
for i in range(5):
try:
return json.load(open(credentials_path)).get('access_token')
except:
sleep(5)

def refresh(self, request):
self.token = self._read_access_token(self.credentials_path)

def __str__(self):
return 'AccessTokenCredentials({})'.format(get_credentials_path())

0 comments on commit 239d092

Please sign in to comment.