コード例 #1
0
def ShouldContinueLogin(cred_config):
    """Prompts users if they try to login in managed environments.

  Args:
    cred_config: Json object loaded from the file specified in --cred-file.

  Returns:
    True if users want to continue the login command.
  """
    if c_devshell.IsDevshellEnvironment():
        message = textwrap.dedent("""
          You are already authenticated with gcloud when running
          inside the Cloud Shell and so do not need to run this
          command. Do you wish to proceed anyway?
          """)
        return console_io.PromptContinue(message=message)
    elif (c_gce.Metadata().connected
          and not auth_external_account.IsExternalAccountConfig(cred_config)):
        message = textwrap.dedent("""
          You are running on a Google Compute Engine virtual machine.
          It is recommended that you use service accounts for authentication.

          You can run:

            $ gcloud config set account `ACCOUNT`

          to switch accounts if necessary.

          Your credentials may be visible to others with access to this
          virtual machine. Are you sure you want to authenticate with
          your personal account?
          """)
        return console_io.PromptContinue(message=message)
    else:
        return True
コード例 #2
0
ファイル: creds.py プロジェクト: piotradamczyk5/gcloud_cli
def _IsUserAccountCredentialsOauth2client(creds):
    if CredentialType.FromCredentials(creds).is_user:
        return True
    if c_devshell.IsDevshellEnvironment():
        return CredentialType.FromCredentials(creds) == CredentialType.GCE
    else:
        return False
コード例 #3
0
  def Run(self, args):
    """Run the authentication command."""

    if c_devshell.IsDevshellEnvironment():
      message = """
          You are already authenticated with gcloud when running
          inside the Cloud Shell and so do not need to run this
          command.

          Do you wish to proceed anyway?
        """
      answer = console_io.PromptContinue(message=message)
      if not answer:
        return None
    elif c_gce.Metadata().connected:
      message = textwrap.dedent("""
          You are running on a Google Compute Engine virtual machine.
          It is recommended that you use service accounts for authentication.

          You can run:

            $ gcloud config set account ``ACCOUNT''

          to switch accounts if necessary.

          Your credentials may be visible to others with access to this
          virtual machine. Are you sure you want to authenticate with
          your personal account?
          """)
      answer = console_io.PromptContinue(message=message)
      if not answer:
        return None

    account = args.account

    if account and not args.force:
      creds = c_store.LoadIfValid(account=account)
      if creds:
        # Account already has valid creds, just switch to it.
        return self.LoginAs(account, creds, args.project, args.activate,
                            args.brief)

    # No valid creds, do the web flow.
    launch_browser = auth_util.ShouldLaunchBrowser(args.launch_browser)
    creds = self.DoInstalledAppBrowserFlow(launch_browser)
    web_flow_account = creds.id_token['email']
    if account and account.lower() != web_flow_account.lower():
      raise c_exc.ToolException(
          'You attempted to log in as account [{account}] but the received '
          'credentials were for account [{web_flow_account}].\n\n'
          'Please check that your browser is logged in as account [{account}] '
          'and that you are using the correct browser profile.'.format(
              account=account, web_flow_account=web_flow_account))

    account = web_flow_account
    # We got new creds, and they are for the correct user.
    c_store.Store(creds, account)
    return self.LoginAs(account, creds, args.project, args.activate,
                        args.brief)
コード例 #4
0
ファイル: creds.py プロジェクト: piotradamczyk5/gcloud_cli
def _IsUserAccountCredentialsGoogleAuth(creds):
    if CredentialTypeGoogleAuth.FromCredentials(creds).is_user:
        return True
    if c_devshell.IsDevshellEnvironment():
        return CredentialTypeGoogleAuth.FromCredentials(
            creds) == CredentialTypeGoogleAuth.GCE
    else:
        return False
コード例 #5
0
def OpenURL(url):
    """Open a URL in the default web browser in a new tab.

  Args:
    url: The full HTTP(S) URL to open.
  """
    # Import in here for performance reasons
    # pylint: disable=g-import-not-at-top
    import webbrowser
    # Devshell has its own 'browser' handler which simply prints the URL; this is
    # redundant
    if not devshell.IsDevshellEnvironment():
        log.status.Print(
            'Opening [{0}] in a new tab in your default browser.'.format(url))
    webbrowser.open_new_tab(url)
コード例 #6
0
def _ShouldCheckSurveyPrompt(command_path):
  """Decides if survey prompt should be checked."""
  if properties.VALUES.survey.disable_prompts.GetBool():
    return False
  # dev shell environment uses temporary folder for user config. That means
  # survey prompt cache gets cleaned each time user starts a new session,
  # which results in too frequent prompting.
  if c_devshell.IsDevshellEnvironment():
    return False

  exempt_commands = ['gcloud.components.post-process',]
  for exempt_command in exempt_commands:
    if command_path.startswith(exempt_command):
      return False

  return True
コード例 #7
0
def GetMetricsEnvironment():
    """Get the metrics environment.

  Returns the property metrics/environment if set, if not, it tries to deduce if
  we're on some known platforms like devshell or GCE.

  Returns:
    None, if no environment is set or found
    str, a string denoting the environment if one is set or found
  """

    environment = VALUES.metrics.environment.Get()
    if environment:
        return environment

    # No explicit environment defined, try to deduce it.
    if c_devshell.IsDevshellEnvironment():
        return 'devshell'
    if gce_cache.GetOnGCE(check_age=False):
        return 'GCE'

    return None
コード例 #8
0
ファイル: login.py プロジェクト: Guliux10/bchacks_deepbreath
    def Run(self, args):
        """Run the authentication command."""

        scopes = config.CLOUDSDK_SCOPES
        # Add REAUTH scope in case the user has 2fact activated.
        # This scope is only used here and when refreshing the access token.
        scopes += (config.REAUTH_SCOPE, )

        if args.enable_gdrive_access:
            scopes += (auth_util.GOOGLE_DRIVE_SCOPE, )

        if c_devshell.IsDevshellEnvironment():
            if c_devshell.HasDevshellAuth():
                message = textwrap.dedent("""
            You are already authenticated with gcloud when running
            inside the Cloud Shell and so do not need to run this
            command. Do you wish to proceed anyway?
            """)
                answer = console_io.PromptContinue(message=message)
                if not answer:
                    return None
        elif c_gce.Metadata().connected:
            message = textwrap.dedent("""
          You are running on a Google Compute Engine virtual machine.
          It is recommended that you use service accounts for authentication.

          You can run:

            $ gcloud config set account `ACCOUNT`

          to switch accounts if necessary.

          Your credentials may be visible to others with access to this
          virtual machine. Are you sure you want to authenticate with
          your personal account?
          """)
            answer = console_io.PromptContinue(message=message)
            if not answer:
                return None

        account = args.account

        if account and not args.force:
            try:
                creds = c_store.Load(account=account, scopes=scopes)
            except c_store.Error:
                creds = None
            if creds:
                # Account already has valid creds, just switch to it.
                log.warning(
                    'Re-using locally stored credentials for [{}]. '
                    'To fetch new credentials, re-run the command with the '
                    '`--force` flag.'.format(account))
                return LoginAs(account, creds, args.project, args.activate,
                               args.brief, args.update_adc)

        # No valid creds, do the web flow.
        launch_browser = check_browser.ShouldLaunchBrowser(args.launch_browser)
        creds = auth_util.DoInstalledAppBrowserFlow(launch_browser, scopes)
        web_flow_account = creds.id_token['email']
        if account and account.lower() != web_flow_account.lower():
            raise auth_exceptions.WrongAccountError(
                'You attempted to log in as account [{account}] but the received '
                'credentials were for account [{web_flow_account}].\n\n'
                'Please check that your browser is logged in as account [{account}] '
                'and that you are using the correct browser profile.'.format(
                    account=account, web_flow_account=web_flow_account))

        account = web_flow_account
        # We got new creds, and they are for the correct user.
        c_store.Store(creds, account, scopes)
        return LoginAs(account, creds, args.project, args.activate, args.brief,
                       args.update_adc)