From 33313105a9a215719b7cf0a9122db03b7ee965c0 Mon Sep 17 00:00:00 2001 From: dfguerrerom Date: Thu, 25 Apr 2024 17:46:59 +0200 Subject: [PATCH] refactor: identify if credentials are from gsa --- sepal_ui/scripts/decorator.py | 13 ++++++++++--- sepal_ui/scripts/utils.py | 14 ++++++++++---- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/sepal_ui/scripts/decorator.py b/sepal_ui/scripts/decorator.py index cf9deceb..db15fe15 100644 --- a/sepal_ui/scripts/decorator.py +++ b/sepal_ui/scripts/decorator.py @@ -60,9 +60,9 @@ def init_ee() -> None: # Extract the project name from credentials _credentials = json.loads(credential_file_path.read_text()) - project_id = os.environ.get( - "EARTHENGINE_PROJECT", - _credentials.get("project_id", _credentials.get("project", None)), + project_id = os.environ.get("EARTHENGINE_PROJECT", None) + project_id = project_id or _credentials.get( + "project_id", _credentials.get("project", None) ) if not project_id: @@ -71,6 +71,13 @@ def init_ee() -> None: "Please set the EARTHENGINE_PROJECT environment variable. " "Or authenticate using `earthengine set_project project_name`." ) + # Check if we are using a google service account + if _credentials.get("type") == "service_account": + ee_user = _credentials.get("client_email") + credentials = ee.ServiceAccountCredentials( + ee_user, str(credential_file_path) + ) + ee.Initialize(credentials=credentials, http_transport=httplib2.Http()) # if the user is in local development the authentication should # already be available diff --git a/sepal_ui/scripts/utils.py b/sepal_ui/scripts/utils.py index e6690cdf..0848248f 100644 --- a/sepal_ui/scripts/utils.py +++ b/sepal_ui/scripts/utils.py @@ -153,9 +153,9 @@ def init_ee() -> None: # Extract the project name from credentials _credentials = json.loads(credential_file_path.read_text()) - project_id = os.environ.get( - "EARTHENGINE_PROJECT", - _credentials.get("project_id", _credentials.get("project", None)), + project_id = os.environ.get("EARTHENGINE_PROJECT", None) + project_id = project_id or _credentials.get( + "project_id", _credentials.get("project", None) ) if not project_id: @@ -164,7 +164,13 @@ def init_ee() -> None: "Please set the EARTHENGINE_PROJECT environment variable. " "Or authenticate using `earthengine set_project project_name`." ) - + # Check if we are using a google service account + if _credentials.get("type") == "service_account": + ee_user = _credentials.get("client_email") + credentials = ee.ServiceAccountCredentials( + ee_user, str(credential_file_path) + ) + ee.Initialize(credentials=credentials, http_transport=httplib2.Http()) # if the user is in local development the authentication should # already be available ee.Initialize(project=project_id, http_transport=httplib2.Http())