Example #1
0
    def test_find_items(self):
        '''find_items_sync()'''

        search_attrs = GnomeKeyring.Attribute.list_new()

        # no attributes, finds everything
        (result, items) = GnomeKeyring.find_items_sync(
                GnomeKeyring.ItemType.GENERIC_SECRET,
                search_attrs)
        self.assertEqual(result, GnomeKeyring.Result.OK)
        print('(no attributes: %i matches) ' % len(items), end='', file=sys.stderr)
        for item in items:
            self.assertNotEqual(item.keyring, '')
            for attr in GnomeKeyring.Attribute.list_to_glist(item.attributes):
                self.assertTrue(attr.type in (GnomeKeyring.AttributeType.STRING,
                            GnomeKeyring.AttributeType.UINT32))
                self.assertEqual(type(attr.name), type(''))
                self.assertGreater(len(attr.name), 0)

                # check that we can get the value
                if attr.type == GnomeKeyring.AttributeType.STRING:
                    self.assertEqual(type(attr.get_string()), type(''))
                else:
                    self.assertTrue(isinstance(attr.get_uint32()), long)

        # search for unknown attribute, should have no results
        GnomeKeyring.Attribute.list_append_string(search_attrs, 'unknown!_attr', '')
        (result, items) = GnomeKeyring.find_items_sync(
                GnomeKeyring.ItemType.GENERIC_SECRET,
                search_attrs)
        self.assertEqual(result, GnomeKeyring.Result.NO_MATCH)
        self.assertEqual(len(items), 0)
Example #2
0
	def get(self, protocol, user, server):
		(result, ids) = GnomeKeyring.list_item_ids_sync(self._defaultKeyring)		
		if result == GnomeKeyring.Result.OK:
			displayNameDict = {}
			for identity in ids:
				(result, item) = GnomeKeyring.item_get_info_sync(self._defaultKeyring, identity)
				displayNameDict[item.get_display_name()] = identity

			if self.KEYRING_ITEM_NAME % (protocol, user, server) in displayNameDict:
				(result, item) = GnomeKeyring.item_get_info_sync(self._defaultKeyring, \
					displayNameDict[self.KEYRING_ITEM_NAME % \
					(protocol, user, server)])

				if item.get_secret() != '':
					return item.get_secret()
				else:
					# DEBUG print "Keyring.get(): No Keyring Password for %s://%s@%s." % (protocol, user, server)
					return ''

			else:
				# DEBUG print "Keyring.get(): %s://%s@%s not in Keyring." % (protocol, user, server)
				return ''

		else:
			# DEBUG print "Keyring.get(): Neither default- nor 'login'-Keyring available."
			return ''
Example #3
0
 def remove_by_id(self, uid):
     """
         Remove an account by uid
         :param uid: (int) account uid
         :return:
     """
     secret_code = self.get_secret_code(uid)
     if secret_code:
         found = False
         (result, ids) = GK.list_item_ids_sync("TwoFactorAuth")
         for gid in ids:
             (result, item) = GK.item_get_info_sync("TwoFactorAuth", gid)
             if result == GK.Result.OK:
                 if item.get_display_name().strip("'") == secret_code:
                     found = True
                     break
         if found:
             GK.item_delete_sync("TwoFactorAuth", gid)
     query = "DELETE FROM accounts WHERE uid=?"
     try:
         self.conn.execute(query, (uid,))
         self.conn.commit()
     except Exception as e:
         logging.error(
             "SQL: Couldn't remove account by uid : %s with error : %s" % (uid, str(e)))
Example #4
0
def get_master_key():
    ids = GnomeKeyring.list_item_ids_sync(KEYRING)[1]
    for id in ids:
        info = GnomeKeyring.item_get_info_sync('login', id)[1]
        if info.get_display_name() == 'gpwg:masterkey':
            return info.get_secret()
    return None
    def find_keyring_items(self):
        attrs = GnomeKeyring.Attribute.list_new()
        GnomeKeyring.Attribute.list_append_string(attrs, 'rhythmbox-plugin', 'pandora')
        result, items = GnomeKeyring.find_items_sync(GnomeKeyring.ItemType.GENERIC_SECRET, attrs)

        if (result is None or result is GnomeKeyring.Result.OK) and len(items) != 0: # Got list of search results
            self.__keyring_data['id'] = items[0].item_id
            result, item = GnomeKeyring.item_get_info_sync(None, self.__keyring_data['id'])
            if result is None or result is GnomeKeyring.Result.OK: # Item retrieved successfully
                self.__keyring_data['item'] = item
                self.fill_account_details()
            else:
                print("Couldn't retrieve keyring item: " + str(result))

        elif result == GnomeKeyring.Result.NO_MATCH or len(items) == 0: # No items were found, so we'll create one
            result, id = GnomeKeyring.item_create_sync(
                                None,
                                GnomeKeyring.ItemType.GENERIC_SECRET,
                                "Rhythmbox: Pandora account information",
                                attrs,
                                "", # Empty secret for now
                                True)
            if result is None or result is GnomeKeyring.Result.OK: # Item successfully created
                self.__keyring_data['id'] = id
                result, item = GnomeKeyring.item_get_info_sync(None, id)
                if result is None: # Item retrieved successfully
                    self.__keyring_data['item'] = item
                    self.fill_account_details()
                else:
                    print("Couldn't retrieve keyring item: " + str(result))
            else:
                print("Couldn't create keyring item: " + str(result))
        else: # Some other error occurred
            print("Couldn't access keyring: " + str(result))
Example #6
0
    def test_item_create_info(self):
        '''item_create_sync(),  item_get_info_sync(), list_item_ids_sync()'''

        self.assertEqual(GnomeKeyring.create_sync(TEST_KEYRING, TEST_PWD),
                GnomeKeyring.Result.OK)
        self.assertEqual(GnomeKeyring.get_info_sync(TEST_KEYRING)[0], GnomeKeyring.Result.OK)

        attrs = GnomeKeyring.Attribute.list_new()
        GnomeKeyring.Attribute.list_append_string(attrs, 'context', 'testsuite')
        GnomeKeyring.Attribute.list_append_uint32(attrs, 'answer', 42)

        (result, id) = GnomeKeyring.item_create_sync(TEST_KEYRING,
                GnomeKeyring.ItemType.GENERIC_SECRET, 'my_password', attrs,
                'my_secret', False)
        self.assertEqual(result, GnomeKeyring.Result.OK)

        # now query for it
        (result, info) = GnomeKeyring.item_get_info_sync(TEST_KEYRING, id)
        self.assertEqual(result, GnomeKeyring.Result.OK)
        self.assertEqual(info.get_display_name(), 'my_password')
        self.assertEqual(info.get_secret(), 'my_secret')

        # list_item_ids_sync()
        (result, items) = GnomeKeyring.list_item_ids_sync(TEST_KEYRING)
        self.assertEqual(result, GnomeKeyring.Result.OK)
        self.assertEqual(items, [id])
Example #7
0
 def _find(self, displayName, keyring):
     item_keys = gk.list_item_ids_sync(keyring)
     for k in item_keys[1]:
         item_info = gk.item_get_info_sync(keyring, k)
         if item_info.get_display_name() == displayName:
             return (k, item_info.get_display_name(), item_info.get_secret())
     return False
Example #8
0
 def _get_first_key(self, keyring):
     item_keys = gk.list_item_ids_sync(keyring)
     if len(item_keys[1]) > 0:
         item_info = gk.item_get_info_sync(keyring, item_keys[1][0])
         return (item_info[1].get_display_name(), item_info[1].get_secret())
     else:
         return False
Example #9
0
 def do_store(self, id, username, password):
     GnomeKeyring.create_sync("liferea", None)
     attrs = GnomeKeyring.Attribute.list_new()
     GnomeKeyring.Attribute.list_append_string(attrs, "id", id)
     GnomeKeyring.Attribute.list_append_string(attrs, "user", username)
     GnomeKeyring.item_create_sync(
         "liferea", GnomeKeyring.ItemType.GENERIC_SECRET, repr(id), attrs, "@@@".join([username, password]), True
     )
Example #10
0
 def set_credentials(self, user, pw):
     attrs = attributes({
             "user": user,
             "server": self._server,
             "protocol": self._protocol,
         })
     GnomeKeyring.item_create_sync(self._keyring,
             GnomeKeyring.ItemType.NETWORK_PASSWORD, self._name, attrs, pw, True)
Example #11
0
    def test_result_str(self):
        '''result_to_message()'''

        self.assertEqual(GnomeKeyring.result_to_message(GnomeKeyring.Result.OK),
                '')
        self.assertEqual(
                type(GnomeKeyring.result_to_message(GnomeKeyring.Result.NO_SUCH_KEYRING)),
                type(''))
Example #12
0
 def delete_credentials(self, user):
     attrs = attributes({
                         "user": user,
                         "server": self._server,
                         "protocol": self._protocol
                         })
     result, items = GnomeKeyring.find_items_sync(GnomeKeyring.ItemType.NETWORK_PASSWORD, attrs)
     for item in items:
         GnomeKeyring.item_delete_sync(self._keyring, item.item_id)
 def _set_value_to_gnomekeyring(self, name, value):
     """Store a value in the keyring."""
     attributes = GnomeKeyring.Attribute.list_new()
     GnomeKeyring.Attribute.list_append_string(attributes, "id", str(name))
     keyring = GnomeKeyring.get_default_keyring_sync()[1]
     value = GnomeKeyring.item_create_sync(
         keyring, GnomeKeyring.ItemType.GENERIC_SECRET, "%s preferences" % (com.APP), attributes, str(value), True
     )
     return value[1]
Example #14
0
	def _migrate_keyring(self):
		attrs = GnomeKeyring.Attribute.list_new()
		GnomeKeyring.Attribute.list_append_string(attrs, 'application', 'Mailnag')
		result, items = GnomeKeyring.find_items_sync(GnomeKeyring.ItemType.GENERIC_SECRET, attrs)
		
		if result == GnomeKeyring.Result.OK:
			for i in items:
				result, info = GnomeKeyring.item_get_info_sync(self._defaultKeyring, i.item_id)
				self.set(info.get_display_name(), i.secret)
				GnomeKeyring.item_delete_sync(self._defaultKeyring, i.item_id)
Example #15
0
    def __init__(self):
        self.loginDetails = False
        if gk.is_available() is True:
            if "Gusic" in gk.list_keyring_names_sync()[1]:
                self.keyring = gk.list_item_ids_sync("Gusic")[1]

                self.loginDetails = self._get_first_key("Gusic")

            else:
                gk.create_sync("Gusic", "Gusic")
 def remove_credentials(self, acc):
     self.lock.acquire()
     try:
         logger.debug("Removing credentias from gnome keyring for the account: %s" % (acc.get_name()))
         if hasattr(acc, "keyringid"):
             gk.item_delete_sync(self._KEYRING_NAME, int(acc.keyringid))
             logger.debug("Credentials removed")
         else:
             logger.debug("The account has not credentials asigned, continue")
     finally:
         self.lock.release()
Example #17
0
def put_in_keyring(acctid, name, value):
  """Store a value in the keyring."""
  id = "%s/%s" % (acctid, name)
  attributes = GnomeKeyring.Attribute.list_new()
  GnomeKeyring.Attribute.list_append_string(attributes, 'id', str(id))
  keyring = GnomeKeyring.get_default_keyring_sync()[1]
  value = GnomeKeyring.item_create_sync(
    keyring, GnomeKeyring.ItemType.GENERIC_SECRET,
    "Gwibber preference: %s" % id,
    attributes, str(value), True)
  return value[1]
Example #18
0
	def __init__(self):
		(result, kr_name) = GnomeKeyring.get_default_keyring_sync()
		self._defaultKeyring = kr_name
		
		if self._defaultKeyring == None:
			self._defaultKeyring = 'login'

		result = GnomeKeyring.unlock_sync(self._defaultKeyring, None)
		
		if result != GnomeKeyring.Result.OK:
			raise KeyringUnlockException('Failed to unlock default keyring')

		self._migrate_keyring()
Example #19
0
	def __init__(self):
		self.KEYRING_ITEM_NAME = 'Mailnag password for %s://%s@%s'
		
		(result, kr_name) = GnomeKeyring.get_default_keyring_sync()
		self._defaultKeyring = kr_name
		
		if self._defaultKeyring == None:
			self._defaultKeyring = 'login'

		result = GnomeKeyring.unlock_sync(self._defaultKeyring, None)
		
		if (result != GnomeKeyring.Result.OK):
			raise Exception('Failed to unlock default keyring')
def before_all(context):
    """Setup evolution stuff
    Being executed before all features
    """

    # Reset GSettings
    schemas = [x for x in Gio.Settings.list_schemas() if 'evolution' in x.lower()]
    for schema in schemas:
        os.system("gsettings reset-recursively %s" % schema)

    # Skip warning dialog
    os.system("gsettings set org.gnome.evolution.shell skip-warning-dialog true")
    # Show switcher buttons as icons (to minimize tree scrolling)
    os.system("gsettings set org.gnome.evolution.shell buttons-style icons")

    # Wait for things to settle
    sleep(0.5)

    # Skip dogtail actions to print to stdout
    config.logDebugToStdOut = False
    config.typingDelay = 0.2

    # Include assertion object
    context.assertion = dummy()

    # Kill initial setup
    os.system("killall /usr/libexec/gnome-initial-setup")

    # Delete existing ABRT problems
    if problem.list():
        [x.delete() for x in problem.list()]

    try:
        from gi.repository import GnomeKeyring
        # Delete originally stored password
        (response, keyring) = GnomeKeyring.get_default_keyring_sync()
        if response == GnomeKeyring.Result.OK:
            if keyring is not None:
                delete_response = GnomeKeyring.delete_sync(keyring)
                assert delete_response == GnomeKeyring.Result.OK, "Delete failed: %s" % delete_response
            create_response = GnomeKeyring.create_sync("login", 'gnome')
            assert create_response == GnomeKeyring.Result.OK, "Create failed: %s" % create_response
            set_default_response = GnomeKeyring.set_default_keyring_sync('login')
            assert set_default_response == GnomeKeyring.Result.OK, "Set default failed: %s" % set_default_response
        unlock_response = GnomeKeyring.unlock_sync("login", 'gnome')
        assert unlock_response == GnomeKeyring.Result.OK, "Unlock failed: %s" % unlock_response
    except Exception as e:
        print("Exception while unlocking a keyring: %s" % e.message)

    context.app = App('evolution')
Example #21
0
def get_keyring_password():
    GnomeKeyring.unlock_sync("login", None)
    attrs = GnomeKeyring.Attribute.list_new()
    GnomeKeyring.Attribute.list_append_string(attrs, "id", "resnet")
    result, value = GnomeKeyring.find_items_sync(GnomeKeyring.ItemType.GENERIC_SECRET, attrs)
    if result == GnomeKeyring.Result.OK:
        return value[0].secret
    elif result == GnomeKeyring.Result.NO_MATCH:
        # Password not found, prompt to add new one
        print("Password not found in keyring")
        password = getpass.getpass("OSU Login Password: "******"login", GnomeKeyring.ItemType.GENERIC_SECRET, "resnet", attrs, password, True)
        return password
    elif result != GnomeKeyring.Result.OK:
        return None
 def save(self, username, password):
     encoded_credentials = self._encode_credentials(username, password)
 
     item_id = self._find_keyring_item_id()
     if not item_id:
         item_id = self._create_keyring_item_info(encoded_credentials)
     else:
         item_info = self._get_keyring_item_info(item_id)
         item_info.set_secret(encoded_credentials)
         GnomeKeyring.item_set_info_sync(
             GnomeCredentialStore.KEYRING_NAME,
             item_id,
             item_info)
     logger.debug("Successfully saved new credentials to item_id: %s" % item_id)
     return True
 def delete_password(self, service, username):
     """Delete the password for the username of the service.
     """
     from gi.repository import GnomeKeyring
     attrs = GnomeKeyring.Attribute.list_new()
     GnomeKeyring.Attribute.list_append_string(attrs, 'username', username)
     GnomeKeyring.Attribute.list_append_string(attrs, 'domain', service)
     result, items = GnomeKeyring.find_items_sync(
         GnomeKeyring.ItemType.NETWORK_PASSWORD, attrs)
     if result == GnomeKeyring.Result.NO_MATCH:
         raise PasswordDeleteError("Password not found")
     for current in items:
         result = GnomeKeyring.item_delete_sync(current.keyring,
                                                current.item_id)
         if result == GnomeKeyring.Result.CANCELLED:
             raise PasswordDeleteError("Cancelled by user")
Example #24
0
 def priority(cls):
     if 'GnomeKeyring' not in globals():
         raise RuntimeError("GnomeKeyring module required")
     result = GnomeKeyring.get_default_keyring_sync()[0]
     if result != GnomeKeyring.Result.OK:
         raise RuntimeError(result.value_name)
     return 1
    def __init__(self):
        Gtk.Application.__init__(self,
                                 application_id="org.gnome.TwoFactorAuth",
                                 flags=Gio.ApplicationFlags.FLAGS_NONE)
        GLib.set_application_name(_("TwoFactorAuth"))
        GLib.set_prgname("Gnome-TwoFactorAuth")

        self.menu = Gio.Menu()
        self.db = Database()
        self.cfg = SettingsReader()
        self.locked = self.cfg.read("state", "login")

        result = GK.unlock_sync("Gnome-TwoFactorAuth", None)
        if result == GK.Result.CANCELLED:
            self.quit()

        cssProviderFile = Gio.File.new_for_uri('resource:///org/gnome/TwoFactorAuth/style.css')
        cssProvider = Gtk.CssProvider()
        screen = Gdk.Screen.get_default()
        styleContext = Gtk.StyleContext()
        try:
            cssProvider.load_from_file(cssProviderFile)
            styleContext.add_provider_for_screen(screen, cssProvider,
                                             Gtk.STYLE_PROVIDER_PRIORITY_USER)
            logging.debug("Loading css file ")
        except Exception as e:
            logging.error("Error message %s" % str(e))
Example #26
0
	def set(self, key, secret):
		if secret == '':
			return
		
		attrs = self._get_attrs(key)
		
		existing_secret = ''
		result, items = GnomeKeyring.find_items_sync(GnomeKeyring.ItemType.GENERIC_SECRET, attrs)
		
		if result == GnomeKeyring.Result.OK:
			existing_secret = items[0].secret
		
		if existing_secret != secret:
			GnomeKeyring.item_create_sync(self._defaultKeyring, \
					GnomeKeyring.ItemType.GENERIC_SECRET, key, \
					attrs, secret, True)
 def __init__(self):
     self._protocol = "network"
     self._key = gk.ItemType.NETWORK_PASSWORD
     if not gk.is_available():
         raise KeyringException("The Gnome keyring is not available")
     logger.debug("GnomeKeyring is available")
     self.loaded = False
     self.lock = threading.RLock()
     
     if not self.loaded:
         (result, keyring_names) = gk.list_keyring_names_sync()
         if self._KEYRING_NAME not in keyring_names:
             logger.error("Error getting the gnome keyring. We'll try to create it: %s")
             logger.debug("Creating keyring " + self._KEYRING_NAME)
             gk.create_sync(self._KEYRING_NAME, None)
         self.loaded = True
Example #28
0
 def get_password(self, item_id):
     result, item_info = GnomeKeyring.item_get_info_sync(
         self.keyring, item_id)
     if result == GnomeKeyring.Result.OK:
         return item_info.get_secret()
     else:
         return ""
def import_keyrings(from_file):
    with open(from_file, "r") as f:
        keyrings = json.loads(f)

    for keyring_name, keyring_items in list(keyrings.items()):
        try:
            existing_ids = GnomeKeyring.list_item_ids_sync(keyring_name)
        except GnomeKeyring.NoSuchKeyringError:
            sys.stderr.write("No keyring '%s' found. Please create this keyring first" % keyring_name)
            sys.exit(1)

        existing_items = [get_item(keyring_name, id) for id in existing_ids]
        existing_items = [i for i in existing_items if i is not None]

        for item in keyring_items:
            if any(items_roughly_equal(item, i) for i in existing_items):
                print("Skipping %s because it already exists" % item['display_name'])
            else:
                nearly = [i for i in existing_items if items_roughly_equal(i, item, ignore_secret=True)]
                if nearly:
                    print("Existing secrets found for '%s'" % item['display_name'])
                    for i in nearly:
                        print(" " + i['secret'])

                    print("So skipping value from '%s':" % from_file)
                    print(" " + item['secret'])
                else:
                    schema = item['attributes']['xdg:schema']
                    item_type = None
                    if schema ==  'org.freedesktop.Secret.Generic':
                        item_type = GnomeKeyring.ITEM_GENERIC_SECRET
                    elif schema == 'org.gnome.keyring.Note':
                        item_type = GnomeKeyring.ITEM_NOTE
                    elif schema == 'org.gnome.keyring.NetworkPassword':
                        item_type == GnomeKeyring.ITEM_NETWORK_PASSWORD

                    if item_type is not None:
                        item_id = GnomeKeyring.item_create_sync(keyring_name,
                                                                item_type,
                                                                item['display_name'],
                                                                fix_attributes(item['attributes']),
                                                                item['secret'],
                                                                False)
                        print("Copying secret %s" % item['display_name'])
                    else:
                        print("Can't handle secret '%s' of type '%s', skipping" % (item['display_name'], schema))
Example #30
0
    def test_info_default(self):
        '''get_info_sync() for default keyring'''

        # we cannot assume too much about the default keyring; it might be
        # locked or not, and we should avoid poking in it too much
        (result, info) = GnomeKeyring.get_info_sync(None)
        self.assertEqual(result, GnomeKeyring.Result.OK)
        self.assertTrue(info.get_is_locked() in (False, True))
Example #31
0
 def get_item(krname, item_id):
     return gk.item_get_info_sync(krname, item_id)
Example #32
0
 def get_item(krname, item):
     return gk.item_get_info_full_sync(krname, item,
                                       gk.ItemInfoFlags.SECRET)
Example #33
0
 def __init__(self, name, server, protocol):
     self._name = name
     self._server = server
     self._protocol = protocol
     result, self._keyring = GnomeKeyring.get_default_keyring_sync()
Example #34
0
 def __init__(self):
     super().__init__()
     if not hasattr(self, "keyring"):
         result, self.keyring = GnomeKeyring.get_default_keyring_sync()
         if result != GnomeKeyring.Result.OK:
             raise Exception(f"Can't get default keyring, error={result}")
def main(args):
    cache_file = os.path.join(BaseDirectory.save_cache_path('password_reset'),
                              'old-passwords.gpg')
    old_password = getpass.getpass("Enter the password we are looking for: ")
    new_password = getpass.getpass("Enter the new password: "******"Failed to fetch keyrings")

        return 1

    update_count = 0

    for keyring in keyrings:
        result, items = GnomeKeyring.list_item_ids_sync(keyring)

        # Read contents of the keyring
        if result != GnomeKeyring.Result.OK:
            print("Failed to fetch keyring items from {}".format(keyring))

            continue

        # Iterate over all keys
        for itemid in items:
            result, info = GnomeKeyring.item_get_info_full_sync(
                keyring,
                itemid,
                GnomeKeyring.ItemInfoFlags.SECRET)

            if result != GnomeKeyring.Result.OK:
                print("Failed to get item {} from keyring {}".format(
                    itemid,
                    keyring))

                continue

            if check_password(info, passwords, new_password=new_password):
                result = GnomeKeyring.item_set_info_sync(keyring, itemid, info)

                if result != GnomeKeyring.Result.OK:
                    print("Failed to save item {} in keyring {}".format(
                        info.get_display_name(), keyring))
                else:
                    update_count += 1

    print("Updated {} keys".format(update_count))
Example #36
0
        else:
            screen.addstr('\n')

    # Done; pause or eat the key that was ungetch()'d
    screen.addstr('Press any key to continue ...')
    screen.getch()


if __name__ == '__main__':
    gi.require_version('GnomeKeyring', '1.0')
    gi.require_version('Secret', '1')
    from gi.repository import GnomeKeyring as gkr, Secret

    # Unlock the login keyring, if necessary
    was_locked = False
    if gkr.get_info_sync(KEYRING)[1].get_is_locked():
        was_locked = True
        import getpass
        result = gkr.unlock_sync(
            'login',
            getpass.getpass(prompt='Enter password for '
                            'login keyring: '))
        if result == gkr.Result.IO_ERROR:  # Incorrect password
            sys.exit(1)

    # Connect to libsecret
    service = Secret.Service.get_sync(Secret.ServiceFlags.OPEN_SESSION
                                      | Secret.ServiceFlags.LOAD_COLLECTIONS)
    collections = service.get_collections()

    # Search the default keyring
        # now query for it
        (result, info) = GnomeKeyring.item_get_info_sync(TEST_KEYRING, id)
        self.assertEqual(result, GnomeKeyring.Result.OK)
        self.assertEqual(info.get_display_name(), 'my_password')
        self.assertEqual(info.get_secret(), 'my_secret')

        # list_item_ids_sync()
        (result, items) = GnomeKeyring.list_item_ids_sync(TEST_KEYRING)
        self.assertEqual(result, GnomeKeyring.Result.OK)
        self.assertEqual(items, [id])

    def test_result_str(self):
        '''result_to_message()'''

        self.assertEqual(
            GnomeKeyring.result_to_message(GnomeKeyring.Result.OK), '')
        self.assertEqual(
            type(
                GnomeKeyring.result_to_message(
                    GnomeKeyring.Result.NO_SUCH_KEYRING)), type(''))


#
# main
#

if not GnomeKeyring.is_available():
    print('GNOME keyring not available', file=sys.stderr)
    sys.exit(0)
unittest.main()
    def tearDown(self):
        '''Ensure that we do no leave test keyring behind.'''

        GnomeKeyring.delete_sync(TEST_KEYRING)
    def test_info_unknown(self):
        '''get_info_sync() for unknown keyring'''

        (result,
         info) = GnomeKeyring.get_info_sync(TEST_KEYRING + '_nonexisting')
        self.assertEqual(result, GnomeKeyring.Result.NO_SUCH_KEYRING)
Example #40
0
 def do_activate(self):
     result = GnomeKeyring.unlock_sync("liferea", None)
     if GnomeKeyring.Result.OK != result:
         raise ValueError("Failed to unlock GnomeKeyring, error "+result)
Example #41
0
 def keyring_name(self):
     system_default = GnomeKeyring.get_default_keyring_sync()[1]
     return self.KEYRING_NAME or system_default
Example #42
0
	def __update_info(self):
		"""Update keyring status information"""
		self._info = keyring.get_info_sync(self.KEYRING_NAME)[1]

		# update icon
		self.__update_icon()
Example #43
0
 def delete_all_credentials(self):
     attrs = attributes({"server": self._server, "protocol": self._protocol})
     result, items = GnomeKeyring.find_items_sync(GnomeKeyring.ItemType.NETWORK_PASSWORD, attrs)
     for item in items:
         GnomeKeyring.item_delete_sync(self._keyring, item.item_id)
Example #44
0
	def is_available(self):
		"""Return true if we are able to use Gnome keyring"""
		return keyring is not None and keyring.is_available()
Example #45
0
 def has_any_credentials(self):
     attrs = attributes({"server": self._server, "protocol": self._protocol})
     result, items = GnomeKeyring.find_items_sync(GnomeKeyring.ItemType.NETWORK_PASSWORD, attrs)
     if result in (GnomeKeyring.Result.NO_MATCH, GnomeKeyring.Result.DENIED):
         return False
     return len(items) > 0
Example #46
0
 def do_delete(self, id):
     keyring = GnomeKeyring.get_default_keyring_sync()[1]
     GnomeKeyring.item_delete_sync(keyring, id)
Example #47
0
 def do_activate(self):
     GnomeKeyring.unlock_sync("liferea", None)
Example #48
0
 def do_store(self, id, username, password):
     GnomeKeyring.create_sync("liferea", None)
     attrs = GnomeKeyring.Attribute.list_new()
     GnomeKeyring.Attribute.list_append_string(attrs, 'id', id)
     GnomeKeyring.Attribute.list_append_string(attrs, 'user', username)
     GnomeKeyring.item_create_sync("liferea", GnomeKeyring.ItemType.GENERIC_SECRET, repr(id), attrs, '@@@'.join([username, password]), True)
Example #49
0
def insert_master_key(master_key):
    GnomeKeyring.item_create_sync(KEYRING,
                                  GnomeKeyring.ItemType.GENERIC_SECRET,
                                  'gpwg:masterkey', GLib.Array(), master_key,
                                  1)
Example #50
0
#!/usr/bin/python
# copyright 2012 Florian Ludwig <*****@*****.**>

import os
import socket
from gi.repository import GnomeKeyring, GLib
import glib

import gpwg

SOCKET_PATH = '/tmp/gpwg'
KEYRING = GnomeKeyring.get_default_keyring_sync()[1]


def insert_master_key(master_key):
    GnomeKeyring.item_create_sync(KEYRING,
                                  GnomeKeyring.ItemType.GENERIC_SECRET,
                                  'gpwg:masterkey', GLib.Array(), master_key,
                                  1)


def get_master_key():
    ids = GnomeKeyring.list_item_ids_sync(KEYRING)[1]
    for id in ids:
        info = GnomeKeyring.item_get_info_sync('login', id)[1]
        if info.get_display_name() == 'gpwg:masterkey':
            return info.get_secret()
    return None


def main():