Exemple #1
0
def query(request):
    ConfigService.setup_default_values()
    pairs = []
    for value in request.GET.getall('filter'):
        split = value.split(':', 1)
        pairs.append({'key': split[0], 'section': split[1]})
    return [c for c in ConfigService.filtered_key_and_section(pairs)]
Exemple #2
0
def query(request):
    ConfigService.setup_default_values()
    pairs = []
    for value in request.GET.getall("filter"):
        split = value.split(":", 1)
        pairs.append({"key": split[0], "section": split[1]})
    return [c for c in ConfigService.filtered_key_and_section(pairs)]
Exemple #3
0
def default_data(base_app):
    from appenlight.models.services.config import ConfigService
    from appenlight.lib import get_callable
    transaction.begin()
    ConfigService.setup_default_values()
    for plugin_name, config in base_app.registry.appenlight_plugins.items():
        if config['default_values_setter']:
            get_callable(config['default_values_setter'])()
    transaction.commit()
Exemple #4
0
def post(request):
    row = ConfigService.by_key_and_section(
        key=request.matchdict.get('key'),
        section=request.matchdict.get('section'))
    if not row:
        raise HTTPNotFound()
    row.value = None
    row.value = request.unsafe_json_body['value']
    return row
Exemple #5
0
def main(argv=sys.argv):
    parser = argparse.ArgumentParser(
        description="Migrate AppEnlight database to latest version",
        add_help=False)
    parser.add_argument("-c",
                        "--config",
                        required=True,
                        help="Configuration ini file of application")
    args = parser.parse_args()
    config_uri = args.config

    setup_logging(config_uri)
    bootstrap(config_uri)
    registry = get_current_registry()
    alembic_cfg = Config()
    alembic_cfg.set_main_option("sqlalchemy.echo", "true")
    alembic_cfg.set_main_option("script_location",
                                "ziggurat_foundations:migrations")
    alembic_cfg.set_main_option("sqlalchemy.url",
                                registry.settings["sqlalchemy.url"])
    command.upgrade(alembic_cfg, "head")
    alembic_cfg = Config()
    alembic_cfg.set_main_option("sqlalchemy.echo", "true")
    alembic_cfg.set_main_option("script_location", "appenlight:migrations")
    alembic_cfg.set_main_option("sqlalchemy.url",
                                registry.settings["sqlalchemy.url"])
    command.upgrade(alembic_cfg, "head")

    for plugin_name, config in registry.appenlight_plugins.items():
        if config["sqlalchemy_migrations"]:
            alembic_cfg = Config()
            alembic_cfg.set_main_option("script_location",
                                        config["sqlalchemy_migrations"])
            alembic_cfg.set_main_option("sqlalchemy.url",
                                        registry.settings["sqlalchemy.url"])
            alembic_cfg.set_main_option("sqlalchemy.echo", "true")
            command.upgrade(alembic_cfg, "head")

    with get_current_request().tm:
        ConfigService.setup_default_values()

        for plugin_name, config in registry.appenlight_plugins.items():
            if config["default_values_setter"]:
                get_callable(config["default_values_setter"])()
Exemple #6
0
def groups_list(request):
    """
    Returns groups list
    """
    groups = Group.all().order_by(Group.group_name)
    list_groups = ConfigService.by_key_and_section("list_groups_to_non_admins",
                                                   "global")
    if list_groups.value or request.has_permission("root_administration"):
        return [g.get_dict() for g in groups]
    else:
        return []
Exemple #7
0
def rate_limiting(request, resource, section, to_increment=1):
    tsample = datetime.datetime.utcnow().replace(second=0, microsecond=0)
    key = REDIS_KEYS["rate_limits"][section].format(tsample, resource.resource_id)
    redis_pipeline = request.registry.redis_conn.pipeline()
    redis_pipeline.incr(key, to_increment)
    redis_pipeline.expire(key, 3600 * 24)
    results = redis_pipeline.execute()
    current_count = results[0]
    config = ConfigService.by_key_and_section(section, "global")
    limit = config.value if config else 1000
    if current_count > int(limit):
        log.info("RATE LIMITING: {}: {}, {}".format(section, resource, current_count))
        abort_msg = "Rate limits are in effect for this application"
        raise HTTPTooManyRequests(abort_msg, headers={"X-AppEnlight": abort_msg})
Exemple #8
0
def add_renderer_globals(event):
    request = event.get("request") or threadlocal.get_current_request()

    renderer_globals = event
    renderer_globals["h"] = helpers
    renderer_globals["js_hash"] = request.registry.js_hash
    renderer_globals["css_hash"] = request.registry.css_hash
    renderer_globals['_'] = _
    renderer_globals['security'] = security
    renderer_globals['flash_msgs'] = []
    renderer_globals['appenlight_plugins'] = []

    if 'jinja' in event['renderer_info'].type:
        renderer_globals['url_list'] = gen_urls(request)
        # add footer html and some other global vars to renderer
        for module, config in request.registry.appenlight_plugins.items():
            if config['url_gen']:
                urls = config['url_gen'](request)
                renderer_globals['url_list']['plugins'][module] = urls

            renderer_globals['appenlight_plugins'].append({
                'name': module,
                'config': {
                    'javascript': config['javascript'],
                    'header_html': config['header_html']
                }
            })

        footer_config = ConfigService.by_key_and_section(
            'template_footer_html', 'global', default_value='')

        renderer_globals['template_footer_html'] = footer_config.value
        try:
            renderer_globals['root_administrator'] = request.has_permission(
                'root_administration', security.RootFactory(request))
        except AttributeError:
            renderer_globals['root_administrator'] = False

    renderer_globals['_mail_url'] = request.registry.settings['_mail_url']

    if not request:
        return

    # do not sens flash headers with /api calls
    if not request.path.startswith('/api'):
        flash_msgs = helpers.get_type_formatted_flash(request)
        renderer_globals['flash_msgs'] = flash_msgs
        request.add_flash_to_headers()
def add_renderer_globals(event):
    request = event.get("request") or threadlocal.get_current_request()

    renderer_globals = event
    renderer_globals["h"] = helpers
    renderer_globals["js_hash"] = request.registry.js_hash
    renderer_globals["css_hash"] = request.registry.css_hash
    renderer_globals["_"] = _
    renderer_globals["security"] = security
    renderer_globals["flash_msgs"] = []
    renderer_globals["appenlight_plugins"] = []

    if "jinja" in event["renderer_info"].type:
        renderer_globals["url_list"] = gen_urls(request)
        # add footer html and some other global vars to renderer
        for module, config in request.registry.appenlight_plugins.items():
            if config["url_gen"]:
                urls = config["url_gen"](request)
                renderer_globals["url_list"]["plugins"][module] = urls

            renderer_globals["appenlight_plugins"].append({
                "name": module,
                "config": {
                    "javascript": config["javascript"],
                    "header_html": config["header_html"],
                },
            })

        footer_config = ConfigService.by_key_and_section(
            "template_footer_html", "global", default_value="")

        renderer_globals["template_footer_html"] = footer_config.value
        try:
            renderer_globals["root_administrator"] = request.has_permission(
                "root_administration", security.RootFactory(request))
        except AttributeError:
            renderer_globals["root_administrator"] = False

    renderer_globals["_mail_url"] = request.registry.settings["_mail_url"]

    if not request:
        return

    # do not sens flash headers with /api calls
    if not request.path.startswith("/api"):
        flash_msgs = helpers.get_type_formatted_flash(request)
        renderer_globals["flash_msgs"] = flash_msgs
        request.add_flash_to_headers()