Ejemplo n.º 1
0
def has_item(user, server, protocol):
    try:
        gkey.find_network_password_sync(user = user, server = server, protocol = protocol)
    except gkey.NoMatchError:
        return False

    return True
Ejemplo n.º 2
0
        def keychain_password(user, server, protocol, logger):
            """Gnome: return a keyring password, if it exists.  Otherwise, return
            None.
            """
            #logger.trace('trying Gnome keyring for user="******", server="%s", protocol="%s"\n'
            #             % (user, server, protocol))
            try:
                # http://developer.gnome.org/gnome-keyring/3.5/gnome-keyring
                # -Network-Passwords.html#gnome-keyring-find-network-password-sync
                secret = gnomekeyring.find_network_password_sync(
                    # user, domain=None, server, object=None, protocol,
                    # authtype=None, port=0
                    user,
                    None,
                    server,
                    None,
                    protocol,
                    None,
                    0)

                #logger.trace('got keyring result %s' % str(secret))
            except gnomekeyring.NoMatchError:
                logger.debug(
                    'gnome-keyring does not know password for %s %s %s' %
                    (user, server, protocol))
                return None

            # secret looks like this:
            # [{'protocol': 'imap', 'keyring': 'Default', 'server': 'gmail.com',
            #   'user': '******', 'item_id': 1L, 'password': '******'}]
            if secret and 'password' in secret[0]:
                return secret[0]['password']

            return None
Ejemplo n.º 3
0
    def get(self, user, server, protocol, app):
        try:
            results = gk.find_network_password_sync(user=user, server=server, protocol=protocol)
        except gk.NoMatchError:
            return None

        return results[0]["password"]
Ejemplo n.º 4
0
Archivo: gktool.py Proyecto: ssato/misc
    def find(self, attrs, single=False):
        self.check_attributes(attrs)

        results = []
        try:
            for x in gk.find_network_password_sync(**attrs):
                # x == {'keyring:..., 'item_id':..., 'secret':..., ...}
                x["secret"] = x.get("password")
                x["id"] = x.get("item_id")
                try:
                    x["display_name"] = gk.item_get_info_sync(x["keyring"], x["id"]).get_display_name()
                except gk.DeniedError:
                    raise  # should not happen.

                logging.info(" x = %s" % str(x))
                results.append(x)

                if single:
                    return results

        except gk.NoMatchError:
            pass
        except:
            raise

        return results
Ejemplo n.º 5
0
    def _clean_gnome_keyring(self):
        '''Clean out our test entries from Gnome Keyring'''

        try:
            items = gnomekeyring.find_network_password_sync(
                self.userA, self.service)
            gnomekeyring.item_delete_sync(None, items[0]['item_id'])
        except:
            pass

        try:
            items = gnomekeyring.find_network_password_sync(
                self.userB, self.service)
            gnomekeyring.item_delete_sync(None, items[0]['item_id'])
        except:
            pass
Ejemplo n.º 6
0
        def keychain_password(user, server, protocol, logger):
            """Gnome: return a keyring password, if it exists.  Otherwise, return
            None.
            """
            #logger.trace('trying Gnome keyring for user="******", server="%s", protocol="%s"\n'
            #             % (user, server, protocol))
            try:
                # http://developer.gnome.org/gnome-keyring/3.5/gnome-keyring
                # -Network-Passwords.html#gnome-keyring-find-network-password-sync
                secret = gnomekeyring.find_network_password_sync(
                    # user, domain=None, server, object=None, protocol,
                    # authtype=None, port=0
                    user, None, server, None, protocol, None, 0
                )
                
                #logger.trace('got keyring result %s' % str(secret))
            except gnomekeyring.NoMatchError:
                logger.debug('gnome-keyring does not know password for %s %s %s'
                             % (user, server, protocol))
                return None

            # secret looks like this:
            # [{'protocol': 'imap', 'keyring': 'Default', 'server': 'gmail.com', 
            #   'user': '******', 'item_id': 1L, 'password': '******'}]
            if secret and 'password' in secret[0]:
                return secret[0]['password']

            return None
Ejemplo n.º 7
0
def get_password_from_gnome_keyring(user, server, protocol):
    try:
        results = gnomekeyring.find_network_password_sync(user=user,
                                                          server=server,
                                                          protocol=protocol)
        return results[0]['password']
    except gnomekeyring.NoMatchError:
        return set_password_in_gnome_keyring(user, server, protocol)
def get_keyring_password_for_msmtp_user(user, server):

    try:
        results = gk.find_network_password_sync(user=user, server=server, protocol='smtp')
    except gk.NoMatchError:
        return None

    return results[0]["password"]
Ejemplo n.º 9
0
def get_password_from_gnome_keyring(user, server, protocol):
    try:
        results = gnomekeyring.find_network_password_sync(user=user,
                                                          server=server,
                                                          protocol=protocol)
        return results[0]['password']
    except gnomekeyring.NoMatchError:
        return set_password_in_gnome_keyring(user, server, protocol)
Ejemplo n.º 10
0
	def get_credentials(self, username, handler):
		if username:
			try:
				items = gnomekeyring.find_network_password_sync(username, 'gmail.com', None, None, None, None, 0)
				handler(items[0]['user'], items[0]['password'])
			except gnomekeyring.NoMatchError:
				self.ask_credentials(username, handler)
		else:
			self.ask_credentials(username, handler)
Ejemplo n.º 11
0
def get_password_by_key(key):
    if sys.platform == 'linux2':
        try:
            items = gnomekeyring.find_network_password_sync(key, 'MavensMate: '+key)
            return items[0]['password']
        except gnomekeyring.CancelledError:
            raise MMException('Unable to retrieve password')
    else:
        return keyring.get_password('MavensMate: '+key, key)
Ejemplo n.º 12
0
def get_password_by_key(key):
    if sys.platform == 'linux2':
        try:
            items = gnomekeyring.find_network_password_sync(key, 'MavensMate: '+key)
            return items[0]['password']
        except gnomekeyring.CancelledError:
            raise MMException('Unable to retrieve password')
    else:
        return keyring.get_password('MavensMate: '+key, key)
Ejemplo n.º 13
0
 def find_password(self, scheme, host, username):
     """Return the password of username@root."""
     try:
         res = gnomekeyring.find_network_password_sync(
             username, None, host, None, scheme)
         ring_id = res[0]["keyring"]
         item_id = res[0]["item_id"]
         self.item_ids[(scheme, host, username)] = (ring_id, item_id)
         return res[0]["password"]
     except (gnomekeyring.NoMatchError, gnomekeyring.NoKeyringDaemonError):
         return
Ejemplo n.º 14
0
 def find_password(self, scheme, host, username):
     """Return the password of username@root."""
     try:
         res = gnomekeyring.find_network_password_sync(
             username, None, host, None, scheme)
         ring_id = res[0]["keyring"]
         item_id = res[0]["item_id"]
         self.item_ids[(scheme, host, username)] = (ring_id, item_id)
         return res[0]["password"]
     except (gnomekeyring.NoMatchError, gnomekeyring.NoKeyringDaemonError):
         return
Ejemplo n.º 15
0
    def get_password(self, service, username):
        """Get password of the username for the service
        """
        try:
            items = gnomekeyring.find_network_password_sync(username, service)
        except gnomekeyring.NoMatchError:
            return None
        except gnomekeyring.CancelledError:
            # The user pressed "Cancel" when prompted to unlock their keyring.
            return None

        assert len(items) == 1, 'no more than one entry should ever match'
        return items[0]['password']
Ejemplo n.º 16
0
    def get_password(self, service, username):
        """Get password of the username for the service
        """
        try:
            items = gnomekeyring.find_network_password_sync(username, service)
        except gnomekeyring.NoMatchError:
            return None
        except gnomekeyring.CancelledError:
            # The user pressed "Cancel" when prompted to unlock their keyring.
            return None

        assert len(items) == 1, 'no more than one entry should ever match'
        return items[0]['password']
Ejemplo n.º 17
0
 def get_pass(self, username, server):
     """ Return the password from the keyring. """
     for retries in range(3):
         try:
             results = gk.find_network_password_sync(user=username, server=server,
                                                     protocol=self.protocol)
             return results[0]["password"]
         except gk.NoMatchError:
             print >> sys.stderr, "No password set for user '%s' in server '%s'" % \
                 (username, server)
             return ''
         except gk.IOError as e:
             print >> sys.stderr, "Problem retrieving password: %s" % str(e)
     return ''
Ejemplo n.º 18
0
 def get_pass(self, username, server):
     """ Return the password from the keyring. """
     for retries in range(3):
         try:
             results = gk.find_network_password_sync(user=username,
                                                     server=server,
                                                     protocol=self.protocol)
             return results[0]["password"]
         except gk.NoMatchError:
             print >> sys.stderr, "No password set for user '%s' in server '%s'" % \
                 (username, server)
             return ''
         except gk.IOError as e:
             print >> sys.stderr, "Problem retrieving password: %s" % str(e)
     return ''
Ejemplo n.º 19
0
    def _keyring_data(self, url, user):
        scheme, host, path = self._urlsplit(url)
        try:
            entries = gnomekeyring.find_network_password_sync(protocol=scheme,
                                                              server=host,
                                                              object=path)
        except gnomekeyring.NoMatchError:
            return None

        for entry in entries:
            if 'user' not in entry or 'password' not in entry:
                continue
            if user is None or entry['user'] == user:
                return entry
        return None
Ejemplo n.º 20
0
 def find_password(self, scheme, host, username):
     """Return the password of username@root."""
     try:
         res = gnomekeyring.find_network_password_sync(
             username, None, host, None, scheme)
         ring_id = res[0]["keyring"]
         item_id = res[0]["item_id"]
         self.item_ids[(scheme, host, username)] = (ring_id, item_id)
         return res[0]["password"]
     except (gnomekeyring.NoMatchError, gnomekeyring.NoKeyringDaemonError):
         return
     except gnomekeyring.Error as exc:
         exc_type = "gnomekeyring." + type(exc).__name__
         exc_string = str(exc)
         raise RosieStoreRetrievalError(exc_type, exc_string)
Ejemplo n.º 21
0
def get_password_by_key(key):
    use_keyring = config.connection.get_plugin_client_setting('mm_use_keyring', False)
    if use_keyring:
        if sys.platform == 'linux2':
            try:
                items = gnomekeyring.find_network_password_sync(key, 'MavensMate: '+key)
                return items[0]['password']
            except gnomekeyring.CancelledError:
                raise MMException('Unable to retrieve password')
        else:
            return keyring.get_password('MavensMate: '+key, key)
    else: #not recommend! we only use this for CI
        file_body = get_file_as_string(os.path.join(config.connection.get_app_settings_directory(),key+'.json'))
        file_body_json = json.loads(file_body)
        return decode(str(key), str(file_body_json['value']))
    def delpass(self, username, server):
        ret = True
        # Does it already exist?
        protocol = self.get_protocol()
        try:
            results = gk.find_network_password_sync(user=username, server=server, protocol=protocol)
        except gk.NoMatchError:
            print "No password set for user '%s' in server '%s'" % (username, server)
            ret = False

        if ret:
            gk.item_delete_sync(self.keyring, results[0]['item_id'])
            print "Password successfully removed"

        return ret
Ejemplo n.º 23
0
    def delpass(self, username, server):
        ret = True
        # Does it already exist?
        protocol = self.get_protocol()
        try:
            results = gk.find_network_password_sync(user=username, server=server, protocol=protocol)
        except gk.NoMatchError:
            print "No password set for user '%s' in server '%s'" % (username, server)
            ret = False

        if ret:
            gk.item_delete_sync(self.keyring, results[0]['item_id'])
            print "Password successfully removed"

        return ret
Ejemplo n.º 24
0
 def find_password(self, scheme, host, username):
     """Return the password of username@root."""
     try:
         res = gnomekeyring.find_network_password_sync(
             username, None, host, None, scheme)
         ring_id = res[0]["keyring"]
         item_id = res[0]["item_id"]
         self.item_ids[(scheme, host, username)] = (ring_id, item_id)
         return res[0]["password"]
     except (gnomekeyring.NoMatchError, gnomekeyring.NoKeyringDaemonError):
         return
     except gnomekeyring.Error as exc:
         exc_type = "gnomekeyring." + type(exc).__name__
         exc_string = str(exc)
         raise RosieStoreRetrievalError(exc_type, exc_string)
Ejemplo n.º 25
0
def get_password(**kwargs):
    try:
        ret = gkey.find_network_password_sync(**kwargs)
    except gkey.NoMatchError:
        raise NoPasswordError()
    except gkey.IOError:
        # Can't communicate with the gnome-keyring daemon
        # (For example, it isn't running, or the GNOME_KEYRING_CONTROL
        # environment variable isn't set.)
        raise PasswordError('unable to communicate with the gnome-keyring '
                            'daemon')

    if not ret:
        raise NoPasswordError()
    elif len(ret) != 1:
        raise PasswordError('expected exactly 1 password, found %d', len(ret))

    return ret[0].get('password')
Ejemplo n.º 26
0
	def get_password(self, key, _folder = None):
		if not G.is_available() : return None
		folder = to_unicode(_folder) if _folder else self.appletName
		item_list = G.list_item_ids_sync(self.appletName)
		password = None
		# ♿ ☟ GnomeKeyring is glitch at find_network_password_sync
		i = 0
		_items = None
		while i < 10 :
			try :
				_items = G.find_network_password_sync(to_unicode(key), folder)
				break
			except G.CancelledError :
				i+=1
			except G.NoMatchError :
				i+=1
			finally : pass
		# ♿ ☝ GnomeKeyring is glitch at find_network_password_sync
		if _items :
			for item in _items :
				if item['keyring']==self.appletName :
					password = item['password']
					break
		return password
Ejemplo n.º 27
0
def get_username(server):
    pwdata = gkey.find_network_password_sync(server=server, protocol="imap")[0]
    return pwdata["user"]
Ejemplo n.º 28
0
#! /usr/bin/python

import gobject, gnomekeyring, pprint

from optparse import OptionParser
parser = OptionParser(add_help_option=False)
parser.add_option("-u", "--user", dest="user",
                  help="The user name", metavar="USER")
parser.add_option("-s", "--server", dest="server",
                  help="The server", metavar="SERVER")
parser.add_option("-c", "--protocol", dest="protocol",
                  help="The protocol", metavar="PROTOCOL")
parser.add_option("-?", "--help", action="help", help="show this help message and exit")

(options, args) = parser.parse_args()

gobject.set_application_name("keyring-utils")

keys = gnomekeyring.find_network_password_sync(user=options.user,
                                              server=options.server,
                                              protocol=options.protocol)
pprint.pprint(keys)
Ejemplo n.º 29
0
 def _get_password_from_keyring(self):
     try:
         results = gnomekeyring.find_network_password_sync(user=self.username, server="twitter.com", protocol="http")
     except gnomekeyring.NoMatchError:
         return None
     return results[0]["password"]
Ejemplo n.º 30
0
def keyring(user,host):
  keys = gnomekeyring.find_network_password_sync(user=user, server=host)
  # First one will do nicely thanks
  return keys[0]["password"]
Ejemplo n.º 31
0
Archivo: conf.py Proyecto: cav71/osc
def get_config(override_conffile=None,
               override_apiurl=None,
               override_debug=None,
               override_http_debug=None,
               override_http_full_debug=None,
               override_traceback=None,
               override_post_mortem=None,
               override_no_keyring=None,
               override_no_gnome_keyring=None,
               override_verbose=None):
    """do the actual work (see module documentation)"""
    global config

    conffile = override_conffile or os.environ.get('OSC_CONFIG', '~/.oscrc')
    conffile = os.path.expanduser(conffile)

    if not os.path.exists(conffile):
        raise oscerr.NoConfigfile(conffile, \
                                  account_not_configured_text % conffile)

    # okay, we made sure that .oscrc exists

    # make sure it is not world readable, it may contain a password.
    os.chmod(conffile, 0o600)

    cp = get_configParser(conffile)

    if not cp.has_section('general'):
        # FIXME: it might be sufficient to just assume defaults?
        msg = config_incomplete_text % conffile
        msg += new_conf_template % DEFAULTS
        raise oscerr.ConfigError(msg, conffile)

    config = dict(cp.items('general', raw=1))
    config['conffile'] = conffile

    for i in boolean_opts:
        try:
            config[i] = cp.getboolean('general', i)
        except ValueError as e:
            raise oscerr.ConfigError('cannot parse \'%s\' setting: ' % i + str(e), conffile)

    config['packagecachedir'] = os.path.expanduser(config['packagecachedir'])
    config['exclude_glob'] = config['exclude_glob'].split()

    re_clist = re.compile('[, ]+')
    config['extra-pkgs'] = [i.strip() for i in re_clist.split(config['extra-pkgs'].strip()) if i]

    # collect the usernames, passwords and additional options for each api host
    api_host_options = {}

    # Regexp to split extra http headers into a dictionary
    # the text to be matched looks essentially looks this:
    # "Attribute1: value1, Attribute2: value2, ..."
    # there may be arbitray leading and intermitting whitespace.
    # the following regexp does _not_ support quoted commas within the value.
    http_header_regexp = re.compile(r"\s*(.*?)\s*:\s*(.*?)\s*(?:,\s*|\Z)")

    # override values which we were called with
    # This needs to be done before processing API sections as it might be already used there
    if override_no_keyring:
        config['use_keyring'] = False
    if override_no_gnome_keyring:
        config['gnome_keyring'] = False

    aliases = {}
    for url in [x for x in cp.sections() if x != 'general']:
        # backward compatiblity
        scheme, host, path = parse_apisrv_url(config.get('scheme', 'https'), url)
        apiurl = urljoin(scheme, host, path)
        user = None
        password = None
        if config['use_keyring'] and GENERIC_KEYRING:
            try:
                # Read from keyring lib if available
                user = cp.get(url, 'user', raw=True)
                password = str(keyring.get_password(host, user))
            except:
                # Fallback to file based auth.
                pass
        elif config['gnome_keyring'] and GNOME_KEYRING:
            # Read from gnome keyring if available
            try:
                gk_data = gnomekeyring.find_network_password_sync(protocol=scheme, server=host, object=path)
                if not 'user' in gk_data[0]:
                    raise oscerr.ConfigError('no user found in keyring', conffile)
                user = gk_data[0]['user']
                if 'password' in gk_data[0]:
                    password = str(gk_data[0]['password'])
                else:
                    # this is most likely an error
                    print('warning: no password found in keyring', file=sys.stderr)
            except gnomekeyring.NoMatchError:
                # Fallback to file based auth.
                pass

        if not user is None and len(user) == 0:
            user = None
            print('Warning: blank user in the keyring for the ' \
                'apiurl %s.\nPlease fix your keyring entry.', file=sys.stderr)

        if user is not None and password is None:
            err = ('no password defined for "%s".\nPlease fix your keyring '
                   'entry or gnome-keyring setup.\nAssuming an empty password.'
                   % url)
            print(err, file=sys.stderr)
            password = ''

        # Read credentials from config
        if user is None:
            #FIXME: this could actually be the ideal spot to take defaults
            #from the general section.
            user = cp.get(url, 'user', raw=True)        # need to set raw to prevent '%' expansion
            password = cp.get(url, 'pass', raw=True)    # especially on password!
            try:
                passwordx = passx_decode(cp.get(url, 'passx', raw=True))  # especially on password!
            except:
                passwordx = ''

            if password == None or password == 'your_password':
                password = ''

            if user is None or user == '':
                raise oscerr.ConfigError('user is blank for %s, please delete or complete the "user=" entry in %s.' % (apiurl, config['conffile']), config['conffile'])

            if config['plaintext_passwd'] and passwordx or not config['plaintext_passwd'] and password:
                if config['plaintext_passwd']:
                    if password != passwordx:
                        print('%s: rewriting from encoded pass to plain pass' % url, file=sys.stderr)
                    add_section(conffile, url, user, passwordx)
                    password = passwordx
                else:
                    if password != passwordx:
                        print('%s: rewriting from plain pass to encoded pass' % url, file=sys.stderr)
                    add_section(conffile, url, user, password)

            if not config['plaintext_passwd']:
                password = passwordx

        if cp.has_option(url, 'http_headers'):
            http_headers = cp.get(url, 'http_headers')
            http_headers = http_header_regexp.findall(http_headers)
        else:
            http_headers = []
        if cp.has_option(url, 'aliases'):
            for i in cp.get(url, 'aliases').split(','):
                key = i.strip()
                if key == '':
                    continue
                if key in aliases:
                    msg = 'duplicate alias entry: \'%s\' is already used for another apiurl' % key
                    raise oscerr.ConfigError(msg, conffile)
                aliases[key] = url

        api_host_options[apiurl] = {'user': user,
                                    'pass': password,
                                    'http_headers': http_headers}

        optional = ('email', 'sslcertck', 'cafile', 'capath')
        for key in optional:
            if cp.has_option(url, key):
                if key == 'sslcertck':
                    api_host_options[apiurl][key] = cp.getboolean(url, key)
                else:
                    api_host_options[apiurl][key] = cp.get(url, key)
        if cp.has_option(url, 'build-root', proper=True):
            api_host_options[apiurl]['build-root'] = cp.get(url, 'build-root', raw=True)

        if not 'sslcertck' in api_host_options[apiurl]:
            api_host_options[apiurl]['sslcertck'] = True

        if scheme == 'http':
            api_host_options[apiurl]['sslcertck'] = False

        if cp.has_option(url, 'trusted_prj'):
            api_host_options[apiurl]['trusted_prj'] = cp.get(url, 'trusted_prj').split(' ')
        else:
            api_host_options[apiurl]['trusted_prj'] = []

    # add the auth data we collected to the config dict
    config['api_host_options'] = api_host_options
    config['apiurl_aliases'] = aliases

    apiurl = aliases.get(config['apiurl'], config['apiurl'])
    config['apiurl'] = urljoin(*parse_apisrv_url(None, apiurl))
    # backward compatibility
    if 'apisrv' in config:
        apisrv = config['apisrv'].lstrip('http://')
        apisrv = apisrv.lstrip('https://')
        scheme = config.get('scheme', 'https')
        config['apiurl'] = urljoin(scheme, apisrv)
    if 'apisrc' in config or 'scheme' in config:
        print('Warning: Use of the \'scheme\' or \'apisrv\' in ~/.oscrc is deprecated!\n' \
                            'Warning: See README for migration details.', file=sys.stderr)
    if 'build_platform' in config:
        print('Warning: Use of \'build_platform\' config option is deprecated! (use \'build_repository\' instead)', file=sys.stderr)
        config['build_repository'] = config['build_platform']

    config['verbose'] = int(config['verbose'])
    # override values which we were called with
    if override_verbose:
        config['verbose'] = override_verbose + 1

    if override_debug:
        config['debug'] = override_debug
    if override_http_debug:
        config['http_debug'] = override_http_debug
    if override_http_full_debug:
        config['http_debug'] = override_http_full_debug or config['http_debug']
        config['http_full_debug'] = override_http_full_debug
    if override_traceback:
        config['traceback'] = override_traceback
    if override_post_mortem:
        config['post_mortem'] = override_post_mortem
    if override_apiurl:
        apiurl = aliases.get(override_apiurl, override_apiurl)
        # check if apiurl is a valid url
        config['apiurl'] = urljoin(*parse_apisrv_url(None, apiurl))

    # XXX unless config['user'] goes away (and is replaced with a handy function, or
    # config becomes an object, even better), set the global 'user' here as well,
    # provided that there _are_ credentials for the chosen apiurl:
    try:
        config['user'] = get_apiurl_usr(config['apiurl'])
    except oscerr.ConfigMissingApiurl as e:
        e.msg = config_missing_apiurl_text % config['apiurl']
        e.file = conffile
        raise e

    # finally, initialize urllib2 for to use the credentials for Basic Authentication
    init_basicauth(config)
Ejemplo n.º 32
0
    'django.contrib.sitemaps',
    'news',
    'wammu',
    'downloads',
    'screenshots',
    'links',
    'manpages',
    'phonedb',
)

import gobject
import gnomekeyring
gobject.set_application_name('Wammu-web')
IDENTICA_USER = '******'
IDENTICA_PASSWORD = gnomekeyring.find_network_password_sync(
        user = IDENTICA_USER,
        domain = 'identi.ca',
        protocol = 'https')[0]['password']

NEWS_PER_PAGE = 5
NEWS_ON_MAIN_PAGE = 5
NEWS_ON_PRODUCT_PAGE = 2
NEWS_IN_RSS = 10
SCREENSHOTS_PER_PAGE = 20
PHONES_PER_PAGE = 50
PHONES_ON_INDEX = 10
PHONES_ON_MAIN_PAGE = 5
PHONES_IN_RSS = 10

PAYPAL_IDENTITY_TOKEN = '1kbDRn7TJ6ikJcqyxZ8AdOUMMT56S7gm8mq3OIHZTFS8ymCulm6IGMW70zu'
PAYPAL_RECEIVER_EMAIL = '*****@*****.**'
THUMBNAIL_SIZE = (180, 180)
Ejemplo n.º 33
0
def get_config(override_conffile=None,
               override_apiurl=None,
               override_debug=None,
               override_http_debug=None,
               override_http_full_debug=None,
               override_traceback=None,
               override_post_mortem=None,
               override_no_keyring=None,
               override_no_gnome_keyring=None,
               override_verbose=None):
    """do the actual work (see module documentation)"""
    global config

    conffile = override_conffile or os.environ.get('OSC_CONFIG', '~/.oscrc')
    conffile = os.path.expanduser(conffile)

    if not os.path.exists(conffile):
        raise oscerr.NoConfigfile(conffile, \
                                  account_not_configured_text % conffile)

    # okay, we made sure that .oscrc exists

    # make sure it is not world readable, it may contain a password.
    os.chmod(conffile, 0o600)

    cp = get_configParser(conffile)

    if not cp.has_section('general'):
        # FIXME: it might be sufficient to just assume defaults?
        msg = config_incomplete_text % conffile
        msg += new_conf_template % DEFAULTS
        raise oscerr.ConfigError(msg, conffile)

    config = dict(cp.items('general', raw=1))
    config['conffile'] = conffile

    for i in boolean_opts:
        try:
            config[i] = cp.getboolean('general', i)
        except ValueError as e:
            raise oscerr.ConfigError(
                'cannot parse \'%s\' setting: ' % i + str(e), conffile)

    config['packagecachedir'] = os.path.expanduser(config['packagecachedir'])
    config['exclude_glob'] = config['exclude_glob'].split()

    re_clist = re.compile('[, ]+')
    config['extra-pkgs'] = [
        i.strip() for i in re_clist.split(config['extra-pkgs'].strip()) if i
    ]

    # collect the usernames, passwords and additional options for each api host
    api_host_options = {}

    # Regexp to split extra http headers into a dictionary
    # the text to be matched looks essentially looks this:
    # "Attribute1: value1, Attribute2: value2, ..."
    # there may be arbitray leading and intermitting whitespace.
    # the following regexp does _not_ support quoted commas within the value.
    http_header_regexp = re.compile(r"\s*(.*?)\s*:\s*(.*?)\s*(?:,\s*|\Z)")

    # override values which we were called with
    # This needs to be done before processing API sections as it might be already used there
    if override_no_keyring:
        config['use_keyring'] = False
    if override_no_gnome_keyring:
        config['gnome_keyring'] = False

    aliases = {}
    for url in [x for x in cp.sections() if x != 'general']:
        # backward compatiblity
        scheme, host, path = parse_apisrv_url(config.get('scheme', 'https'),
                                              url)
        apiurl = urljoin(scheme, host, path)
        user = None
        password = None
        if config['use_keyring'] and GENERIC_KEYRING:
            try:
                # Read from keyring lib if available
                user = cp.get(url, 'user', raw=True)
                password = str(keyring.get_password(host, user))
            except:
                # Fallback to file based auth.
                pass
        elif config['gnome_keyring'] and GNOME_KEYRING:
            # Read from gnome keyring if available
            try:
                gk_data = gnomekeyring.find_network_password_sync(
                    protocol=scheme, server=host, object=path)
                if not 'user' in gk_data[0]:
                    raise oscerr.ConfigError('no user found in keyring',
                                             conffile)
                user = gk_data[0]['user']
                if 'password' in gk_data[0]:
                    password = str(gk_data[0]['password'])
                else:
                    # this is most likely an error
                    print('warning: no password found in keyring',
                          file=sys.stderr)
            except gnomekeyring.NoMatchError:
                # Fallback to file based auth.
                pass

        if not user is None and len(user) == 0:
            user = None
            print('Warning: blank user in the keyring for the ' \
                'apiurl %s.\nPlease fix your keyring entry.', file=sys.stderr)

        if user is not None and password is None:
            err = (
                'no password defined for "%s".\nPlease fix your keyring '
                'entry or gnome-keyring setup.\nAssuming an empty password.' %
                url)
            print(err, file=sys.stderr)
            password = ''

        # Read credentials from config
        if user is None:
            #FIXME: this could actually be the ideal spot to take defaults
            #from the general section.
            user = cp.get(url, 'user',
                          raw=True)  # need to set raw to prevent '%' expansion
            password = cp.get(url, 'pass', raw=True)  # especially on password!
            try:
                passwordx = passx_decode(cp.get(
                    url, 'passx', raw=True))  # especially on password!
            except:
                passwordx = ''

            if password == None or password == 'your_password':
                password = ''

            if user is None or user == '':
                raise oscerr.ConfigError(
                    'user is blank for %s, please delete or complete the "user=" entry in %s.'
                    % (apiurl, config['conffile']), config['conffile'])

            if config['plaintext_passwd'] and passwordx or not config[
                    'plaintext_passwd'] and password:
                if config['plaintext_passwd']:
                    if password != passwordx:
                        print('%s: rewriting from encoded pass to plain pass' %
                              url,
                              file=sys.stderr)
                    add_section(conffile, url, user, passwordx)
                    password = passwordx
                else:
                    if password != passwordx:
                        print('%s: rewriting from plain pass to encoded pass' %
                              url,
                              file=sys.stderr)
                    add_section(conffile, url, user, password)

            if not config['plaintext_passwd']:
                password = passwordx

        if cp.has_option(url, 'http_headers'):
            http_headers = cp.get(url, 'http_headers')
            http_headers = http_header_regexp.findall(http_headers)
        else:
            http_headers = []
        if cp.has_option(url, 'aliases'):
            for i in cp.get(url, 'aliases').split(','):
                key = i.strip()
                if key == '':
                    continue
                if key in aliases:
                    msg = 'duplicate alias entry: \'%s\' is already used for another apiurl' % key
                    raise oscerr.ConfigError(msg, conffile)
                aliases[key] = url

        api_host_options[apiurl] = {
            'user': user,
            'pass': password,
            'http_headers': http_headers
        }

        optional = ('email', 'sslcertck', 'cafile', 'capath')
        for key in optional:
            if cp.has_option(url, key):
                if key == 'sslcertck':
                    api_host_options[apiurl][key] = cp.getboolean(url, key)
                else:
                    api_host_options[apiurl][key] = cp.get(url, key)
        if cp.has_option(url, 'build-root', proper=True):
            api_host_options[apiurl]['build-root'] = cp.get(url,
                                                            'build-root',
                                                            raw=True)

        if not 'sslcertck' in api_host_options[apiurl]:
            api_host_options[apiurl]['sslcertck'] = True

        if scheme == 'http':
            api_host_options[apiurl]['sslcertck'] = False

        if cp.has_option(url, 'trusted_prj'):
            api_host_options[apiurl]['trusted_prj'] = cp.get(
                url, 'trusted_prj').split(' ')
        else:
            api_host_options[apiurl]['trusted_prj'] = []

    # add the auth data we collected to the config dict
    config['api_host_options'] = api_host_options
    config['apiurl_aliases'] = aliases

    apiurl = aliases.get(config['apiurl'], config['apiurl'])
    config['apiurl'] = urljoin(*parse_apisrv_url(None, apiurl))
    # backward compatibility
    if 'apisrv' in config:
        apisrv = config['apisrv'].lstrip('http://')
        apisrv = apisrv.lstrip('https://')
        scheme = config.get('scheme', 'https')
        config['apiurl'] = urljoin(scheme, apisrv)
    if 'apisrc' in config or 'scheme' in config:
        print('Warning: Use of the \'scheme\' or \'apisrv\' in ~/.oscrc is deprecated!\n' \
                            'Warning: See README for migration details.', file=sys.stderr)
    if 'build_platform' in config:
        print(
            'Warning: Use of \'build_platform\' config option is deprecated! (use \'build_repository\' instead)',
            file=sys.stderr)
        config['build_repository'] = config['build_platform']

    config['verbose'] = int(config['verbose'])
    # override values which we were called with
    if override_verbose:
        config['verbose'] = override_verbose + 1

    if override_debug:
        config['debug'] = override_debug
    if override_http_debug:
        config['http_debug'] = override_http_debug
    if override_http_full_debug:
        config['http_debug'] = override_http_full_debug or config['http_debug']
        config['http_full_debug'] = override_http_full_debug
    if override_traceback:
        config['traceback'] = override_traceback
    if override_post_mortem:
        config['post_mortem'] = override_post_mortem
    if override_apiurl:
        apiurl = aliases.get(override_apiurl, override_apiurl)
        # check if apiurl is a valid url
        config['apiurl'] = urljoin(*parse_apisrv_url(None, apiurl))

    # XXX unless config['user'] goes away (and is replaced with a handy function, or
    # config becomes an object, even better), set the global 'user' here as well,
    # provided that there _are_ credentials for the chosen apiurl:
    try:
        config['user'] = get_apiurl_usr(config['apiurl'])
    except oscerr.ConfigMissingApiurl as e:
        e.msg = config_missing_apiurl_text % config['apiurl']
        e.file = conffile
        raise e

    # finally, initialize urllib2 for to use the credentials for Basic Authentication
    init_basicauth(config)
Ejemplo n.º 34
0
#   source "~/bin/mutt-gnome-keyring-password.py yourusername your.imap.server imap"|
#
# Note the trailing | character in the last line!
#
# This script was inspired by a similar hack for offlineimap by Ross Burton:
# http://burtonini.com/blog/computers/offlineimap-2008-11-04-20-00
#

import sys
import gobject
import gnomekeyring


try:
    user, server, protocol = sys.argv[1:]
except ValueError as e:
    print 'Error parsing arguments: %s' % (e,)
    print 'Usage: %s USERNAME SERVERNAME PROTOCOL' % (sys.argv[0],)
    sys.exit(1)

gobject.set_application_name('Mutt')

try:
    q = dict(user=user, server=server, protocol=protocol)
    keys = gnomekeyring.find_network_password_sync(**q)
    password = keys[0]["password"].replace('"', r'\"')
    print 'set imap_pass = "******"' % (password,)
    print 'set smtp_pass = "******"' % (password,)
except (gnomekeyring.NoMatchError, gnomekeyring.IOError), e:
    pass
Ejemplo n.º 35
0
Archivo: conf.py Proyecto: myMeow/osc
        # backward compatiblity
        scheme, host = parse_apisrv_url(config.get("scheme", "https"), url)
        apiurl = urljoin(scheme, host)
        user = None
        if config["use_keyring"] and GENERIC_KEYRING:
            try:
                # Read from keyring lib if available
                user = cp.get(url, "user", raw=True)
                password = keyring.get_password(host, user)
            except:
                # Fallback to file based auth.
                pass
        elif config["gnome_keyring"] and GNOME_KEYRING:
            # Read from gnome keyring if available
            try:
                gk_data = gnomekeyring.find_network_password_sync(protocol=scheme, server=host)
                if not "user" in gk_data[0]:
                    raise oscerr.ConfigError("no user found in keyring", conffile)
                user = gk_data[0]["user"]
                if "password" in gk_data[0]:
                    password = gk_data[0]["password"]
                else:
                    # this is most likely an error
                    print >> sys.stderr, "warning: no password found in keyring"
            except gnomekeyring.NoMatchError:
                # Fallback to file based auth.
                pass

        if not user is None and len(user) == 0:
            user = None
            print >> sys.stderr, "Warning: blank user in the keyring for the " "apiurl %s.\nPlease fix your keyring entry."
Ejemplo n.º 36
0
Archivo: conf.py Proyecto: stskeeps/osc
        # backward compatiblity
        scheme, host = parse_apisrv_url(config.get('scheme', 'https'), url)
        apiurl = urljoin(scheme, host)
        user = None
        if config['use_keyring'] and GENERIC_KEYRING:
            try:
                # Read from keyring lib if available
                user = cp.get(url, 'user', raw=True)
                password = keyring.get_password(host, user)
            except:
                # Fallback to file based auth.
                pass
        elif config['gnome_keyring'] and GNOME_KEYRING:
            # Read from gnome keyring if available
            try:
                gk_data = gnomekeyring.find_network_password_sync(protocol=scheme, server=host)
                password = gk_data[0]['password']
                user = gk_data[0]['user']
            except gnomekeyring.NoMatchError:
                # Fallback to file based auth.
                pass

        if not user is None and len(user) == 0:
            user = None
            print >>sys.stderr, 'Warning: blank user in the keyring for the ' \
                'apiurl %s.\nPlease fix your keyring entry.'

        # Read credentials from config
        if user is None:
            #FIXME: this could actually be the ideal spot to take defaults
            #from the general section.
Ejemplo n.º 37
0
def get_username(server):
    pwdata = gkey.find_network_password_sync(server=server, protocol='imap')[0]
    return pwdata['user']
Ejemplo n.º 38
0
#   set imap_user = "******"
#   source "~/bin/mutt-gnome-keyring-password.py yourusername your.imap.server imap"|
#
# Note the trailing | character in the last line!
#
# This script was inspired by a similar hack for offlineimap by Ross Burton:
# http://burtonini.com/blog/computers/offlineimap-2008-11-04-20-00
#

import sys
import gobject
import gnomekeyring


try:
    user, server, protocol = sys.argv[1:]
except ValueError as e:
    print 'Error parsing arguments: %s' % (e,)
    print 'Usage: %s USERNAME SERVERNAME PROTOCOL' % (sys.argv[0],)
    sys.exit(1)

gobject.set_application_name('Mutt')

try:
    q = dict(user=user, server=server, protocol=protocol)
    keys = gnomekeyring.find_network_password_sync(**q)
    password = keys[0]["password"].replace('"', r'\"')
    print 'set imap_pass = "******"' % (password,)
except (gnomekeyring.NoMatchError, gnomekeyring.IOError), e:
    pass
Ejemplo n.º 39
0
def del_item(user, server, protocol):
    results = gkey.find_network_password_sync(user = username,
                                              server = server,
                                              protocol = protocol)

    gkey.item_delete_sync(keyring, results[0]['item_id'])
Ejemplo n.º 40
0
def getpass(user, server, protocol):
    r = gk.find_network_password_sync(user=user, server=server,
                                      protocol=protocol)
    return r[0]['password']