Esempio n. 1
0
 def __wrapper(func, *fargs, **fkwargs):
     if rhodecode.CELERY_ENABLED and not rhodecode.CELERY_EAGER:
         backends = config['vcs.backends'] = aslist(config.get(
             'vcs.backends', 'hg,git'),
                                                    sep=',')
         for alias in rhodecode.BACKENDS.keys():
             if alias not in backends:
                 del rhodecode.BACKENDS[alias]
         utils.configure_pyro4(config)
         utils.configure_vcs(config)
         connect_vcs(config['vcs.server'],
                     utils.get_vcs_server_protocol(config))
     ret = func(*fargs, **fkwargs)
     return ret
Esempio n. 2
0
def set_vcs_config(config):
    """
    Patch VCS config with some RhodeCode specific stuff

    :param config: rhodecode.CONFIG
    """
    import rhodecode
    from rhodecode.lib.vcs import conf
    from rhodecode.lib.utils2 import aslist
    conf.settings.BACKENDS = {
        'hg': 'rhodecode.lib.vcs.backends.hg.MercurialRepository',
        'git': 'rhodecode.lib.vcs.backends.git.GitRepository',
    }

    conf.settings.GIT_EXECUTABLE_PATH = config.get('git_path', 'git')
    conf.settings.GIT_REV_FILTER = config.get('git_rev_filter', '--all').strip()
    conf.settings.DEFAULT_ENCODINGS = aslist(config.get('default_encoding',
                                                        'utf8'), sep=',')
Esempio n. 3
0
def set_vcs_config(config):
    """
    Patch VCS config with some RhodeCode specific stuff

    :param config: rhodecode.CONFIG
    """
    import rhodecode
    from rhodecode.lib.vcs import conf
    from rhodecode.lib.utils2 import aslist
    conf.settings.BACKENDS = {
        'hg': 'rhodecode.lib.vcs.backends.hg.MercurialRepository',
        'git': 'rhodecode.lib.vcs.backends.git.GitRepository',
    }

    conf.settings.GIT_EXECUTABLE_PATH = config.get('git_path', 'git')
    conf.settings.GIT_REV_FILTER = config.get('git_rev_filter',
                                              '--all').strip()
    conf.settings.DEFAULT_ENCODINGS = aslist(config.get(
        'default_encoding', 'utf8'),
                                             sep=',')
Esempio n. 4
0
    def __wrapper(self, func, *fargs, **fkwargs):
        cls = fargs[0]
        user = cls.rhodecode_user
        loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
        # defined whitelist of controllers which API access will be enabled
        whitelist = aslist(config.get('api_access_controllers_whitelist'),
                           sep=',')
        api_access_whitelist = loc in whitelist
        log.debug('loc:%s is in API whitelist:%s:%s' % (loc, whitelist,
                                                        api_access_whitelist))
        #check IP
        ip_access_ok = True
        if not user.ip_allowed:
            from rhodecode.lib import helpers as h
            h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr))),
                    category='warning')
            ip_access_ok = False

        api_access_ok = False
        if self.api_access or api_access_whitelist:
            log.debug('Checking API KEY access for %s' % cls)
            if user.api_key == request.GET.get('api_key'):
                api_access_ok = True
            else:
                log.debug("API KEY token not valid")

        log.debug('Checking if %s is authenticated @ %s' % (user.username, loc))
        if (user.is_authenticated or api_access_ok) and ip_access_ok:
            reason = 'RegularAuth' if user.is_authenticated else 'APIAuth'
            log.info('user %s is authenticated and granted access to %s '
                     'using %s' % (user.username, loc, reason)
            )
            return func(*fargs, **fkwargs)
        else:
            log.warn('user %s NOT authenticated on func: %s' % (
                user, loc)
            )
            p = url.current()

            log.debug('redirecting to login page with %s' % p)
            return redirect(url('login_home', came_from=p))
Esempio n. 5
0
    def __wrapper(self, func, *fargs, **fkwargs):
        cls = fargs[0]
        user = cls.rhodecode_user
        loc = "%s:%s" % (cls.__class__.__name__, func.__name__)
        # defined whitelist of controllers which API access will be enabled
        whitelist = aslist(config.get('api_access_controllers_whitelist'),
                           sep=',')
        api_access_whitelist = loc in whitelist
        log.debug('loc:%s is in API whitelist:%s:%s' %
                  (loc, whitelist, api_access_whitelist))
        #check IP
        ip_access_ok = True
        if not user.ip_allowed:
            from rhodecode.lib import helpers as h
            h.flash(h.literal(_('IP %s not allowed' % (user.ip_addr))),
                    category='warning')
            ip_access_ok = False

        api_access_ok = False
        if self.api_access or api_access_whitelist:
            log.debug('Checking API KEY access for %s' % cls)
            if user.api_key == request.GET.get('api_key'):
                api_access_ok = True
            else:
                log.debug("API KEY token not valid")

        log.debug('Checking if %s is authenticated @ %s' %
                  (user.username, loc))
        if (user.is_authenticated or api_access_ok) and ip_access_ok:
            reason = 'RegularAuth' if user.is_authenticated else 'APIAuth'
            log.info('user %s is authenticated and granted access to %s '
                     'using %s' % (user.username, loc, reason))
            return func(*fargs, **fkwargs)
        else:
            log.warn('user %s NOT authenticated on func: %s' % (user, loc))
            p = url.current()

            log.debug('redirecting to login page with %s' % p)
            return redirect(url('login_home', came_from=p))
Esempio n. 6
0
def configure_vcs(config):
    """
    Patch VCS config with some RhodeCode specific stuff
    """
    from rhodecode.lib.vcs import conf
    from rhodecode.lib.utils2 import aslist
    conf.settings.BACKENDS = {
        'hg': 'rhodecode.lib.vcs.backends.hg.MercurialRepository',
        'git': 'rhodecode.lib.vcs.backends.git.GitRepository',
        'svn': 'rhodecode.lib.vcs.backends.svn.SubversionRepository',
    }

    conf.settings.HG_USE_REBASE_FOR_MERGING = config.get(
        'rhodecode_hg_use_rebase_for_merging', False)
    conf.settings.GIT_REV_FILTER = shlex.split(
        config.get('git_rev_filter', '--all').strip())
    conf.settings.DEFAULT_ENCODINGS = aslist(config.get(
        'default_encoding', 'UTF-8'),
                                             sep=',')
    conf.settings.ALIASES[:] = config.get('vcs.backends')
    conf.settings.SVN_COMPATIBLE_VERSION = config.get(
        'vcs.svn.compatible_version')
Esempio n. 7
0
def attach_context_attributes(context):
    rc_config = SettingsModel().get_all_settings(cache=True)

    context.rhodecode_version = rhodecode.__version__
    context.rhodecode_edition = config.get('rhodecode.edition')
    # unique secret + version does not leak the version but keep consistency
    context.rhodecode_version_hash = md5(
        config.get('beaker.session.secret', '') +
        rhodecode.__version__)[:8]

    # Default language set for the incoming request
    context.language = translation.get_lang()[0]

    # Visual options
    context.visual = AttributeDict({})

    # DB store
    context.visual.show_public_icon = str2bool(
        rc_config.get('rhodecode_show_public_icon'))
    context.visual.show_private_icon = str2bool(
        rc_config.get('rhodecode_show_private_icon'))
    context.visual.stylify_metatags = str2bool(
        rc_config.get('rhodecode_stylify_metatags'))
    context.visual.dashboard_items = safe_int(
        rc_config.get('rhodecode_dashboard_items', 100))
    context.visual.admin_grid_items = safe_int(
        rc_config.get('rhodecode_admin_grid_items', 100))
    context.visual.repository_fields = str2bool(
        rc_config.get('rhodecode_repository_fields'))
    context.visual.show_version = str2bool(
        rc_config.get('rhodecode_show_version'))
    context.visual.use_gravatar = str2bool(
        rc_config.get('rhodecode_use_gravatar'))
    context.visual.gravatar_url = rc_config.get('rhodecode_gravatar_url')
    context.visual.default_renderer = rc_config.get(
        'rhodecode_markup_renderer', 'rst')
    context.visual.rhodecode_support_url = \
        rc_config.get('rhodecode_support_url') or url('rhodecode_support')

    context.pre_code = rc_config.get('rhodecode_pre_code')
    context.post_code = rc_config.get('rhodecode_post_code')
    context.rhodecode_name = rc_config.get('rhodecode_title')
    context.default_encodings = aslist(config.get('default_encoding'), sep=',')
    # if we have specified default_encoding in the request, it has more
    # priority
    if request.GET.get('default_encoding'):
        context.default_encodings.insert(0, request.GET.get('default_encoding'))
    context.clone_uri_tmpl = rc_config.get('rhodecode_clone_uri_tmpl')

    # INI stored
    context.labs_active = str2bool(
        config.get('labs_settings_active', 'false'))
    context.visual.allow_repo_location_change = str2bool(
        config.get('allow_repo_location_change', True))
    context.visual.allow_custom_hooks_settings = str2bool(
        config.get('allow_custom_hooks_settings', True))
    context.debug_style = str2bool(config.get('debug_style', False))

    context.rhodecode_instanceid = config.get('instance_id')

    # AppEnlight
    context.appenlight_enabled = str2bool(config.get('appenlight', 'false'))
    context.appenlight_api_public_key = config.get(
        'appenlight.api_public_key', '')
    context.appenlight_server_url = config.get('appenlight.server_url', '')

    # END CONFIG VARS

    # TODO: This dosn't work when called from pylons compatibility tween.
    # Fix this and remove it from base controller.
    # context.repo_name = get_repo_slug(request)  # can be empty

    context.csrf_token = auth.get_csrf_token()
    context.backends = rhodecode.BACKENDS.keys()
    context.backends.sort()
    context.unread_notifications = NotificationModel().get_unread_cnt_for_user(
        context.rhodecode_user.user_id)
 def _to_python(self, value, state):
     if isinstance(value, basestring):
         value = aslist(value, ',')
     return super(_UniqueListFromString, self)._to_python(value, state)
def load_environment(global_conf,
                     app_conf,
                     initial=False,
                     test_env=None,
                     test_index=None):
    """
    Configure the Pylons environment via the ``pylons.config``
    object
    """
    config = PylonsConfig()

    # Pylons paths
    root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    paths = {
        'root': root,
        'controllers': os.path.join(root, 'controllers'),
        'static_files': os.path.join(root, 'public'),
        'templates': [os.path.join(root, 'templates')],
    }

    # Initialize config with the basic options
    config.init_app(global_conf, app_conf, package='rhodecode', paths=paths)

    # store some globals into rhodecode
    rhodecode.CELERY_ENABLED = str2bool(config['app_conf'].get('use_celery'))
    rhodecode.CELERY_EAGER = str2bool(
        config['app_conf'].get('celery.always.eager'))

    config['routes.map'] = make_map(config)

    if asbool(config.get('generate_js_files', 'false')):
        jsroutes = config['routes.map'].jsroutes()
        jsroutes_file_content = generate_jsroutes_content(jsroutes)
        jsroutes_file_path = os.path.join(paths['static_files'], 'js',
                                          'rhodecode', 'routes.js')

        with io.open(jsroutes_file_path, 'w', encoding='utf-8') as f:
            f.write(jsroutes_file_content)

    config['pylons.app_globals'] = app_globals.Globals(config)
    config['pylons.h'] = helpers
    rhodecode.CONFIG = config

    load_rcextensions(root_path=config['here'])

    # Setup cache object as early as possible
    import pylons
    pylons.cache._push_object(config['pylons.app_globals'].cache)

    # Create the Mako TemplateLookup, with the default auto-escaping
    config['pylons.app_globals'].mako_lookup = TemplateLookup(
        directories=paths['templates'],
        error_handler=handle_mako_error,
        module_directory=os.path.join(app_conf['cache_dir'], 'templates'),
        input_encoding='utf-8',
        default_filters=['escape'],
        imports=['from webhelpers.html import escape'])

    # sets the c attribute access when don't existing attribute are accessed
    config['pylons.strict_tmpl_context'] = True

    # Limit backends to "vcs.backends" from configuration
    backends = config['vcs.backends'] = aslist(config.get(
        'vcs.backends', 'hg,git'),
                                               sep=',')
    for alias in rhodecode.BACKENDS.keys():
        if alias not in backends:
            del rhodecode.BACKENDS[alias]
    log.info("Enabled backends: %s", backends)

    # initialize vcs client and optionally run the server if enabled
    vcs_server_uri = config.get('vcs.server', '')
    vcs_server_enabled = str2bool(config.get('vcs.server.enable', 'true'))
    start_server = (str2bool(config.get('vcs.start_server', 'false')) and
                    not int(os.environ.get('RC_VCSSERVER_TEST_DISABLE', '0')))
    if vcs_server_enabled and start_server:
        log.info("Starting vcsserver")
        start_vcs_server(server_and_port=vcs_server_uri,
                         protocol=utils.get_vcs_server_protocol(config),
                         log_level=config['vcs.server.log_level'])

    set_available_permissions(config)
    db_cfg = make_db_config(clear_session=True)

    repos_path = list(db_cfg.items('paths'))[0][1]
    config['base_path'] = repos_path

    config['vcs.hooks.direct_calls'] = _use_direct_hook_calls(config)
    config['vcs.hooks.protocol'] = _get_vcs_hooks_protocol(config)

    # store db config also in main global CONFIG
    set_rhodecode_config(config)

    # configure instance id
    utils.set_instance_id(config)

    # CONFIGURATION OPTIONS HERE (note: all config options will override
    # any Pylons config options)

    # store config reference into our module to skip import magic of pylons
    rhodecode.CONFIG.update(config)

    utils.configure_pyro4(config)
    utils.configure_vcs(config)
    if vcs_server_enabled:
        connect_vcs(vcs_server_uri, utils.get_vcs_server_protocol(config))

    import_on_startup = str2bool(config.get('startup.import_repos', False))
    if vcs_server_enabled and import_on_startup:
        repo2db_mapper(ScmModel().repo_scan(repos_path), remove_obsolete=False)
    return config