當前位置: 首頁>>代碼示例>>Python>>正文


Python oauth2.service_account方法代碼示例

本文整理匯總了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")
            })
        ) 
開發者ID:rapid7,項目名稱:insightconnect-plugins,代碼行數:20,代碼來源:connection.py

示例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 
開發者ID:jupyterhub,項目名稱:oauthenticator,代碼行數:24,代碼來源:google.py

示例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 
開發者ID:demisto,項目名稱:content,代碼行數:23,代碼來源:GoogleCloudCompute.py

示例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 
開發者ID:ray-project,項目名稱:ray,代碼行數:26,代碼來源:config.py

示例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()
    ) 
開發者ID:snowflakedb,項目名稱:SnowAlert,代碼行數:19,代碼來源:gsuite_logs.py

示例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 
開發者ID:apache,項目名稱:airflow,代碼行數:14,代碼來源:base_google.py

示例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) 
開發者ID:rapid7,項目名稱:insightconnect-plugins,代碼行數:40,代碼來源:connection.py

示例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 
開發者ID:ray-project,項目名稱:ray,代碼行數:41,代碼來源:config.py

示例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 
開發者ID:ray-project,項目名稱:ray,代碼行數:15,代碼來源:config.py

示例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 
開發者ID:ray-project,項目名稱:ray,代碼行數:13,代碼來源:config.py

示例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 
開發者ID:ray-project,項目名稱:ray,代碼行數:40,代碼來源:config.py

示例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) 
開發者ID:firebase,項目名稱:firebase-admin-python,代碼行數:5,代碼來源:_token_gen.py

示例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) 
開發者ID:firebase,項目名稱:firebase-admin-python,代碼行數:28,代碼來源:_token_gen.py

示例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)) 
開發者ID:firebase,項目名稱:firebase-admin-python,代碼行數:36,代碼來源:credentials.py

示例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 
開發者ID:forseti-security,項目名稱:forseti-security,代碼行數:14,代碼來源:base_repository_test.py


注:本文中的google.oauth2.service_account方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。