Using custom config settings in extensions

Extensions can define their own custom config settings that users can add to their CKAN config files to configure the behavior of the extension.

Continuing with the IAuthFunctions example from Writing extensions tutorial, let’s make an alternative version of the extension that allows users to create new groups if a new config setting ckan.iauthfunctions.users_can_create_groups is True:

# encoding: utf-8

from typing import Optional
from ckan.types import AuthResult, Context, DataDict

import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
from ckan.config.declaration import Declaration, Key


def group_create(
        context: Context,
        data_dict: Optional[DataDict] = None) -> AuthResult:

    # Get the value of the ckan.iauthfunctions.users_can_create_groups
    # setting from the CKAN config file as a string, or False if the setting
    # isn't in the config file.
    users_can_create_groups = toolkit.config.get(
        'ckan.iauthfunctions.users_can_create_groups')

    if users_can_create_groups:
        return {'success': True}
    else:
        return {'success': False,
                'msg': 'Only sysadmins can create groups'}


class ExampleIAuthFunctionsPlugin(plugins.SingletonPlugin):
    plugins.implements(plugins.IAuthFunctions)
    plugins.implements(plugins.IConfigDeclaration)

    def get_auth_functions(self):
        return {'group_create': group_create}

    # IConfigDeclaration

    def declare_config_options(self, declaration: Declaration, key: Key):
        declaration.declare_bool(
            key.ckan.iauthfunctions.users_can_create_groups)

The group_create authorization function in this plugin uses config to read the setting from the config file, then calls ckan.plugins.toolkit.asbool() to convert the value from a string (all config settings values are strings, when read from the file) to a boolean.

Note

There are also asint() and aslist() functions in the plugins toolkit.

With this plugin enabled, you should find that users can create new groups if you have ckan.iauthfunctions.users_can_create_groups = True in the [app:main] section of your CKAN config file. Otherwise, only sysadmin users will be allowed to create groups.

Note

Names of config settings provided by extensions should include the name of the extension, to avoid conflicting with core config settings or with config settings from other extensions. See Avoid name clashes.

Note

The users still need to be logged-in to create groups. In general creating, updating or deleting content in CKAN requires the user to be logged-in to a registered user account, no matter what the relevant authorization function says.