Spaces:
Sleeping
Sleeping
File size: 1,735 Bytes
270c4f4 e0ee8f7 270c4f4 e0ee8f7 270c4f4 e0ee8f7 270c4f4 e0ee8f7 270c4f4 e0ee8f7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import json
import os
import logging
from typing import Optional
import google.auth
import google.auth.credentials
from google.oauth2 import service_account
logger = logging.getLogger(__name__)
_SCOPES = ["https://www.googleapis.com/auth/cloud-platform"]
def get_google_credentials() -> google.auth.credentials.Credentials:
"""
Resolution order:
1. GOOGLE_CREDENTIALS_JSON env var (raw JSON string) → service account info
2. GOOGLE_APPLICATION_CREDENTIALS env var set & file exists → service account file
3. Fallback → ADC (gcloud auth application-default login)
"""
creds_json: Optional[str] = os.environ.get("GOOGLE_CREDENTIALS_JSON")
if creds_json:
logger.info("Google auth: service account dari GOOGLE_CREDENTIALS_JSON")
# Value may be raw JSON or base64-encoded JSON
try:
import base64
decoded = base64.b64decode(creds_json).decode("utf-8")
info = json.loads(decoded)
except Exception:
info = json.loads(creds_json)
return service_account.Credentials.from_service_account_info(info, scopes=_SCOPES)
creds_path: Optional[str] = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
if creds_path:
if not os.path.isfile(creds_path):
raise FileNotFoundError(
f"GOOGLE_APPLICATION_CREDENTIALS='{creds_path}' tapi file tidak ditemukan."
)
logger.info("Google auth: service account dari %s", creds_path)
return service_account.Credentials.from_service_account_file(creds_path, scopes=_SCOPES)
logger.info("Google auth: menggunakan ADC (gcloud login)")
credentials, _ = google.auth.default(scopes=_SCOPES)
return credentials
|