本文整理汇总了Python中google.oauth2.service_account方法的典型用法代码示例。如果您正苦于以下问题:Python oauth2.service_account方法的具体用法?Python oauth2.service_account怎么用?Python oauth2.service_account使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类google.oauth2
的用法示例。
在下文中一共展示了oauth2.service_account方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: connect
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def connect(self, params):
self.logger.info(f"Connect: Connecting...")
self.client = bigquery.Client(
project=params.get(Input.PROJECT_ID),
credentials=service_account.Credentials.from_service_account_info({
"type": "service_account",
"project_id": params.get(Input.PROJECT_ID),
"private_key_id": params.get(Input.PRIVATE_KEY_ID),
"private_key": params.get(Input.PRIVATE_KEY).get("privateKey").replace('\\n', "\n", -1),
"client_email": params.get(Input.CLIENT_EMAIL),
"client_id": params.get(Input.CLIENT_ID),
"auth_uri": params.get(Input.AUTH_URI),
"client_x509_cert_url": params.get(Input.CLIENT_X509_CERT_URL),
"token_uri": params.get(Input.TOKEN_URI, "https://oauth2.googleapis.com/token"),
"auth_provider_x509_cert_url": params.get(Input.AUTH_PROVIDER_X509_CERT_URL,
"https://www.googleapis.com/oauth2/v1/certs")
})
)
示例2: _service_client_credentials
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def _service_client_credentials(self, scopes, user_email_domain):
"""
Return a configured service client credentials for the API.
"""
try:
from google.oauth2 import service_account
except:
raise ImportError(
"Could not import google.oauth2's service_account,"
"you may need to run pip install oauthenticator[googlegroups] or not declare google groups"
)
gsuite_administrator_email = "{}@{}".format(self.gsuite_administrator[user_email_domain], user_email_domain)
self.log.debug("scopes are %s, user_email_domain is %s", scopes, user_email_domain)
credentials = service_account.Credentials.from_service_account_file(
self.google_service_account_keys[user_email_domain],
scopes=scopes
)
credentials = credentials.with_subject(gsuite_administrator_email)
return credentials
示例3: build_and_authenticate
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def build_and_authenticate(googleservice):
"""
Return a service object via which can call GRM API.
Use the service_account credential file generated in the Google Cloud
Platform to build the Google Resource Manager API Service object.
returns: service
Google Resource Manager API Service object via which commands in the
integration will make API calls
"""
global SERVICE_ACT_PROJECT_ID, COMPUTE
auth_json_string = str(SERVICE_ACCOUNT_FILE).replace("\'", "\"").replace("\\\\", "\\")
service_account_info = json.loads(auth_json_string)
SERVICE_ACT_PROJECT_ID = service_account_info.get('project_id')
service_credentials = service_account.Credentials.from_service_account_info(
service_account_info, scopes=SCOPE
)
COMPUTE = discovery.build(googleservice, API_VERSION, credentials=service_credentials)
return COMPUTE
示例4: fetch_gcp_credentials_from_provider_config
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def fetch_gcp_credentials_from_provider_config(provider_config):
"""
Attempt to fetch and parse the JSON GCP credentials from the provider
config yaml file.
"""
service_account_info_string = provider_config.get("gcp_credentials")
if service_account_info_string is None:
logger.info("gcp_credentials not found in cluster yaml file. "
"Falling back to GOOGLE_APPLICATION_CREDENTIALS "
"environment variable.")
# If gcp_credentials is None, then discovery.build will search for
# credentials in the local environment.
return None
# If parsing the gcp_credentials failed, then the user likely made a
# mistake in copying the credentials into the config yaml.
try:
service_account_info = json.loads(service_account_info_string)
except json.decoder.JSONDecodeError:
raise RuntimeError("gcp_credentials found in cluster yaml file but "
"formatted improperly.")
gcp_credentials = service_account.Credentials.from_service_account_info(
service_account_info)
return gcp_credentials
示例5: get_logs
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def get_logs(service_account_info, with_subject=None, event_name='', start_time=None):
creds = service_account.Credentials.from_service_account_info(service_account_info)
if with_subject is not None:
creds = creds.with_subject(with_subject).with_scopes(SCOPES)
service = build('admin', version='reports_v1', credentials=creds)
return (
service.activities()
.list(
userKey='all',
applicationName='login',
eventName=event_name,
startTime=start_time and start_time.isoformat(),
)
.execute()
)
示例6: _get_field
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def _get_field(self, f: str, default: Any = None) -> Any:
"""
Fetches a field from extras, and returns it. This is some Airflow
magic. The google_cloud_platform hook type adds custom UI elements
to the hook page, which allow admins to specify service_account,
key_path, etc. They get formatted as shown below.
"""
long_f = 'extra__google_cloud_platform__{}'.format(f)
if hasattr(self, 'extras') and long_f in self.extras:
return self.extras[long_f]
else:
return default
示例7: connect
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def connect(self, params):
admin_user = params.get('admin_user')
private_key = params.get('private_key').get('privateKey')
auth = params
auth['private_key'] = private_key
auth['type'] = 'service_account'
del auth['admin_user']
self.project = auth['project_id']
scopes = ['https://www.googleapis.com/auth/drive']
if admin_user:
self.logger.info("Connecting to {email} as {admin}".format(email=auth['client_email'],
admin=admin_user))
else:
self.logger.info("Connection to {} as service account".format(auth['client_email']))
# Fix escaping issues in private_key
if '\\n' in auth['private_key']:
auth['private_key'] = auth['private_key'].replace('\\n', "\n", -1)
# Build a Google credentials object
if admin_user:
try:
credentials = service_account.Credentials.from_service_account_info(auth,
scopes=scopes,
subject=admin_user)
except ValueError as e:
raise e
else:
try:
credentials = service_account.Credentials.from_service_account_info(auth, scopes=scopes)
except ValueError:
raise ConnectionTestException.Preset.API_KEY
self.google_client = gspread.Client(auth=credentials)
self.google_client.session = AuthorizedSession(credentials)
示例8: _configure_iam_role
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def _configure_iam_role(config, crm, iam):
"""Setup a gcp service account with IAM roles.
Creates a gcp service acconut and binds IAM roles which allow it to control
control storage/compute services. Specifically, the head node needs to have
an IAM role that allows it to create further gce instances and store items
in google cloud storage.
TODO: Allow the name/id of the service account to be configured
"""
email = SERVICE_ACCOUNT_EMAIL_TEMPLATE.format(
account_id=DEFAULT_SERVICE_ACCOUNT_ID,
project_id=config["provider"]["project_id"])
service_account = _get_service_account(email, config, iam)
if service_account is None:
logger.info("_configure_iam_role: "
"Creating new service account {}".format(
DEFAULT_SERVICE_ACCOUNT_ID))
service_account = _create_service_account(
DEFAULT_SERVICE_ACCOUNT_ID, DEFAULT_SERVICE_ACCOUNT_CONFIG, config,
iam)
assert service_account is not None, "Failed to create service account"
_add_iam_policy_binding(service_account, DEFAULT_SERVICE_ACCOUNT_ROLES,
crm)
config["head_node"]["serviceAccounts"] = [{
"email": service_account["email"],
# NOTE: The amount of access is determined by the scope + IAM
# role of the service account. Even if the cloud-platform scope
# gives (scope) access to the whole cloud-platform, the service
# account is limited by the IAM rights specified below.
"scopes": ["https://www.googleapis.com/auth/cloud-platform"]
}]
return config
示例9: _get_service_account
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def _get_service_account(account, config, iam):
project_id = config["provider"]["project_id"]
full_name = ("projects/{project_id}/serviceAccounts/{account}"
"".format(project_id=project_id, account=account))
try:
service_account = iam.projects().serviceAccounts().get(
name=full_name).execute()
except errors.HttpError as e:
if e.resp.status != 404:
raise
service_account = None
return service_account
示例10: _create_service_account
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def _create_service_account(account_id, account_config, config, iam):
project_id = config["provider"]["project_id"]
service_account = iam.projects().serviceAccounts().create(
name="projects/{project_id}".format(project_id=project_id),
body={
"accountId": account_id,
"serviceAccount": account_config,
}).execute()
return service_account
示例11: _add_iam_policy_binding
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def _add_iam_policy_binding(service_account, roles, crm):
"""Add new IAM roles for the service account."""
project_id = service_account["projectId"]
email = service_account["email"]
member_id = "serviceAccount:" + email
policy = crm.projects().getIamPolicy(
resource=project_id, body={}).execute()
already_configured = True
for role in roles:
role_exists = False
for binding in policy["bindings"]:
if binding["role"] == role:
if member_id not in binding["members"]:
binding["members"].append(member_id)
already_configured = False
role_exists = True
if not role_exists:
already_configured = False
policy["bindings"].append({
"members": [member_id],
"role": role,
})
if already_configured:
# In some managed environments, an admin needs to grant the
# roles, so only call setIamPolicy if needed.
return
result = crm.projects().setIamPolicy(
resource=project_id, body={
"policy": policy,
}).execute()
return result
示例12: from_iam
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def from_iam(cls, request, google_cred, service_account):
signer = iam.Signer(request, google_cred, service_account)
return _SigningProvider(signer, service_account)
示例13: _init_signing_provider
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def _init_signing_provider(self):
"""Initializes a signing provider by following the go/firebase-admin-sign protocol."""
# If the SDK was initialized with a service account, use it to sign bytes.
google_cred = self.app.credential.get_credential()
if isinstance(google_cred, google.oauth2.service_account.Credentials):
return _SigningProvider.from_credential(google_cred)
# If the SDK was initialized with a service account email, use it with the IAM service
# to sign bytes.
service_account = self.app.options.get('serviceAccountId')
if service_account:
return _SigningProvider.from_iam(self.request, google_cred, service_account)
# If the SDK was initialized with some other credential type that supports signing
# (e.g. GAE credentials), use it to sign bytes.
if isinstance(google_cred, credentials.Signing):
return _SigningProvider.from_credential(google_cred)
# Attempt to discover a service account email from the local Metadata service. Use it
# with the IAM service to sign bytes.
resp = self.request(url=METADATA_SERVICE_URL, headers={'Metadata-Flavor': 'Google'})
if resp.status != 200:
raise ValueError(
'Failed to contact the local metadata service: {0}.'.format(resp.data.decode()))
service_account = resp.data.decode()
return _SigningProvider.from_iam(self.request, google_cred, service_account)
示例14: __init__
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def __init__(self, cert):
"""Initializes a credential from a Google service account certificate.
Service account certificates can be downloaded as JSON files from the Firebase console.
To instantiate a credential from a certificate file, either specify the file path or a
dict representing the parsed contents of the file.
Args:
cert: Path to a certificate file or a dict representing the contents of a certificate.
Raises:
IOError: If the specified certificate file doesn't exist or cannot be read.
ValueError: If the specified certificate is invalid.
"""
super(Certificate, self).__init__()
if isinstance(cert, str):
with open(cert) as json_file:
json_data = json.load(json_file)
elif isinstance(cert, dict):
json_data = cert
else:
raise ValueError(
'Invalid certificate argument: "{0}". Certificate argument must be a file path, '
'or a dict containing the parsed file contents.'.format(cert))
if json_data.get('type') != self._CREDENTIAL_TYPE:
raise ValueError('Invalid service account certificate. Certificate must contain a '
'"type" field set to "{0}".'.format(self._CREDENTIAL_TYPE))
try:
self._g_credential = service_account.Credentials.from_service_account_info(
json_data, scopes=_scopes)
except ValueError as error:
raise ValueError('Failed to initialize a certificate credential. '
'Caused by: "{0}"'.format(error))
示例15: get_test_service_account
# 需要导入模块: from google import oauth2 [as 别名]
# 或者: from google.oauth2 import service_account [as 别名]
def get_test_service_account(self, mock_signer):
keyfile_dict = {
'type': 'service_account',
'client_email': 'test@service.account',
'private_key': '12345',
'private_key_id': '12345',
'client_id': '123',
'token_uri': 'https://example.com/oauth2/token'}
creds = (
service_account.Credentials.from_service_account_info(
keyfile_dict))
return creds