|
18 | 18 | import base64 |
19 | 19 | import importlib |
20 | 20 | from abc import ABC, abstractmethod |
21 | | -from typing import Any, Dict, Optional, Type |
| 21 | +import logging |
| 22 | +from typing import Any, Dict, List, Optional, Type |
22 | 23 |
|
23 | 24 | from requests import HTTPError, PreparedRequest, Session |
24 | 25 | from requests.auth import AuthBase |
@@ -119,6 +120,38 @@ def auth_header(self) -> str: |
119 | 120 | return f"Bearer {self._token}" |
120 | 121 |
|
121 | 122 |
|
| 123 | +class GoogleAuthManager(AuthManager): |
| 124 | + """ |
| 125 | + An auth manager that is responsible for handling Google credentials. |
| 126 | + """ |
| 127 | + |
| 128 | + def __init__(self, credentials_path: Optional[str] = None, scopes: Optional[List[str]] = None): |
| 129 | + """ |
| 130 | + Initialize GoogleAuthManager. |
| 131 | +
|
| 132 | + Args: |
| 133 | + credentials_path: Optional path to Google credentials JSON file. |
| 134 | + scopes: Optional list of OAuth2 scopes. |
| 135 | + """ |
| 136 | + try: |
| 137 | + import google.auth |
| 138 | + import google.auth.transport.requests |
| 139 | + except ImportError as e: |
| 140 | + raise ImportError( |
| 141 | + "Google Auth libraries not found. Please install 'google-auth'." |
| 142 | + ) from e |
| 143 | + |
| 144 | + if credentials_path: |
| 145 | + self.credentials, _ = google.auth.load_credentials_from_file(credentials_path, scopes=scopes) |
| 146 | + else: |
| 147 | + logging.info("Using Google Default Application Credentials") |
| 148 | + self.credentials, _ = google.auth.default(scopes=scopes) |
| 149 | + self._auth_request = google.auth.transport.requests.Request() |
| 150 | + |
| 151 | + def auth_header(self) -> Optional[str]: |
| 152 | + self.credentials.refresh(self._auth_request) |
| 153 | + return f"Bearer {self.credentials.token}" |
| 154 | + |
122 | 155 | class AuthManagerAdapter(AuthBase): |
123 | 156 | """A `requests.auth.AuthBase` adapter that integrates an `AuthManager` into a `requests.Session` to automatically attach the appropriate Authorization header to every request. |
124 | 157 |
|
@@ -197,3 +230,4 @@ def create(cls, class_or_name: str, config: Dict[str, Any]) -> AuthManager: |
197 | 230 | AuthManagerFactory.register("noop", NoopAuthManager) |
198 | 231 | AuthManagerFactory.register("basic", BasicAuthManager) |
199 | 232 | AuthManagerFactory.register("legacyoauth2", LegacyOAuth2AuthManager) |
| 233 | +AuthManagerFactory.register("google", GoogleAuthManager) |
0 commit comments