def Run(self, args): """List the account for known credentials.""" accounts = c_store.AvailableAccounts() active_account = properties.VALUES.core.account.Get() if args.account: # TODO(user) Remove error after Sept. 13, 2015. raise exceptions.Error( 'The behavior of ``gcloud auth list --account has changed. ' 'Please use ``--filter-account' ' to filter the output of ' '``auth list' '. Elsewhere in gcloud ``--account' ' sets the ' 'currently active account and this behavior will become available ' 'to ``auth list' ' in a future gcloud release.') if args.filter_account: if args.filter_account in accounts: accounts = [args.filter_account] else: accounts = [] auth_info = collections.namedtuple('auth_info', ['active_account', 'accounts']) return auth_info(active_account, accounts)
def AllAccounts(): """The resource list return value for the auth command Run() method.""" active_account = properties.VALUES.core.account.Get() return [ _AcctInfo(account, account == active_account) for account in c_store.AvailableAccounts() ]
def Run(self, args): """Revoke credentials and update active account.""" accounts = args.accounts or [] if type(accounts) is str: accounts = [accounts] available_accounts = c_store.AvailableAccounts() unknown_accounts = set(accounts) - set(available_accounts) if unknown_accounts: raise c_exc.UnknownArgumentException( 'accounts', ' '.join(unknown_accounts)) if args.all: accounts = available_accounts active_account = properties.VALUES.core.account.Get() if not accounts and active_account: accounts = [active_account] if not accounts: raise c_exc.InvalidArgumentException( 'accounts', 'No credentials available to revoke.') for account in accounts: if active_account == account: properties.PersistProperty(properties.VALUES.core.account, None) if not c_store.Revoke(account): log.warning( '[{}] already inactive (previously revoked?)'.format(account)) return accounts
def testStoreLoadDevShellCredentialsGoogleAuth(self): creds = c_store.Load(use_google_auth=True) self.assertIsInstance(creds, devshell.DevShellCredentialsGoogleAuth) self.assertEqual(creds.token, 'sometoken') self.assertGreater(creds.expiry, datetime.datetime.utcnow()) self.assertLess( creds.expiry, datetime.datetime.utcnow() + datetime.timedelta(seconds=1800)) accounts = c_store.AvailableAccounts() self.assertIn('*****@*****.**', accounts)
def testStore(self): creds = c_store.Load() self.assertIsInstance(creds, devshell.DevshellCredentials) self.assertEqual(creds.access_token, 'sometoken') self.assertGreater(creds.token_expiry, datetime.datetime.utcnow()) self.assertLess( creds.token_expiry, datetime.datetime.utcnow() + datetime.timedelta(seconds=1800)) accounts = c_store.AvailableAccounts() self.assertIn('*****@*****.**', accounts)
def Run(self, args): accounts = c_store.AvailableAccounts() active_account = properties.VALUES.core.account.Get() if args.filter_account: if args.filter_account in accounts: accounts = [args.filter_account] else: accounts = [] return auth_util.AuthResults(accounts, active_account)
def Run(self, args): """List the account for known credentials.""" accounts = c_store.AvailableAccounts() active_account = properties.VALUES.core.account.Get() if args.filter_account: if args.filter_account in accounts: accounts = [args.filter_account] else: accounts = [] return _AuthInfo(active_account, accounts)
def Run(self, args): """List the account for known credentials.""" accounts = c_store.AvailableAccounts() active_account = c_store.ActiveAccount() if args.account: if args.account in accounts: accounts = [args.account] else: accounts = [] auth_info = collections.namedtuple('auth_info', ['active_account', 'accounts']) return auth_info(active_account, accounts)
def Run(self, args): """Revoke credentials and update active account.""" accounts = args.accounts or [] if isinstance(accounts, str): accounts = [accounts] available_accounts = c_store.AvailableAccounts() unknown_accounts = set(accounts) - set(available_accounts) if unknown_accounts: raise c_exc.UnknownArgumentException('accounts', ' '.join(unknown_accounts)) if args.all: accounts = available_accounts active_account = properties.VALUES.core.account.Get() if not accounts and active_account: accounts = [active_account] if not accounts: raise c_exc.InvalidArgumentException( 'accounts', 'No credentials available to revoke.') for account in accounts: if active_account == account: properties.PersistProperty(properties.VALUES.core.account, None) if not c_store.Revoke(account, use_google_auth=not args.use_oauth2client): if account.endswith('.gserviceaccount.com'): log.warning( '[{}] appears to be a service account. Service account tokens ' 'cannot be revoked, but they will expire automatically. To ' 'prevent use of the service account token earlier than the ' 'expiration, revoke the parent service account or service ' 'account key.'.format(account)) else: log.warning( '[{}] already inactive (previously revoked?)'.format( account)) return accounts
def _PickAccount(self, console_only, preselected=None): """Checks if current credentials are valid, if not runs auth login. Args: console_only: bool, True if the auth flow shouldn't use the browser preselected: str, disable prompts and use this value if not None Returns: bool, True if valid credentials are setup. """ new_credentials = False accounts = c_store.AvailableAccounts() if accounts: # There is at least one credentialed account. if preselected: # Try to use the preselected account. Fail if its not credentialed. account = preselected if account not in accounts: log.status.write('\n[{0}] is not one of your credentialed accounts ' '[{1}].\n'.format(account, ','.join(accounts))) return False # Fall through to the set the account property. else: # Prompt for the account to use. idx = console_io.PromptChoice( accounts + ['Log in with a new account'], message='Choose the account you would like to use to perform ' 'operations for this configuration:', prompt_string=None) if idx is None: return False if idx < len(accounts): account = accounts[idx] else: new_credentials = True elif preselected: # Preselected account specified but there are no credentialed accounts. log.status.write('\n[{0}] is not a credentialed account.\n'.format( preselected)) return False else: # Must log in with new credentials. answer = console_io.PromptContinue( prompt_string='You must log in to continue. Would you like to log in') if not answer: return False new_credentials = True if new_credentials: # Call `gcloud auth login` to get new credentials. # `gcloud auth login` may have user interaction, do not suppress it. browser_args = ['--no-launch-browser'] if console_only else [] if not self._RunCmd(['auth', 'login'], ['--force', '--brief'] + browser_args, disable_user_output=False): return False # `gcloud auth login` already did `gcloud config set account`. else: # Set the config account to the already credentialed account. properties.PersistProperty(properties.VALUES.core.account, account) log.status.write('You are logged in as: [{0}].\n\n' .format(properties.VALUES.core.account.Get())) return True
def Run(self, args): """Revoke credentials and update active account.""" accounts = args.accounts or [] if isinstance(accounts, str): accounts = [accounts] available_accounts = c_store.AvailableAccounts() unknown_accounts = set(accounts) - set(available_accounts) if unknown_accounts: raise c_exc.UnknownArgumentException( 'accounts', ' '.join(unknown_accounts)) if args.all: accounts = available_accounts active_account = properties.VALUES.core.account.Get() if not accounts and active_account: accounts = [active_account] if not accounts: raise c_exc.InvalidArgumentException( 'accounts', 'No credentials available to revoke.') for account in accounts: if active_account == account: properties.PersistProperty(properties.VALUES.core.account, None) # External account and external account user credentials cannot be # revoked. # Detect these type of credentials to show a more user friendly message # on revocation calls. # Note that impersonated external account credentials will appear like # service accounts. These will end with gserviceaccount.com and will be # handled the same way service account credentials are handled. try: creds = c_store.Load( account, prevent_refresh=True, use_google_auth=True) except creds_exceptions.Error: # Ignore all errors. These will be properly handled in the subsequent # Revoke call. creds = None if not c_store.Revoke(account): if account.endswith('.gserviceaccount.com'): log.warning( '[{}] appears to be a service account. Service account tokens ' 'cannot be revoked, but they will expire automatically. To ' 'prevent use of the service account token earlier than the ' 'expiration, delete or disable the parent service account.' .format(account)) elif c_creds.IsExternalAccountCredentials(creds): log.warning( '[{}] appears to be an external account. External account ' 'tokens cannot be revoked, but they will expire automatically.' .format(account)) elif c_creds.IsExternalAccountUserCredentials(creds): log.warning( '[{}] appears to be an external account user. External account ' 'user tokens cannot be revoked, but they will expire ' 'automatically.'.format(account)) else: log.warning( '[{}] already inactive (previously revoked?)'.format(account)) return accounts