Skip to content

Commit 6837352

Browse files
committed
feat: add ImpersonatedCredentials to be used with impersonalized creds
1 parent 0d498a6 commit 6837352

File tree

1 file changed

+60
-3
lines changed

1 file changed

+60
-3
lines changed

firebase_admin/credentials.py

+60-3
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,9 @@
1818
import pathlib
1919

2020
import google.auth
21+
import google.auth.impersonated_credentials
2122
from google.auth.transport import requests
22-
from google.oauth2 import credentials
23-
from google.oauth2 import service_account
24-
23+
from google.oauth2 import credentials, service_account
2524

2625
_request = requests.Request()
2726
_scopes = [
@@ -215,6 +214,64 @@ def get_credential(self):
215214
return self._g_credential
216215

217216

217+
class ImpersonatedCredentials(Base):
218+
"""A credential initialized from a google.auth.impersonated_credentials.Credentials"""
219+
220+
def __init__(self, icreds: google.auth.impersonated_credentials.Credentials):
221+
"""Initializes a credential from a google.auth.impersonated_credentials.Credentials.
222+
223+
Args:
224+
icreds: A google.auth.impersonated_credentials.Credentials instance.
225+
226+
Raises:
227+
ValueError: If the impersonated credential is invalid.
228+
229+
Example:
230+
```python
231+
import google.auth
232+
import firebase_admin
233+
from firebase_admin.credentials import ImpersonatedCredentials
234+
235+
creds, project_id = google.auth.default(quota_project_id=PROJECT_ID_DEFAULT, scopes=_scopes,)
236+
logger.info(f"Obtained default credentials for the project {project_id}")
237+
fullname_service_account = (
238+
f"{service_account_name_filtered}@{project_id}.iam.gserviceaccount.com"
239+
)
240+
logger.info(
241+
f"Obtained impersonated credentials for the service account {fullname_service_account}",
242+
)
243+
244+
icreds = google.auth.impersonated_credentials.Credentials(
245+
source_credentials=creds,
246+
target_principal=fullname_service_account,
247+
target_scopes=_scopes,
248+
)
249+
250+
impersonated_creds = ImpersonatedCredentials(icreds)
251+
252+
app = firebase_admin.initialize_app(impersonated_creds, name=name_firebase)
253+
```
254+
"""
255+
if not isinstance(icreds, google.auth.impersonated_credentials.Credentials):
256+
raise ValueError(
257+
"Invalid impersonated credentials. Credentials must be an instance of "
258+
"google.auth.impersonated_credentials.Credentials"
259+
)
260+
super(ImpersonatedCredentials, self).__init__()
261+
self._g_credential = icreds
262+
263+
def get_credential(self):
264+
"""Returns the underlying Google credential.
265+
266+
Returns:
267+
google.auth.credentials.Credentials: A Google Auth credential instance."""
268+
return self._g_credential
269+
270+
@property
271+
def service_account_email(self):
272+
return self._g_credential.service_account_email
273+
274+
218275
def _is_file_path(path):
219276
try:
220277
pathlib.Path(path)

0 commit comments

Comments
 (0)