Spaces:
Sleeping
Sleeping
Create authenticate.py
Browse files- authenticate.py +62 -0
authenticate.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from google.oauth2 import service_account
|
| 2 |
+
from google.auth.transport.requests import Request
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def get_access_token():
|
| 10 |
+
# Load service account credentials from JSON file or environment variable
|
| 11 |
+
credentials = service_account.Credentials.from_service_account_info(
|
| 12 |
+
json.loads(os.getenv('ACCOUNT_CREDS')),
|
| 13 |
+
scopes=['https://www.googleapis.com/auth/cloud-platform']
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# Refresh token if needed
|
| 17 |
+
if credentials.expired:
|
| 18 |
+
credentials.refresh(Request())
|
| 19 |
+
|
| 20 |
+
return credentials.token
|
| 21 |
+
|
| 22 |
+
def get_access_token_v1():
|
| 23 |
+
"""
|
| 24 |
+
Generate a Google Cloud access token from service account credentials.
|
| 25 |
+
Returns the access token string or raises an exception if failed.
|
| 26 |
+
"""
|
| 27 |
+
try:
|
| 28 |
+
# Set up logging
|
| 29 |
+
logging.basicConfig(level=logging.INFO)
|
| 30 |
+
logger = logging.getLogger(__name__)
|
| 31 |
+
|
| 32 |
+
# Get credentials from environment variable
|
| 33 |
+
creds_json = os.getenv('ACCOUNT_CREDS')
|
| 34 |
+
if not creds_json:
|
| 35 |
+
raise ValueError("ACCOUNT_CREDS environment variable not found")
|
| 36 |
+
|
| 37 |
+
# Parse credentials JSON
|
| 38 |
+
try:
|
| 39 |
+
creds_dict = json.loads(creds_json)
|
| 40 |
+
except json.JSONDecodeError:
|
| 41 |
+
raise ValueError("Invalid JSON in ACCOUNT_CREDS")
|
| 42 |
+
|
| 43 |
+
# Create credentials object
|
| 44 |
+
credentials = service_account.Credentials.from_service_account_info(
|
| 45 |
+
creds_dict,
|
| 46 |
+
scopes=['https://www.googleapis.com/auth/cloud-platform']
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# Ensure token is valid and refresh if needed
|
| 50 |
+
if not credentials.valid:
|
| 51 |
+
logger.info("Token expired or invalid, refreshing...")
|
| 52 |
+
credentials.refresh(Request())
|
| 53 |
+
|
| 54 |
+
if not credentials.token:
|
| 55 |
+
raise ValueError("No token generated after refresh")
|
| 56 |
+
|
| 57 |
+
logger.info("Successfully generated access token")
|
| 58 |
+
return credentials.token
|
| 59 |
+
|
| 60 |
+
except Exception as e:
|
| 61 |
+
logger.error(f"Error generating access token: {str(e)}")
|
| 62 |
+
raise
|