Python keyring.set_password() Examples

The following are 30 code examples of keyring.set_password(). 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 also want to check out all available functions/classes of the module keyring , or try the search function .
Example #1
Source File: auth.py    From flytekit with 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 #2
Source File: gutil.py    From bcloud with 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 #3
Source File: manager.py    From runsqlrun with 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 #4
Source File: security.py    From stocklook with 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 #5
Source File: runtime.py    From CumulusCI with 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 #6
Source File: runtime.py    From CumulusCI with 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 #7
Source File: client.py    From yolo with 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 #8
Source File: secret_settings.py    From msticpy with 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 #9
Source File: auth.py    From snowflake-connector-python with 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 #10
Source File: password_manager.py    From poetry with 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 #11
Source File: keyring_storage.py    From luci-py with 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 #12
Source File: keyring_storage.py    From data with GNU General Public License v3.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 #13
Source File: keyring_storage.py    From twitter-for-bigquery with 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 #14
Source File: keyring_storage.py    From twitter-for-bigquery with 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 #15
Source File: security.py    From stocklook with MIT License 5 votes vote down vote up
def set(self, service_name, username, password):
        """
        Sets a password securely under the username.
        :param service_name:
        :param username:
        :param password:
        :return:
        """
        keyring.set_password(service_name, username, password)
        self.data[service_name] = username 
Example #16
Source File: keyring_storage.py    From earthengine with 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 #17
Source File: gtasks.py    From Gtasks with MIT License 5 votes vote down vote up
def authenticate(self):
        extra = {'client_id': self.client_id, 'client_secret': self.client_secret}
        self.google = OAuth2Session(self.client_id, scope=Gtasks.SCOPE,
                redirect_uri=self.redirect_uri, auto_refresh_kwargs=extra,
                auto_refresh_url=Gtasks.TOKEN_URL, token_updater=lambda t: None)

        refresh_token = keyring.get_password('gtasks.py', self.identifier)
        if refresh_token and not self.force_login:
            self.google.refresh_token(Gtasks.TOKEN_URL, refresh_token)
        else:
            authorization_url, __ = self.google.authorization_url(Gtasks.AUTH_URL,
                    access_type='offline', approval_prompt='force')

            if self.open_browser:
                webbrowser.open_new_tab(authorization_url)
                prompt = ('The following URL has been opened in your web browser:'
                        '\n\n{}\n\nPlease paste the response code below:\n')
            else:
                prompt = ('Please copy the following URL into your web browser:'
                        '\n\n{}\n\nPlease paste the response code below:\n')
            redirect_response = compatible_input(prompt.format(authorization_url))
            print('Thank you!')

            tokens = self.google.fetch_token(Gtasks.TOKEN_URL,
                    client_secret=self.client_secret, code=redirect_response)
            keyring.set_password('gtasks.py', self.identifier,
                    tokens['refresh_token']) 
Example #18
Source File: config.py    From bonfire with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def store_password_in_keyring(host, username, password):
    keyring.set_password('bonfire_' + host, username, password) 
Example #19
Source File: secrets.py    From releasetool with Apache License 2.0 5 votes vote down vote up
def ensure_password(name, prompt):
    password = get_password(name)

    if not password:
        password = click.prompt(prompt)
        set_password(name, password)

    return password 
Example #20
Source File: keyring_storage.py    From data with GNU General Public License v3.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
Source File: keyring_storage.py    From luci-py with 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
Source File: keyring_storage.py    From luci-py with 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
Source File: keyring_storage.py    From luci-py with 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 #24
Source File: keyring_storage.py    From luci-py with 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
Source File: keyring_storage.py    From luci-py with 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
Source File: keyring_storage.py    From luci-py with 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 #27
Source File: keyring_storage.py    From luci-py with 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 #28
Source File: keyring_storage.py    From luci-py with 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 #29
Source File: credentials.py    From onelogin-aws-cli with MIT License 5 votes vote down vote up
def _save_password_to_keychain(self):
        keyring.set_password(self.SERVICE_NAME, self.username, self.password) 
Example #30
Source File: __main__.py    From yagmail with MIT License 5 votes vote down vote up
def register(username, password):
    """ Use this to add a new gmail account to your OS' keyring so it can be used in yagmail """
    keyring.set_password('yagmail', username, password)