Python keyring.set_password() Examples

The following are 30 code examples for showing how to use keyring.set_password(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module keyring , or try the search function .

Example 1
Project: snowflake-connector-python   Author: snowflakedb   File: auth.py    License: Apache License 2.0 6 votes vote down vote up
def write_temporary_credential(host, account, user, id_token, store_temporary_credential=False):
    if not id_token:
        logger.debug("no ID token is given when try to store temporary credential")
        return
    if IS_MACOS or IS_WINDOWS:
        if not keyring:
            logger.debug("Dependency 'keyring' is not installed, cannot cache id token. You might experience "
                         "multiple authentication pop ups while using ExternalBrowser Authenticator. To avoid "
                         "this please install keyring module using the following command : pip install "
                         "snowflake-connector-python[secure-local-storage]")
            return
        new_target = convert_target(host, user)
        try:
            keyring.set_password(new_target, user.upper(), id_token)
        except keyring.errors.KeyringError as ke:
            logger.debug("Could not store id_token to keyring, %s", str(ke))
    elif IS_LINUX and store_temporary_credential:
        write_temporary_credential_file(host, account, user, id_token)
    else:
        logger.debug("connection parameter client_store_temporary_credential not set or OS not support") 
Example 2
Project: poetry   Author: python-poetry   File: password_manager.py    License: MIT License 6 votes vote down vote up
def set_password(self, name, username, password):
        if not self.is_available():
            return

        import keyring
        import keyring.errors

        name = self.get_entry_name(name)

        try:
            keyring.set_password(name, username, password)
        except (RuntimeError, keyring.errors.KeyringError) as e:
            raise KeyRingError(
                "Unable to store the password for {} in the key ring: {}".format(
                    name, str(e)
                )
            ) 
Example 3
Project: msticpy   Author: microsoft   File: secret_settings.py    License: MIT License 6 votes vote down vote up
def set_secret(self, secret_name: str, secret_value: Any):
        """
        Set a secret in the keyring group.

        Parameters
        ----------
        secret_name : str
            Name of the secret
        secret_value : Any
            Secret value

        """
        if self.debug:
            print(f"Saving {secret_name} to keyring {self.keyring}")
        self._secret_names.add(secret_name)
        keyring.set_password(self.keyring, secret_name, secret_value) 
Example 4
Project: yolo   Author: rackerlabs   File: client.py    License: Apache License 2.0 6 votes vote down vote up
def login(self):
        # Get RACKSPACE_USERNAME and RACKSPACE_API_KEY envvars
        # prompt for them interactively.
        # The envvar approach works scripted commands, while the interactive
        # mode is preferred for executing on the command line (by a human).
        self._rax_username = get_username()
        self._rax_api_key = get_api_key(self.rax_username)

        # TODO(larsbutler): perform login against the rackspace identity api

        # store them in keyring:
        keyring.set_password(
            const.NAMESPACE, 'rackspace_username', self.rax_username
        )
        keyring.set_password(
            const.NAMESPACE, 'rackspace_api_key', self.rax_api_key
        )
        print('login successful!') 
Example 5
Project: CumulusCI   Author: SFDO-Tooling   File: runtime.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_keychain_key(self):
        key_from_env = os.environ.get("CUMULUSCI_KEY")
        try:
            key_from_keyring = keyring.get_password("cumulusci", "CUMULUSCI_KEY")
            has_functioning_keychain = True
        except Exception as e:
            keychain_exception = e
            key_from_keyring = None
            has_functioning_keychain = False
        # If no key in environment or file, generate one
        key = key_from_env or key_from_keyring
        if key is None:
            if has_functioning_keychain:
                key = random_alphanumeric_underscore(length=16)
            else:
                raise KeychainKeyNotFound(
                    "Unable to store CumulusCI encryption key. "
                    "You can configure it manually by setting the CUMULUSCI_KEY "
                    "environment variable to a random 16-character string. "
                    f"ERROR: {keychain_exception}"
                )
        if has_functioning_keychain and not key_from_keyring:
            keyring.set_password("cumulusci", "CUMULUSCI_KEY", key)
        return key 
Example 6
Project: CumulusCI   Author: SFDO-Tooling   File: runtime.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_org_expired(self, org_name, org_config):
        if org_config.scratch and org_config.date_created and org_config.expired:
            click.echo(click.style("The scratch org is expired", fg="yellow"))
            self.keychain.create_scratch_org(
                org_name,
                org_config.config_name,
                days=org_config.days,
                set_password=org_config.set_password,
            )
            click.echo(
                click.style(
                    "Org config was refreshed, attempting to recreate scratch org",
                    fg="yellow",
                )
            )
            org_config = self.keychain.get_org(org_name)
            org_config.create_org()

        return org_config 
Example 7
Project: stocklook   Author: zbarge   File: security.py    License: MIT License 6 votes vote down vote up
def reset_credentials(self, service_name, username, new_secret_items=None):
        """
        Removes a username/password from KeyRing
        and replaces with a new one if desired.

        :param service_name: (str)
            The service name to remove.

        :param username: (str)
            The username to remove the password for.

        :param new_secret_items: (list, default None)
            The new secret item(s) to assign to the username if desired.

        :return: (None)
        """
        try:
            keyring.delete_password(service_name, username)
        except keyring.errors.PasswordDeleteError:
            pass

        if new_secret_items:
            new_pass = self._join_password_items(new_secret_items)
            keyring.set_password(service_name, username, new_pass) 
Example 8
Project: runsqlrun   Author: andialbrecht   File: manager.py    License: MIT License 6 votes vote down vote up
def update_connection(self, data):
        if 'key' not in data:
            data['key'] = str(uuid.uuid4()).replace('-', '')
        key = data.pop('key')
        if os.path.exists(CONNECTIONS_FILE):
            with open(CONNECTIONS_FILE) as f:
                content = json.load(f)
        else:
            content = {}
        password = data.pop('password', None)
        content[key] = data
        with open(CONNECTIONS_FILE, 'w') as f:
            json.dump(content, f)
        if password is not None:
            data['password'] = password
            conn = self.get_connection(key)
            if not (conn and conn.has_session_password()):
                keyring.set_password('runsqlrun', key, password)
        self.update_connections()
        return key 
Example 9
Project: bcloud   Author: XuShaohua   File: gutil.py    License: GNU General Public License v3.0 6 votes vote down vote up
def dump_profile(profile):
    '''保存帐户的配置信息.

    这里会检查用户是否愿意保存密码, 如果需要保存密码的话, 就调用keyring来存
    放密码.
    但如果密码为空, 就不再存放它了.
    '''
    profile = profile.copy()
    path = os.path.join(Config.CONF_DIR, profile['username'])
    if profile['remember-password'] and profile['password']:
        for i in range(RETRIES):
            try:
                keyring.set_password(Config.DBUS_APP_NAME, profile['username'],
                                     profile['password'])
                break
            except dbus.exceptions.DBusException:
                logger.error(traceback.format_exc())
    profile['password'] = ''
    with open(path, 'w') as fh:
        json.dump(profile, fh) 
Example 10
Project: flytekit   Author: lyft   File: auth.py    License: Apache License 2.0 6 votes vote down vote up
def _initialize_credentials(self, auth_token_resp):

        """
        The auth_token_resp body is of the form:
        {
          "access_token": "foo",
          "refresh_token": "bar",
          "id_token": "baz",
          "token_type": "Bearer"
        }
        """
        response_body = auth_token_resp.json()
        if "access_token" not in response_body:
            raise ValueError('Expected "access_token" in response from oauth server')
        if "refresh_token" in response_body:
            self._refresh_token = response_body["refresh_token"]

        access_token = response_body["access_token"]
        refresh_token = response_body["refresh_token"]

        _keyring.set_password(_keyring_service_name, _keyring_access_token_storage_key, access_token)
        _keyring.set_password(_keyring_service_name, _keyring_refresh_token_storage_key, refresh_token)
        self._credentials = Credentials(access_token=access_token) 
Example 11
Project: pkmeter   Author: pkkid   File: pkconfig.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set(self, namespace, path, value, to_keyring=False):
        path = '%s.%s' % (namespace, path)
        if to_keyring:
            keyring.set_password(APPNAME, path, value)
        else:
            utils.rset(self.values, path, value) 
Example 12
Project: EDMarketConnector   Author: EDCD   File: config.py    License: GNU General Public License v2.0 5 votes vote down vote up
def set_password(self, account, password):
        try:
            import keyring
            keyring.set_password(self.identifier, account, password)
        except ImportError:
            pass 
Example 13
Project: earthengine   Author: mortcanty   File: keyring_storage.py    License: MIT License 5 votes vote down vote up
def locked_put(self, credentials):
    """Write Credentials to file.

    Args:
      credentials: Credentials, the credentials to store.
    """
    keyring.set_password(self._service_name, self._user_name,
                         credentials.to_json()) 
Example 14
Project: earthengine   Author: mortcanty   File: keyring_storage.py    License: MIT License 5 votes vote down vote up
def locked_delete(self):
    """Delete Credentials file.

    Args:
      credentials: Credentials, the credentials to store.
    """
    keyring.set_password(self._service_name, self._user_name, '') 
Example 15
Project: poetry   Author: python-poetry   File: password_manager.py    License: MIT License 5 votes vote down vote up
def set_pypi_token(self, name, token):
        if not self.keyring.is_available():
            self._config.auth_config_source.add_property(
                "pypi-token.{}".format(name), token
            )
        else:
            self.keyring.set_password(name, "__token__", token) 
Example 16
Project: poetry   Author: python-poetry   File: password_manager.py    License: MIT License 5 votes vote down vote up
def set_http_password(self, name, username, password):
        auth = {"username": username}

        if not self.keyring.is_available():
            auth["password"] = password
        else:
            self.keyring.set_password(name, username, password)

        self._config.auth_config_source.add_property("http-basic.{}".format(name), auth) 
Example 17
Project: jira   Author: pycontribs   File: jirashell.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def handle_basic_auth(auth, server):
    if auth.get("password"):
        password = auth["password"]
        if input("Would you like to remember password in OS keyring? (y/n)") == "y":
            keyring.set_password(server, auth["username"], password)
    else:
        print("Getting password from keyring...")
        password = keyring.get_password(server, auth["username"])
        assert password, "No password provided!"
    return (auth["username"], password) 
Example 18
Project: D-VAE   Author: muhanzhang   File: gh_api.py    License: MIT License 5 votes vote down vote up
def get_auth_token():
    global token

    if token is not None:
        return token

    import keyring
    token = keyring.get_password('github', fake_username)
    if token is not None:
        return token

    print("Please enter your github username and password. These are not "
          "stored, only used to get an oAuth token. You can revoke this at "
          "any time on Github.")
    user = input("Username: ")
    pw = getpass.getpass("Password: ")

    auth_request = {
        "scopes": [
            "public_repo",
            "gist"
        ],
        "note": "IPython tools",
        "note_url": "https://github.com/ipython/ipython/tree/master/tools",
    }
    response = requests.post('https://api.github.com/authorizations',
                             auth=(user, pw), data=json.dumps(auth_request))
    response.raise_for_status()
    token = json.loads(response.text)['token']
    keyring.set_password('github', fake_username, token)
    return token 
Example 19
Project: splunk-ref-pas-code   Author: splunk   File: keyring_storage.py    License: Apache License 2.0 5 votes vote down vote up
def locked_put(self, credentials):
    """Write Credentials to file.

    Args:
      credentials: Credentials, the credentials to store.
    """
    keyring.set_password(self._service_name, self._user_name,
                         credentials.to_json()) 
Example 20
Project: splunk-ref-pas-code   Author: splunk   File: keyring_storage.py    License: Apache License 2.0 5 votes vote down vote up
def locked_delete(self):
    """Delete Credentials file.

    Args:
      credentials: Credentials, the credentials to store.
    """
    keyring.set_password(self._service_name, self._user_name, '') 
Example 21
Project: sndlatr   Author: Schibum   File: keyring_storage.py    License: Apache License 2.0 5 votes vote down vote up
def locked_put(self, credentials):
    """Write Credentials to file.

    Args:
      credentials: Credentials, the credentials to store.
    """
    keyring.set_password(self._service_name, self._user_name,
                         credentials.to_json()) 
Example 22
Project: sndlatr   Author: Schibum   File: keyring_storage.py    License: Apache License 2.0 5 votes vote down vote up
def locked_delete(self):
    """Delete Credentials file.

    Args:
      credentials: Credentials, the credentials to store.
    """
    keyring.set_password(self._service_name, self._user_name, '') 
Example 23
Project: biweeklybudget   Author: jantman   File: config.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def write(self, *args):
        """See ConfigParser.write().  Also writes secure items to keystore."""
        ConfigParser.write(self, *args)
        if self.keyring_available:
            for key, thing in self._unsaved.items():
                action = thing[0]
                value = thing[1]
                if action == 'set':
                    keyring.set_password(self.keyring_name, key, value)
                elif action == 'delete':
                    try:
                        keyring.delete_password(self.keyring_name, key)
                    except:
                        pass
        self._unsaved = {} 
Example 24
Project: billing-export-python   Author: googlearchive   File: keyring_storage.py    License: Apache License 2.0 5 votes vote down vote up
def locked_put(self, credentials):
    """Write Credentials to file.

    Args:
      credentials: Credentials, the credentials to store.
    """
    keyring.set_password(self._service_name, self._user_name,
                         credentials.to_json()) 
Example 25
Project: billing-export-python   Author: googlearchive   File: keyring_storage.py    License: Apache License 2.0 5 votes vote down vote up
def locked_delete(self):
    """Delete Credentials file.

    Args:
      credentials: Credentials, the credentials to store.
    """
    keyring.set_password(self._service_name, self._user_name, '') 
Example 26
Project: google-analytics   Author: debrouwere   File: keyring.py    License: ISC License 5 votes vote down vote up
def set(name, secrets):
    keyring.set_password(DOMAIN, name, json.dumps(secrets)) 
Example 27
Project: openconnect-sso   Author: vlaci   File: config.py    License: GNU General Public License v3.0 5 votes vote down vote up
def password(self, value):
        keyring.set_password(APP_NAME, self.username, value) 
Example 28
Project: python-aada   Author: piontas   File: configure.py    License: MIT License 5 votes vote down vote up
def _configure(self, parsed_args):
        new_values = {}
        try:
            config = self._session.get_scoped_config()
        except ProfileNotFound:
            config = {}
        for config_name, prompt_text in self.PROMPT_VALUES:
            current_value = config.get(config_name)
            new_value = self._get_value(current_value, prompt_text)
            if new_value is not None and new_value != current_value:
                new_values[config_name] = new_value
        config_filename = os.path.expanduser(
            self._session.get_config_variable('config_file'))
        if KEYRING and config.get('use_keyring'):
            updatepwd = input('Update Azure password in keyring? (yes/no)')
            if updatepwd.upper() in ['Y', 'YES']:
                azure_pass = getpass.getpass('Azure password ')
                keyring.set_password('aada', config.get('azure_username'),
                                     azure_pass)
        if new_values:
            self._write_credentials(new_values, parsed_args.profile)
            if parsed_args.profile is not None:
                new_values['__section__'] = ('profile {}'.format(
                    parsed_args.profile))
            self._config_writer.update_config(new_values, config_filename)
        return 0 
Example 29
Project: onedrived-dev   Author: xybu   File: od_api_session.py    License: MIT License 5 votes vote down vote up
def save_session(self, **save_session_kwargs):
        if self.SESSION_ARG_KEYNAME not in save_session_kwargs:
            raise ValueError('"%s" must be specified in save_session() argument.' % self.SESSION_ARG_KEYNAME)
        data = base64.b64encode(zlib.compress(pickle.dumps(self, self.PICKLE_PROTOCOL))).decode('utf-8')
        keyring.set_password(self.KEYRING_SERVICE_NAME, save_session_kwargs[self.SESSION_ARG_KEYNAME], data) 
Example 30
Project: attention-lvcsr   Author: rizar   File: gh_api.py    License: MIT License 5 votes vote down vote up
def get_auth_token():
    global token

    if token is not None:
        return token

    import keyring
    token = keyring.get_password('github', fake_username)
    if token is not None:
        return token

    print("Please enter your github username and password. These are not "
          "stored, only used to get an oAuth token. You can revoke this at "
          "any time on Github.")
    user = input("Username: ")
    pw = getpass.getpass("Password: ")

    auth_request = {
        "scopes": [
            "public_repo",
            "gist"
        ],
        "note": "IPython tools",
        "note_url": "https://github.com/ipython/ipython/tree/master/tools",
    }
    response = requests.post('https://api.github.com/authorizations',
                             auth=(user, pw), data=json.dumps(auth_request))
    response.raise_for_status()
    token = json.loads(response.text)['token']
    keyring.set_password('github', fake_username, token)
    return token