|
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 |
@@ -109,6 +110,38 @@ def auth_header(self) -> str: |
109 | 110 | return f"Bearer {self._token}" |
110 | 111 |
|
111 | 112 |
|
| 113 | +class GoogleAuthManager(AuthManager): |
| 114 | + """ |
| 115 | + An auth manager that is responsible for handling Google credentials. |
| 116 | + """ |
| 117 | + |
| 118 | + def __init__(self, credentials_path: Optional[str] = None, scopes: Optional[List[str]] = None): |
| 119 | + """ |
| 120 | + Initialize GoogleAuthManager. |
| 121 | +
|
| 122 | + Args: |
| 123 | + credentials_path: Optional path to Google credentials JSON file. |
| 124 | + scopes: Optional list of OAuth2 scopes. |
| 125 | + """ |
| 126 | + try: |
| 127 | + import google.auth |
| 128 | + import google.auth.transport.requests |
| 129 | + except ImportError as e: |
| 130 | + raise ImportError( |
| 131 | + "Google Auth libraries not found. Please install 'google-auth'." |
| 132 | + ) from e |
| 133 | + |
| 134 | + if credentials_path: |
| 135 | + self.credentials, _ = google.auth.load_credentials_from_file(credentials_path, scopes=scopes) |
| 136 | + else: |
| 137 | + logging.info("Using Google Default Application Credentials") |
| 138 | + self.credentials, _ = google.auth.default(scopes=scopes) |
| 139 | + self._auth_request = google.auth.transport.requests.Request() |
| 140 | + |
| 141 | + def auth_header(self) -> Optional[str]: |
| 142 | + self.credentials.refresh(self._auth_request) |
| 143 | + return f"Bearer {self.credentials.token}" |
| 144 | + |
112 | 145 | class AuthManagerAdapter(AuthBase): |
113 | 146 | """A `requests.auth.AuthBase` adapter that integrates an `AuthManager` into a `requests.Session` to automatically attach the appropriate Authorization header to every request. |
114 | 147 |
|
@@ -187,3 +220,4 @@ def create(cls, class_or_name: str, config: Dict[str, Any]) -> AuthManager: |
187 | 220 | AuthManagerFactory.register("noop", NoopAuthManager) |
188 | 221 | AuthManagerFactory.register("basic", BasicAuthManager) |
189 | 222 | AuthManagerFactory.register("legacyoauth2", LegacyOAuth2AuthManager) |
| 223 | +AuthManagerFactory.register("google", GoogleAuthManager) |
0 commit comments