Lookup credentials for a given target in keyring and .netrc.

    Optionally prompts for credentials if not found.

    Returns:
        2-tuple (username, password) or None
171646
def get_credentials_for_url(url, opts, force_user=None):
    
    creds = None
    verbose = int(opts.get("verbose"))
    force_prompt = opts.get("prompt", False)
    allow_prompt = not opts.get("no_prompt", True)
    allow_keyring = not opts.get("no_keyring", False) and not force_user
    allow_netrc = not opts.get("no_netrc", False) and not force_user

    # print("get_credentials_for_url", force_user, allow_prompt)
    if force_user and not allow_prompt:
        raise RuntimeError(
            "Cannot get credentials for a distinct user ({}) from keyring or .netrc and "
            "prompting is disabled.".format(force_user)
        )

    # Lookup our own pyftpsync 1.x credential store. This is deprecated with 2.x
    home_path = os.path.expanduser("~")
    file_path = os.path.join(home_path, DEFAULT_CREDENTIAL_STORE)
    if os.path.isfile(file_path):
        raise RuntimeError(
            "Custom password files are no longer supported. Delete {} and use .netrc instead.".format(
                file_path
            )
        )

    # Query keyring database
    if creds is None and keyring and allow_keyring:
        try:
            # Note: we pass the url as `username` and username:password as `password`
            c = keyring.get_password("pyftpsync", url)
            if c is not None:
                creds = c.split(":", 1)
                write(
                    "Using credentials from keyring('pyftpsync', '{}'): {}:***.".format(
                        url, creds[0]
                    )
                )
            else:
                if verbose >= 4:
                    write(
                        "No credentials found in keyring('pyftpsync', '{}').".format(
                            url
                        )
                    )
        #        except keyring.errors.TransientKeyringError:
        except Exception as e:
            # e.g. user clicked 'no'
            write_error("Could not get password from keyring {}".format(e))

    # Query .netrc file
    #     print(opts)
    if creds is None and allow_netrc:
        try:
            authenticators = None
            authenticators = netrc.netrc().authenticators(url)
        except CompatFileNotFoundError:
            if verbose >= 4:
                write("Could not get password (no .netrc file).")
        except Exception as e:
            write_error("Could not read .netrc: {}.".format(e))

        if authenticators:
            creds = (authenticators[0], authenticators[2])
            write("Using credentials from .netrc file: {}:***.".format(creds[0]))
        else:
            if verbose >= 4:
                write("Could not find entry for '{}' in .netrc file.".format(url))

    # Prompt for password if we don't have credentials yet, or --prompt was set.
    if allow_prompt:
        if creds is None:
            creds = prompt_for_password(url)
        elif force_prompt:
            # --prompt was set but we can provide a default for the user name
            creds = prompt_for_password(url, default_user=creds[0])

    return creds
715494
def find_credential(self, url):
        
        for repository, cred in self.creds_by_repository.items():
            if url.startswith(repository):
                return cred
758027
def credentials(login=None):
    
    if not login:
        login = environ.get("PROF_LOGIN")
    password = environ.get("PROF_PASSWORD")
    if not login:
        try:
            login = input("login? ")
            print("\t\tDon't get prompted everytime. Store your login in the ``~/.profrc`` config file")
        except KeyboardInterrupt:
            exit(0)
    if not password:
        try:
            password = getpass.getpass("pass for {0} ? ".format(login))
        except KeyboardInterrupt:
            exit(0)
    return (login, password)
1372229
def _credentials_found_in_envars():
        
        return any([os.getenv('PAN_ACCESS_TOKEN'),
                    os.getenv('PAN_CLIENT_ID'),
                    os.getenv('PAN_CLIENT_SECRET'),
                    os.getenv('PAN_REFRESH_TOKEN')])
104356
def ExtractCredentialsFromPathSpec(self, path_spec):
    
    credentials = manager.CredentialsManager.GetCredentials(path_spec)
    for identifier in credentials.CREDENTIALS:
      value = getattr(path_spec, identifier, None)
      if value is None:
        continue

      self.SetCredential(path_spec, identifier, value)
59542
def getCredentials(self):
        """"""

        (username, password, public_key, private_key) = self.getCredentialValues()

        if public_key or private_key:
            return UserKeyCredential(username, public_key, private_key)

        if username or password:
            return UserPassCredential(username, password)

        return None
477111
def find_credentials(host):
    '''
    
    '''
    user_names = [__pillar__['proxy'].get('username', 'root')]
    passwords = __pillar__['proxy']['passwords']
    for user in user_names:
        for password in passwords:
            try:
                # Try to authenticate with the given user/password combination
                ret = __salt__['vsphere.system_info'](host=host,
                                                      username=user,
                                                      password=password)
            except SaltSystemExit:
                # If we can't authenticate, continue on to try the next password.
                continue
            # If we have data returned from above, we've successfully authenticated.
            if ret:
                DETAILS['username'] = user
                DETAILS['password'] = password
                return user, password
    # We've reached the end of the list without successfully authenticating.
    raise SaltSystemExit('Cannot complete login due to an incorrect user name or password.')
767584
def getSecret(name, version="", region=None,
              table="credential-store", context=None,
              dynamodb=None, kms=None, **kwargs):
    '''
    
    '''
    if not context:
        context = {}

    # Can we cache
    if dynamodb is None or kms is None:
        session = get_session(**kwargs)
        if dynamodb is None:
            dynamodb = session.resource('dynamodb', region_name=region)
        if kms is None:
            kms = session.client('kms', region_name=region)

    secrets = dynamodb.Table(table)

    if version == "":
        # do a consistent fetch of the credential with the highest version
        response = secrets.query(Limit=1,
                                 ScanIndexForward=False,
                                 ConsistentRead=True,
                                 KeyConditionExpression=boto3.dynamodb.conditions.Key("name").eq(name))
        if response["Count"] == 0:
            raise ItemNotFound("Item {'name': '%s'} couldn't be found." % name)
        material = response["Items"][0]
    else:
        response = secrets.get_item(Key={"name": name, "version": version})
        if "Item" not in response:
            raise ItemNotFound(
                "Item {'name': '%s', 'version': '%s'} couldn't be found." % (name, version))
        material = response["Item"]

    key_service = KeyService(kms, None, context)

    return open_aes_ctr_legacy(key_service, material)
961100
def _save_password_in_keyring(credential_id, username, password):
    '''
    
    '''
    try:
        import keyring  # pylint: disable=import-error
        return keyring.set_password(credential_id, username, password)
    except ImportError:
        log.error('Tried to store password in keyring, but no keyring module is installed')
        return False
1065953
def checkKey(self, credentials):
        
        filename = self._keyfile
        if not os.path.exists(filename):
            return 0
        lines = open(filename).xreadlines()
        for l in lines:
            l2 = l.split()
            if len(l2) < 2:
                continue
            try:
                if base64.decodestring(l2[1]) == credentials.blob:
                    return 1
            except binascii.Error:
                continue
        return 0
1087220
def read_credentials(self, credentials):
        
        self._items.clear()
        for key in credentials.get_key_names():
            value = credentials.get_as_nullable_string(key)
            self._items.append(CredentialParams.from_tuples([key, value]))
603721
def credentials(self):
        
        if self._credentials is None:
            self._credentials = CredentialList(
                self._version,
                account_sid=self._solution['account_sid'],
                credential_list_sid=self._solution['sid'],
            )
        return self._credentials
408742
def store_password_in_keyring(credential_id, username, password=None):
    '''
    
    '''
    try:
        # pylint: disable=import-error
        import keyring
        import keyring.errors
        # pylint: enable=import-error
        if password is None:
            prompt = 'Please enter password for {0}: '.format(credential_id)
            try:
                password = getpass.getpass(prompt)
            except EOFError:
                password = None

            if not password:
                # WE should raise something else here to be able to use this
                # as/from an API
                raise RuntimeError('Invalid password provided.')

        try:
            _save_password_in_keyring(credential_id, username, password)
        except keyring.errors.PasswordSetError as exc:
            log.debug('Problem saving password in the keyring: %s', exc)
    except ImportError:
        log.error('Tried to store password in keyring, but no keyring module is installed')
        return False
526559
def has_credentials(self):
        
        return all([
            getattr(self, '_%s' % field, None) is not None
            for field in self.CredentialMap.get(self.provider_name)])
478121
def keyring_auth(self, username=None):
        
        if not keyring:
            # Module not installed
            raise exc.KeyringModuleNotInstalled("The 'keyring' Python module "
                    "is not installed on this system.")
        if username is None:
            username = pyrax.get_setting("keyring_username")
        if not username:
            raise exc.KeyringUsernameMissing("No username specified for "
                    "keyring authentication.")
        password = keyring.get_password("pyrax", username)
        if password is None:
            raise exc.KeyringPasswordNotFound("No password was found for the "
                    "username '%s'." % username)
        style = self._creds_style or self._default_creds_style
        # Keyring username may be different than the credentials. Use the
        # existing username, if present; otherwise, use the supplied username.
        username = self.username or username
        if style == "apikey":
            return self.authenticate(username=username, api_key=password)
        else:
            return self.authenticate(username=username, password=password)
20965
def verify_credentials(self, delegate=None):
        ""
        parser = txml.Users(delegate)
        return self.__downloadPage('/account/verify_credentials.xml', parser)
1285555
def retrieve_client_credentials(self):
        
        client_id = self.params.get('client_id')
        client_secret = self.params.get('client_secret')
        return (client_id, client_secret)