Skip to content

chore(auth): Update Auth API to v2 #691

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 6, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions firebase_admin/_auth_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ def __init__(self, app, tenant_id=None):

credential = None
version_header = 'Python/Admin/{0}'.format(firebase_admin.__version__)
timeout = app.options.get('httpTimeout', _http_client.DEFAULT_TIMEOUT_SECONDS)
timeout = app.options.get(
'httpTimeout', _http_client.DEFAULT_TIMEOUT_SECONDS)
# Non-default endpoint URLs for emulator support are set in this dict later.
endpoint_urls = {}
self.emulated = False
Expand All @@ -48,9 +49,10 @@ def __init__(self, app, tenant_id=None):
# endpoint URLs to use the emulator. Additionally, use a fake credential.
emulator_host = _auth_utils.get_emulator_host()
if emulator_host:
base_url = 'http://{0}/identitytoolkit.googleapis.com'.format(emulator_host)
base_url = 'http://{0}/identitytoolkit.googleapis.com'.format(
emulator_host)
endpoint_urls['v1'] = base_url + '/v1'
endpoint_urls['v2beta1'] = base_url + '/v2beta1'
endpoint_urls['v2'] = base_url + '/v2'
credential = _utils.EmulatorAdminCredentials()
self.emulated = True
else:
Expand All @@ -67,7 +69,7 @@ def __init__(self, app, tenant_id=None):
self._user_manager = _user_mgt.UserManager(
http_client, app.project_id, tenant_id, url_override=endpoint_urls.get('v1'))
self._provider_manager = _auth_providers.ProviderConfigClient(
http_client, app.project_id, tenant_id, url_override=endpoint_urls.get('v2beta1'))
http_client, app.project_id, tenant_id, url_override=endpoint_urls.get('v2'))

@property
def tenant_id(self):
Expand Down Expand Up @@ -284,7 +286,7 @@ def download(page_token, max_results):
return self._user_manager.list_users(page_token, max_results)
return _user_mgt.ListUsersPage(download, page_token, max_results)

def create_user(self, **kwargs): # pylint: disable=differing-param-doc
def create_user(self, **kwargs): # pylint: disable=differing-param-doc
"""Creates a new user account with the specified properties.

Args:
Expand All @@ -311,7 +313,7 @@ def create_user(self, **kwargs): # pylint: disable=differing-param-doc
uid = self._user_manager.create_user(**kwargs)
return self.get_user(uid=uid)

def update_user(self, uid, **kwargs): # pylint: disable=differing-param-doc
def update_user(self, uid, **kwargs): # pylint: disable=differing-param-doc
"""Updates an existing user account with the specified properties.

Args:
Expand Down
62 changes: 41 additions & 21 deletions firebase_admin/_auth_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ def items(self):
class ProviderConfigClient:
"""Client for managing Auth provider configurations."""

PROVIDER_CONFIG_URL = 'https://identitytoolkit.googleapis.com/v2beta1'
PROVIDER_CONFIG_URL = 'https://identitytoolkit.googleapis.com/v2'

def __init__(self, http_client, project_id, tenant_id=None, url_override=None):
self.http_client = http_client
Expand All @@ -187,7 +187,8 @@ def __init__(self, http_client, project_id, tenant_id=None, url_override=None):

def get_oidc_provider_config(self, provider_id):
_validate_oidc_provider_id(provider_id)
body = self._make_request('get', '/oauthIdpConfigs/{0}'.format(provider_id))
body = self._make_request(
'get', '/oauthIdpConfigs/{0}'.format(provider_id))
return OIDCProviderConfig(body)

def create_oidc_provider_config(
Expand All @@ -200,7 +201,8 @@ def create_oidc_provider_config(
'issuer': _validate_url(issuer, 'issuer'),
}
if display_name is not None:
req['displayName'] = _auth_utils.validate_string(display_name, 'display_name')
req['displayName'] = _auth_utils.validate_string(
display_name, 'display_name')
if enabled is not None:
req['enabled'] = _auth_utils.validate_boolean(enabled, 'enabled')

Expand All @@ -214,12 +216,14 @@ def create_oidc_provider_config(
response_type['code'] = _auth_utils.validate_boolean(
code_response_type, 'code_response_type')
if code_response_type:
req['clientSecret'] = _validate_non_empty_string(client_secret, 'client_secret')
req['clientSecret'] = _validate_non_empty_string(
client_secret, 'client_secret')
if response_type:
req['responseType'] = response_type

params = 'oauthIdpConfigId={0}'.format(provider_id)
body = self._make_request('post', '/oauthIdpConfigs', json=req, params=params)
body = self._make_request(
'post', '/oauthIdpConfigs', json=req, params=params)
return OIDCProviderConfig(body)

def update_oidc_provider_config(
Expand All @@ -233,11 +237,13 @@ def update_oidc_provider_config(
if display_name == _user_mgt.DELETE_ATTRIBUTE:
req['displayName'] = None
else:
req['displayName'] = _auth_utils.validate_string(display_name, 'display_name')
req['displayName'] = _auth_utils.validate_string(
display_name, 'display_name')
if enabled is not None:
req['enabled'] = _auth_utils.validate_boolean(enabled, 'enabled')
if client_id:
req['clientId'] = _validate_non_empty_string(client_id, 'client_id')
req['clientId'] = _validate_non_empty_string(
client_id, 'client_id')
if issuer:
req['issuer'] = _validate_url(issuer, 'issuer')

Expand All @@ -251,12 +257,14 @@ def update_oidc_provider_config(
response_type['code'] = _auth_utils.validate_boolean(
code_response_type, 'code_response_type')
if code_response_type:
req['clientSecret'] = _validate_non_empty_string(client_secret, 'client_secret')
req['clientSecret'] = _validate_non_empty_string(
client_secret, 'client_secret')
if response_type:
req['responseType'] = response_type

if not req:
raise ValueError('At least one parameter must be specified for update.')
raise ValueError(
'At least one parameter must be specified for update.')

update_mask = _auth_utils.build_update_mask(req)
params = 'updateMask={0}'.format(','.join(update_mask))
Expand All @@ -266,7 +274,8 @@ def update_oidc_provider_config(

def delete_oidc_provider_config(self, provider_id):
_validate_oidc_provider_id(provider_id)
self._make_request('delete', '/oauthIdpConfigs/{0}'.format(provider_id))
self._make_request(
'delete', '/oauthIdpConfigs/{0}'.format(provider_id))

def list_oidc_provider_configs(self, page_token=None, max_results=MAX_LIST_CONFIGS_RESULTS):
return _ListOIDCProviderConfigsPage(
Expand All @@ -277,7 +286,8 @@ def _fetch_oidc_provider_configs(self, page_token=None, max_results=MAX_LIST_CON

def get_saml_provider_config(self, provider_id):
_validate_saml_provider_id(provider_id)
body = self._make_request('get', '/inboundSamlConfigs/{0}'.format(provider_id))
body = self._make_request(
'get', '/inboundSamlConfigs/{0}'.format(provider_id))
return SAMLProviderConfig(body)

def create_saml_provider_config(
Expand All @@ -297,12 +307,14 @@ def create_saml_provider_config(
},
}
if display_name is not None:
req['displayName'] = _auth_utils.validate_string(display_name, 'display_name')
req['displayName'] = _auth_utils.validate_string(
display_name, 'display_name')
if enabled is not None:
req['enabled'] = _auth_utils.validate_boolean(enabled, 'enabled')

params = 'inboundSamlConfigId={0}'.format(provider_id)
body = self._make_request('post', '/inboundSamlConfigs', json=req, params=params)
body = self._make_request(
'post', '/inboundSamlConfigs', json=req, params=params)
return SAMLProviderConfig(body)

def update_saml_provider_config(
Expand All @@ -312,24 +324,29 @@ def update_saml_provider_config(
_validate_saml_provider_id(provider_id)
idp_config = {}
if idp_entity_id is not None:
idp_config['idpEntityId'] = _validate_non_empty_string(idp_entity_id, 'idp_entity_id')
idp_config['idpEntityId'] = _validate_non_empty_string(
idp_entity_id, 'idp_entity_id')
if sso_url is not None:
idp_config['ssoUrl'] = _validate_url(sso_url, 'sso_url')
if x509_certificates is not None:
idp_config['idpCertificates'] = _validate_x509_certificates(x509_certificates)
idp_config['idpCertificates'] = _validate_x509_certificates(
x509_certificates)

sp_config = {}
if rp_entity_id is not None:
sp_config['spEntityId'] = _validate_non_empty_string(rp_entity_id, 'rp_entity_id')
sp_config['spEntityId'] = _validate_non_empty_string(
rp_entity_id, 'rp_entity_id')
if callback_url is not None:
sp_config['callbackUri'] = _validate_url(callback_url, 'callback_url')
sp_config['callbackUri'] = _validate_url(
callback_url, 'callback_url')

req = {}
if display_name is not None:
if display_name == _user_mgt.DELETE_ATTRIBUTE:
req['displayName'] = None
else:
req['displayName'] = _auth_utils.validate_string(display_name, 'display_name')
req['displayName'] = _auth_utils.validate_string(
display_name, 'display_name')
if enabled is not None:
req['enabled'] = _auth_utils.validate_boolean(enabled, 'enabled')
if idp_config:
Expand All @@ -338,7 +355,8 @@ def update_saml_provider_config(
req['spConfig'] = sp_config

if not req:
raise ValueError('At least one parameter must be specified for update.')
raise ValueError(
'At least one parameter must be specified for update.')

update_mask = _auth_utils.build_update_mask(req)
params = 'updateMask={0}'.format(','.join(update_mask))
Expand All @@ -348,7 +366,8 @@ def update_saml_provider_config(

def delete_saml_provider_config(self, provider_id):
_validate_saml_provider_id(provider_id)
self._make_request('delete', '/inboundSamlConfigs/{0}'.format(provider_id))
self._make_request(
'delete', '/inboundSamlConfigs/{0}'.format(provider_id))

def list_saml_provider_configs(self, page_token=None, max_results=MAX_LIST_CONFIGS_RESULTS):
return _ListSAMLProviderConfigsPage(
Expand Down Expand Up @@ -430,5 +449,6 @@ def _validate_x509_certificates(x509_certificates):
if not isinstance(x509_certificates, list) or not x509_certificates:
raise ValueError('x509_certificates must be a non-empty list.')
if not all([isinstance(cert, str) and cert for cert in x509_certificates]):
raise ValueError('x509_certificates must only contain non-empty strings.')
raise ValueError(
'x509_certificates must only contain non-empty strings.')
return [{'x509Certificate': cert} for cert in x509_certificates]
14 changes: 9 additions & 5 deletions firebase_admin/tenant_mgt.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ def list_tenants(page_token=None, max_results=_MAX_LIST_TENANTS_RESULTS, app=Non
FirebaseError: If an error occurs while retrieving the user accounts.
"""
tenant_mgt_service = _get_tenant_mgt_service(app)

def download(page_token, max_results):
return tenant_mgt_service.list_tenants(page_token, max_results)
return ListTenantsPage(download, page_token, max_results)
Expand All @@ -205,7 +206,8 @@ class Tenant:

def __init__(self, data):
if not isinstance(data, dict):
raise ValueError('Invalid data argument in Tenant constructor: {0}'.format(data))
raise ValueError(
'Invalid data argument in Tenant constructor: {0}'.format(data))
if not 'name' in data:
raise ValueError('Tenant response missing required keys.')

Expand All @@ -232,12 +234,13 @@ def enable_email_link_sign_in(self):
class _TenantManagementService:
"""Firebase tenant management service."""

TENANT_MGT_URL = 'https://identitytoolkit.googleapis.com/v2beta1'
TENANT_MGT_URL = 'https://identitytoolkit.googleapis.com/v2'

def __init__(self, app):
credential = app.credential.get_credential()
version_header = 'Python/Admin/{0}'.format(firebase_admin.__version__)
base_url = '{0}/projects/{1}'.format(self.TENANT_MGT_URL, app.project_id)
base_url = '{0}/projects/{1}'.format(
self.TENANT_MGT_URL, app.project_id)
self.app = app
self.client = _http_client.JsonHttpClient(
credential=credential, base_url=base_url, headers={'X-Client-Version': version_header})
Expand All @@ -256,7 +259,7 @@ def auth_for_tenant(self, tenant_id):

client = auth.Client(self.app, tenant_id=tenant_id)
self.tenant_clients[tenant_id] = client
return client
return client

def get_tenant(self, tenant_id):
"""Gets the tenant corresponding to the given ``tenant_id``."""
Expand Down Expand Up @@ -308,7 +311,8 @@ def update_tenant(
enable_email_link_sign_in, 'enableEmailLinkSignin')

if not payload:
raise ValueError('At least one parameter must be specified for update.')
raise ValueError(
'At least one parameter must be specified for update.')

url = '/tenants/{0}'.format(tenant_id)
update_mask = ','.join(_auth_utils.build_update_mask(payload))
Expand Down
Loading