Ejemplo n.º 1
0
    def __call__(self):
        """ Important registery parameters are the 'dest_authlogin' and
        'dest_authpassword' used to contact the authentification ldap based
        system.
        """
        # Small hack copied from the trustedauth cube to make sure the secret
        # key file is loaded on both sides of cw (repo and web)
        secretfile = self.repo.vreg.config.get(KEYCONFENTRY) or ""
        secretfile = secretfile.strip()
        if not secretfile:
            raise ConfigurationError("Configuration '%s' is missing or empty. "
                                     "Please check your configuration file!" %
                                     KEYCONFENTRY)
        set_secret(self.repo.vreg.config, secretfile)

        # Make sure a login and password is provided to contact the external
        # sources on both sides of cw (repo and web)
        cyphr = build_cypher(self.repo.vreg.config._secret)
        src_file = self.repo.vreg.config.get(KEYINPUTSRC) or ""
        src_file = src_file.strip()
        if not src_file:
            raise ConfigurationError("Configuration '%s' is missing or empty. "
                                     "Please check your configuration file!" %
                                     KEYINPUTSRC)
        src_login, src_password, src_url, src_config = load_source_config(
            src_file)
        self.repo.vreg.src_authlogin = base64.encodestring(
            cyphr.encrypt("%128s" % src_login))
        self.repo.vreg.src_authpassword = base64.encodestring(
            cyphr.encrypt("%128s" % src_password))
        dest_file = self.repo.vreg.config.get(KEYOUTPUTSRC) or ""
        dest_file = dest_file.strip()
        if not dest_file:
            raise ConfigurationError("Configuration '%s' is missing or empty. "
                                     "Please check your configuration file!" %
                                     KEYOUTPUTSRC)
        dest_login, dest_password, dest_url, dest_config = load_source_config(
            dest_file)
        self.repo.vreg.dest_authlogin = base64.encodestring(
            cyphr.encrypt("%128s" % dest_login))
        self.repo.vreg.dest_authpassword = base64.encodestring(
            cyphr.encrypt("%128s" % dest_password))

        # Create or update source
        with self.repo.internal_cnx() as cnx:
            _create_or_update_ldap_data_source(cnx,
                                               src_url,
                                               src_config,
                                               dest_url,
                                               dest_config,
                                               update=True)

        # Check if the source are active or not
        if self.repo.vreg.config.get(KEYDISABLEENTRY, False):
            LDAPFeedSource.disabled = True
Ejemplo n.º 2
0
def set_secret(config, secretfile):
    """ Set a '_secret' config parameter with the 32 bytes key available in the
    'registration-cypher-seed' configuration file.
    """
    try:
        secret = open(secretfile).read().strip()
    except IOError:
        raise ConfigurationError(
            "Cannot open secret key file. Check your configuration file!")
        return
    if not secret or len(secret) > 32:
        raise ConfigurationError(
            "Secret key must me a string 0 < len(key) <= 32.")
    config._secret = secret.ljust(32, "#")
Ejemplo n.º 3
0
 def run(self, args):
     check_options_consistency(self.config)
     print('\n' + underline_title('Initializing the system database'))
     from cubicweb.server import init_repository
     appid = args[0]
     config = ServerConfiguration.config_for(appid)
     try:
         system = config.system_source_config
         extra_args = system.get('db-extra-arguments')
         extra = extra_args and {'extra_args': extra_args} or {}
         get_connection(system['db-driver'],
                        database=system['db-name'],
                        host=system.get('db-host'),
                        port=system.get('db-port'),
                        user=system.get('db-user') or '',
                        password=system.get('db-password') or '',
                        schema=system.get('db-namespace'),
                        **extra)
     except Exception as ex:
         raise ConfigurationError(
             'You seem to have provided wrong connection information in '
             'the %s file. Resolve this first (error: %s).' %
             (config.sources_file(), str(ex).strip()))
     init_repository(config, drop=self.config.drop)
     if not self.config.automatic:
         while ASK.confirm('Enter another source ?', default_is_yes=False):
             CWCTL.run([
                 'source-add', '--config-level',
                 str(self.config.config_level), config.appid
             ])
Ejemplo n.º 4
0
def configuration_cls(name):
    """return the configuration class registered with the given name"""
    try:
        return [c for c in CONFIGURATIONS if c.name == name][0]
    except IndexError:
        raise ConfigurationError(
            'no such config %r (check it exists with "cubicweb-ctl list")' %
            name)
Ejemplo n.º 5
0
 def instance_home(cls, appid):
     """return the home directory of the instance with the given
     instance id
     """
     home = join(cls.instances_dir(), appid)
     if not exists(home):
         raise ConfigurationError('no such instance %s (check it exists with'
                                  ' "cubicweb-ctl list")' % appid)
     return home
Ejemplo n.º 6
0
def guess_configuration(directory):
    """try to guess the configuration to use for a directory. If multiple
    configurations are found, ConfigurationError is raised
    """
    modes = possible_configurations(directory)
    if len(modes) != 1:
        raise ConfigurationError('unable to guess configuration from %r %s'
                                 % (directory, modes))
    return modes[0]
Ejemplo n.º 7
0
 def configure_instance(self, appid):
     if self.config.param is not None:
         appcfg = self.cwconfig
         for key, value in self.config.param.items():
             try:
                 appcfg.global_set_option(key, value)
             except KeyError:
                 raise ConfigurationError(
                     'unknown configuration key "%s" for mode %s' % (key, appcfg.name))
         appcfg.save()
Ejemplo n.º 8
0
 def cube_dir(cls, cube):
     """return the cube directory for the given cube id, raise
     `ConfigurationError` if it doesn't exist
     """
     pkgname = _cube_pkgname(cube)
     loader = pkgutil.find_loader(pkgname)
     if loader:
         return dirname(loader.get_filename())
     msg = 'no module %(pkg)s in search path nor cube %(cube)r in %(path)s'
     raise ConfigurationError(msg % {'cube': cube,
                                     'pkg': _cube_pkgname(cube)})
Ejemplo n.º 9
0
    def __init__(self, source_config, repairing=False):
        try:
            self.dbdriver = source_config['db-driver'].lower()
            dbname = source_config['db-name']
        except KeyError as e:
            raise ConfigurationError(
                'missing some expected entries in sources file (do you have '
                'a db-driver and a db-name keys?), error: %s' % e)

        dbhost = source_config.get('db-host')
        port = source_config.get('db-port')
        dbport = port and int(port) or None
        dbuser = source_config.get('db-user')
        dbpassword = source_config.get('db-password')
        dbencoding = source_config.get('db-encoding', 'UTF-8')
        dbextraargs = source_config.get('db-extra-arguments')
        dbnamespace = source_config.get('db-namespace')

        self.dbhelper = logilab_database.get_db_helper(self.dbdriver)
        self.dbhelper.record_connection_info(dbname, dbhost, dbport, dbuser,
                                             dbpassword, dbextraargs,
                                             dbencoding, dbnamespace)
        self.sqlgen = SQLGenerator()

        # copy back some commonly accessed attributes
        dbapi_module = self.dbhelper.dbapi_module
        self.OperationalError = dbapi_module.OperationalError
        self.InterfaceError = dbapi_module.InterfaceError
        self.DbapiError = dbapi_module.Error
        self._binary = self.dbhelper.binary_value
        self._process_value = dbapi_module.process_value
        self._dbencoding = dbencoding

        if self.dbdriver == 'sqlite':
            self.cnx_wrap = SqliteConnectionWrapper
            self.dbhelper.dbname = abspath(self.dbhelper.dbname)
        else:
            self.cnx_wrap = ConnectionWrapper

        if not repairing:
            statement_timeout = int(
                source_config.get('db-statement-timeout', 0))

            if statement_timeout > 0:

                def set_postgres_timeout(cnx):
                    cnx.cursor().execute('SET statement_timeout to %d' %
                                         statement_timeout)
                    cnx.commit()

                postgres_hooks = SQL_CONNECT_HOOKS['postgres']
                postgres_hooks.append(set_postgres_timeout)
Ejemplo n.º 10
0
 def config_helper(self, config, required=True, cmdname=None):
     if cmdname is None:
         cmdname = self.name
     for helpercls in _HDLRS.get(cmdname, ()):
         if helpercls.cfgname == config.name:
             return helpercls(config)
     if config.name == 'all-in-one':
         for helpercls in _HDLRS.get(cmdname, ()):
             if helpercls.cfgname == 'repository':
                 return helpercls(config)
     if required:
         msg = 'No helper for command %s using %s configuration' % (
             cmdname, config.name)
         raise ConfigurationError(msg)
Ejemplo n.º 11
0
    def anonymous_user(self):
        """return a login and password to use for anonymous users.

        None may be returned for both if anonymous connection is not
        allowed or if an empty login is used in configuration
        """
        try:
            user = self['anonymous-user'] or None
            passwd = self['anonymous-password']
        except KeyError:
            user, passwd = None, None
        except UnicodeDecodeError:
            raise ConfigurationError(
                "anonymous information should only contains ascii")
        return user, passwd
Ejemplo n.º 12
0
 def reorder_cubes(cls, cubes):
     """reorder cubes from the top level cubes to inner dependencies
     cubes
     """
     from logilab.common.graph import ordered_nodes, UnorderableGraph
     graph = {}
     for cube in cubes:
         cube = CW_MIGRATION_MAP.get(cube, cube)
         graph[cube] = set(dep for dep in cls.cube_dependencies(cube)
                           if dep in cubes)
         graph[cube] |= set(dep for dep in cls.cube_recommends(cube)
                            if dep in cubes)
     try:
         return ordered_nodes(graph)
     except UnorderableGraph as ex:
         raise ConfigurationError(ex)
Ejemplo n.º 13
0
 def cmd_drop_cube(self, cube, removedeps=False):
     if removedeps:
         toremove = self.config.expand_cubes([cube])
     else:
         toremove = (cube, )
     origcubes = self.config._cubes
     basecubes = [c for c in origcubes if not c in toremove]
     # don't fake-add any new ones, or we won't be able to really-add them later
     self.config._cubes = tuple(
         cube for cube in self.config.expand_cubes(basecubes)
         if cube in origcubes)
     removed = [p for p in origcubes if not p in self.config._cubes]
     if not cube in removed and cube in origcubes:
         raise ConfigurationError("can't remove cube %s, "
                                  "used as a dependency" % cube)
     return removed
Ejemplo n.º 14
0
 def __call__(self):
     """ Before an 'in_group' relation deletion or addition, check the
     assocaited group name: can't modifiy managers, users, guests and
     moderators group associated unless you are administrator.
     """
     parent = self._cw.entity_from_eid(self.eidto)
     child = self._cw.entity_from_eid(self.eidfrom)
     group_name = parent.name
     if child.firstname is None or child.surname is None:
         user_name = child.login
     else:
         user_name = child.firstname + " " + child.surname
     if group_name in self._cw.vreg.config.get("restricted-groups", []):
         raise ConfigurationError(
             "You do not have sufficient permissions to administrate '%s' "
             "in the '%s' group." % (user_name, group_name))
Ejemplo n.º 15
0
def configure_instance2(self, appid):
    configure_instance(self, appid)
    if self.config.db is not None:
        appcfg = ServerConfiguration.config_for(appid)
        srccfg = appcfg.read_sources_file()
        for key, value in self.config.db.items():
            if '.' in key:
                section, key = key.split('.', 1)
            else:
                section = 'system'
            try:
                srccfg[section][key] = value
            except KeyError:
                raise ConfigurationError(
                    'unknown configuration key "%s" in section "%s" for source'
                    % (key, section))
        admcfg = Configuration(options=USER_OPTIONS)
        admcfg['login'] = srccfg['admin']['login']
        admcfg['password'] = srccfg['admin']['password']
        srccfg['admin'] = admcfg
        appcfg.write_sources_file(srccfg)
Ejemplo n.º 16
0
    def ldap2cwattrs(self, sdict, etype):
        """Transform dictionary of LDAP attributes to CW.

        etype must be CWUser or CWGroup
        """
        assert etype in ('CWUser', 'CWGroup'), etype
        tdict = {}
        if etype == 'CWUser':
            items = self.source.user_attrs.items()
        elif etype == 'CWGroup':
            items = self.source.group_attrs.items()
        for sattr, tattr in items:
            if tattr not in self.non_attribute_keys:
                try:
                    value = sdict[sattr]
                except KeyError:
                    raise ConfigurationError(
                        'source attribute %s has not been found in the source, '
                        'please check the %s-attrs-map field and the permissions of '
                        'the LDAP binding user' % (sattr, etype[2:].lower()))
                if not isinstance(value, list):
                    value = [value]
                tdict[tattr] = value
        return tdict