### Plugin Entry Point Registration (setup.cfg) Source: https://kadi4mat.readthedocs.io/en/stable/development/plugins.html Configure plugin registration for 'example' using the 'kadi_plugin_example.plugin' module. Specify Kadi4Mat as an install requirement. ```ini [options] install_requires = kadi>=X,=X, Source: https://kadi4mat.readthedocs.io/en/stable/apiref/plugins.html Example of defining a custom API endpoint within a plugin using the Kadi API blueprint. ```APIDOC ## GET /api/my_plugin/ ### Description Defines a custom API endpoint for a plugin using the Kadi API blueprint system. ### Method GET ### Endpoint /api/my_plugin/ ### Parameters #### Path Parameters - **my_endpoint** (string) - Required - The specific endpoint identifier defined by the plugin. ### Response #### Success Response (200) - **status** (integer) - Returns a 200 OK status code. ``` -------------------------------- ### GET /kadi/lib/storage/misc/preview_thumbnail Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Sends a thumbnail to a client for previewing purposes. ```APIDOC ## GET /kadi/lib/storage/misc/preview_thumbnail ### Description Send a thumbnail to a client for previewing. Uses the MiscStorage to send the thumbnails. ### Method GET ### Parameters #### Query Parameters - **identifier** (string) - Required - A file identifier that will be passed to the storage. - **filename** (string) - Required - The name of the thumbnail to send. ### Response #### Success Response (200) - **response** (object) - The response object containing the thumbnail data. ``` -------------------------------- ### Start Send Mail Task Function Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/mails/tasks.html Launches the email sending task in the background. It returns True if the task was successfully started, False otherwise. Note that a successful start does not guarantee email delivery. ```python def start_send_mail_task( *, subject, message, to_addresses, from_address=None, cc=None, bcc=None, attachments=None, reply_to=None, html_message=None, headers=None, ): """Send a mail in a background task. See :func:`kadi.lib.mails.core.send_mail` for the possible parameters. In case the connection to the mail server fails, the task will be retried every 60 seconds until a maximum defined in ``CELERY_ANNOTATIONS`` in the application's configuration is reached. Other errors will cause the task to fail, however. :return: ``True`` if the task was started successfully, ``False`` otherwise. Note that the task being started successfully does not necessarily mean that the email will be sent successfully as well. """ return launch_task( const.TASK_SEND_MAIL, kwargs={ "subject": subject, "message": message, "to_addresses": to_addresses, "from_address": from_address, "cc": cc, "bcc": bcc, "attachments": attachments, "reply_to": reply_to, "html_message": html_message, "headers": headers, }, ) ``` -------------------------------- ### Basic Configuration File Example Source: https://kadi4mat.readthedocs.io/en/stable/installation/configuration/index.html A standard Python configuration file defining authentication providers and the server name. ```python # Configure authentication providers to log in to Kadi4Mat. AUTH_PROVIDERS = [ { "type": "local", "allow_registration": True, }, ] # Configure the name of the Kadi4Mat server. SERVER_NAME = "kadi4mat.example.edu" # Other configuration values... ``` -------------------------------- ### Python Docstring Example Source: https://kadi4mat.readthedocs.io/en/stable/development/documentation.html Use RST style for docstrings in Python, including longer descriptions, examples, and parameter/return value documentation. ```python def foo(param_a, param_b=None): """Brief description, ideally in one line, but can also consist of multiple lines, if necessary. Longer description and additional information, if necessary. Here we could also include an example or anything else that RST allows us to do: .. code-block:: python3 # An example on how to call the function. foo(1, param_b=2) :param param_a: Description of param_a. :param param_b: (optional) Very long description of an optional param_b that may take up multiple lines. :return: Description of return value. :raises Exception: If something went wrong. """ ``` -------------------------------- ### GET /plugin-preferences Source: https://kadi4mat.readthedocs.io/en/stable/apiref/modules.html Retrieves all plugin preferences configurations. ```APIDOC ## GET /plugin-preferences ### Description Retrieves a dictionary of all plugin preferences configurations using the kadi_get_preferences_config hook. ### Response #### Success Response (200) - **configs** (object) - A dictionary mapping plugin names to their respective configuration settings. ``` -------------------------------- ### POST /tasks/apply-role-rules Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Starts a background task to apply role rules to users. ```APIDOC ## POST /tasks/apply-role-rules ### Description Apply a specific or all existing role rules in a background task. ### Method POST ### Parameters #### Query Parameters - **role_rule** (string) - Optional - A specific role rule to apply. - **user** (string) - Optional - A specific user to apply the role rule(s) to. If not given, all existing users are considered. ### Response #### Success Response (200) - **result** (boolean) - True if the task was started successfully, False otherwise. ``` -------------------------------- ### Get Plugin Licenses Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/licenses/core.html Retrieves licenses provided by installed plugins. ```APIDOC ## GET /api/licenses/plugins ### Description Retrieves all licenses made available through installed plugins. Invalid license data from plugins will be ignored. ### Method GET ### Endpoint /api/licenses/plugins ### Response #### Success Response (200) - **licenses** (object) - A dictionary where keys are license names and values are objects containing 'title' and 'url' for each license provided by plugins. ### Response Example ```json { "licenses": { "my-plugin-license": { "title": "My Custom Plugin License", "url": "http://example.com/my-plugin-license" } } } ``` ``` -------------------------------- ### Plugin Entry Point Registration (pyproject.toml) Source: https://kadi4mat.readthedocs.io/en/stable/development/plugins.html Register a plugin named 'example' that loads hook implementations from the 'kadi_plugin_example.plugin' module. Ensure Kadi4Mat is listed as a dependency. ```toml [project] dependencies = [ "kadi>=X,", "client_secret": "", } } ``` -------------------------------- ### Display Kadi CLI Help Source: https://kadi4mat.readthedocs.io/en/stable/development/tools.html Run this command to get an overview of all available subcommands in the Kadi CLI. Ensure the Kadi4Mat environment is active. ```bash kadi ``` -------------------------------- ### Perform OAuth2 GET Request Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/federation.html Executes a GET request to a specified endpoint using an OAuth2 client. Includes error logging and returns a standardized JSON response. ```python client = get_oauth2_client(name) if endpoint.startswith("/"): endpoint = endpoint[1:] try: response = client.get(endpoint, token=token, params=params, timeout=10) except Exception as e: current_app.logger.exception(e) return json_error_response( 502, description=f"Request to instance '{name}' failed." ) return json_response(response.status_code, response.json()) ``` -------------------------------- ### View HTML Documentation Source: https://kadi4mat.readthedocs.io/en/stable/development/documentation.html Open the generated HTML documentation in a web browser. ```bash firefox docs/build/html/index.html ``` -------------------------------- ### Update npm Packages Source: https://kadi4mat.readthedocs.io/en/stable/development/coding.html Use these commands to update your project's dependencies. `npm update` updates compatible versions, while `npm install @x.y.z` installs a specific version. ```bash npm update # Automatically update all packages with compatible versions ``` ```bash npm install @x.y.z # Install version x.y.z (e.g. a new major version) of a package ``` -------------------------------- ### POST /licenses/initialize Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Initializes built-in licenses in the database. ```APIDOC ## POST /licenses/initialize ### Description Initialize all built-in licenses in the database by creating database objects for them. ### Method POST ### Response #### Success Response (200) - **result** (boolean) - True if at least one license was created, False otherwise. ``` -------------------------------- ### Initialize and set configuration values in a form Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/forms.html Handles automatic prepopulation and saving of configuration items based on form field data. ```python submit = SubmitField(_l("Save changes")) def _iterate_fields(self, callback): for field in self._unbound_fields: field_name = field[0] if field_name not in self._ignored_fields: callback(field_name) def __init__( self, *args, user=None, key_prefix=None, ignored_fields=None, encrypted_fields=None, **kwargs, ): self._user = user self._key_prefix = f"{key_prefix.upper()}_" if key_prefix else "" self._ignored_fields = ignored_fields if ignored_fields is not None else set() self._ignored_fields.add("submit") self._encrypted_fields = ( encrypted_fields if encrypted_fields is not None else set() ) kwargs["data"] = {} def _prepopulate_fields(field_name): config_key = self._key_prefix + field_name.upper() if self._user is None: config_value = get_sys_config(config_key, use_fallback=False) else: config_value = self._user.get_config( config_key, decrypt=field_name in self._encrypted_fields ) if config_value is not MISSING: kwargs["data"][field_name] = config_value self._iterate_fields(_prepopulate_fields) super().__init__(*args, **kwargs) [docs] def set_config_values(self): """Automatically set all config items based on the respective field data. Useful to populate all relevant config items in the database after a form is submitted. Similar to prepopulating the form fields, the names of the fields are taken in uppercase as keys for each config item. """ def _set_config_value(field_name): config_key = self._key_prefix + field_name.upper() field_data = getattr(self, field_name).data if self._user is None: set_sys_config(config_key, field_data) else: self._user.set_config( config_key, field_data, encrypt=field_name in self._encrypted_fields ) self._iterate_fields(_set_config_value) ``` -------------------------------- ### Export Filter Dictionary Example Source: https://kadi4mat.readthedocs.io/en/stable/apiref/modules.html A dictionary specifying filters to adjust returned export data for 'json', 'rdf', and 'ro-crate' export types. This example shows default values for each filter. ```python { # Whether user information about the creator of the collection or any # linked resource should be excluded. "user": False, # Whether to exclude information about records that are part of the # collection. "records": False, # Whether to exclude all (True), outgoing ("out") or incoming ("in") # links of records with other records when record information is not # excluded. "links": False, # To specify which kind of export data of records should be included in # an exported RO-Crate when using the "ro-crate" export type and record # information is not excluded. All other filters also apply to this # export data, as far as applicable. "export_data": ["json", "rdf"], # Whether to return only the metadata file of an exported RO-Crate when # using the "ro-crate" export type. "metadata_only": False, } ``` -------------------------------- ### Initialize System Roles Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/permissions/utils.html Creates database entries for system roles defined in constants if they do not already exist. Returns True if any new roles were created. ```python role_created = False for role_name in const.SYSTEM_ROLES: if ( Role.query.filter_by(name=role_name, object=None, object_id=None).first() is None ): Role.create(name=role_name) role_created = True return role_created ``` -------------------------------- ### Get Permitted Record Links Source: https://kadi4mat.readthedocs.io/en/stable/apiref/modules.html Convenience function to get all links of a record that a user can access. This includes links to or from records for which the user has read permission. Links involving inactive records are filtered out. ```APIDOC ## GET /api/records/links/permitted ### Description Convenience function to get all links of a record that a user can access. ### Method GET ### Endpoint /api/records/links/permitted ### Parameters #### Query Parameters - **record_or_id** (object/string) - Required - The record or ID of a record whose links should be obtained. - **direction** (string) - Optional - A direction to limit the returned record links to (`"out"` for outgoing, `"in"` for incoming). - **actions** (array) - Optional - A list of further actions to check as part of the access permissions of records. - **user** (object/string) - Optional - The user to check for access permissions. Defaults to the current user. ### Response #### Success Response (200) - **record_links** (query) - The permitted record link objects as a query. ``` -------------------------------- ### Initialize LocalStorage Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/storage/local.html Instantiates the storage provider with a required absolute root directory path. ```python class LocalStorage(BaseStorage): """Storage provider that uses the local file system. :param root_directory: The directory the storage provider operates in. Must be an absolute path. :param num_dirs: (optional) Number of directories for local file paths generated by this storage provider. Must be a minimum of ``0``. :param dir_len: (optional) Length of each directory for local file paths generated by this storage provider. Must be a minimum of ``1``. :raises ValueError: If the given root directory is not suitable. """ def __init__(self, root_directory, num_dirs=3, dir_len=2): super().__init__(const.STORAGE_TYPE_LOCAL, storage_name=_l("Local")) if not os.path.isabs(root_directory): raise ValueError( f"Given root directory '{root_directory}' is not an absolute path." ) self._root_directory = root_directory self._num_dirs = max(num_dirs, 0) self._dir_len = max(dir_len, 1) ``` -------------------------------- ### Reset and initialize database Source: https://kadi4mat.readthedocs.io/en/stable/development/issues.html Commands to drop, recreate, and initialize the Kadi database when migration chains are broken. ```bash sudo -Hiu postgres dropdb kadi sudo -Hiu postgres createdb -O kadi -E utf-8 -T template0 kadi ``` ```bash kadi db init # Initialize the database kadi db sample-data # Initialize the database and setup some sample users and resources ``` -------------------------------- ### GET /publication/providers Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Retrieves a list of all registered publication providers. ```APIDOC ## GET /publication/providers ### Description Get a list of registered publication providers, combined from plugin hooks and OAuth2 providers. ### Parameters #### Query Parameters - **resource** (Record/Collection) - Required - The resource to eventually publish. - **user** (User) - Optional - The user to check for OAuth2 connection status. ### Response #### Success Response (200) - **List** (Array) - A list of provider dictionaries sorted by name. #### Response Example [ { "name": "example", "description": "An example publication provider.", "title": "Example provider", "website": "https://example.com", "is_connected": true } ] ``` -------------------------------- ### Initialize LDAP Server Object Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/ldap.html Creates a new LDAP Server instance with optional SSL/TLS configuration. ```python def make_server(host, port=389, use_ssl=False, validate_cert="REQUIRED", ciphers=None): """Create a new LDAP ``Server`` object. :param host: The host name or IP address of the LDAP server. :param port: (optional) The port the LDAP server is listening on. :param use_ssl: (optional) Flag indicating whether the entire connection should be secured via SSL/TLS. :param validate_cert: (optional) Whether the certificate of the server should be validated. One of ``"NONE"``, ``"OPTIONAL"`` or ``"REQUIRED"``. :param ciphers: (optional) One or more SSL/TLS ciphers to use as a single string according to the OpenSSL cipher list format. May also be set to ``"DEFAULT"``, in which case the default ciphers of the installed OpenSSL version are used. :return: The new ``Server`` object or ``None`` if it could not be created. """ try: tls = ldap.Tls( validate=getattr(ssl, f"CERT_{validate_cert}", ssl.CERT_REQUIRED), ciphers=ciphers, ) return ldap.Server(host, port=port, use_ssl=use_ssl, tls=tls) except Exception as e: current_app.logger.exception(e) return None ``` -------------------------------- ### GET /licenses/plugins Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Retrieves all licenses added via plugins. ```APIDOC ## GET /licenses/plugins ### Description Get all licenses added via plugins using the kadi_get_licenses plugin hook. ### Method GET ### Response #### Success Response (200) - **licenses** (dictionary) - A dictionary mapping the unique name of each license to a dictionary containing 'title' and 'url'. ``` -------------------------------- ### Initialize System Roles Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/permissions/utils.html Initializes all system roles by creating database objects for system roles that do not already exist. ```APIDOC ## POST /api/roles/system/initialize ### Description Initialize all system roles. Will create database objects of the system roles defined in `kadi.lib.constants.SYSTEM_ROLES` that do not exist yet. ### Method POST ### Endpoint /api/roles/system/initialize ### Response #### Success Response (200) - **role_created** (boolean) - True if at least one system role was created, False otherwise. ``` -------------------------------- ### File Creation Source: https://kadi4mat.readthedocs.io/en/stable/apiref/modules.html How to create a new file and add it to the database session. ```APIDOC ## POST /api/files ### Description Creates a new file entry in the database and associates it with a record. This method handles the initial setup for a file, which can then be populated with data via uploads. ### Method POST ### Endpoint /api/files ### Parameters #### Request Body - **creator** (string) - Required - The identifier of the user creating the file. - **record** (string) - Required - The identifier of the record to which the file belongs. - **name** (string) - Required - The name of the file. Restricted to a maximum length of 256 characters. - **size** (integer) - Required - The size of the file in bytes. Must be a value greater than or equal to 0. - **description** (string) - Optional - A description for the file. Restricted to a maximum length of 50000 characters. - **checksum** (string) - Optional - The checksum of the file. Restricted to a maximum length of 256 characters. - **mimetype** (string) - Optional - The regular MIME type of the file. Defaults to 'application/octet-stream'. Restricted to a maximum length of 256 characters. - **magic_mimetype** (string) - Optional - The MIME type determined from the file's content. - **storage_type** (string) - Optional - The type of storage provider. Defaults to the application's configured default. - **state** (string) - Optional - The initial state of the file. Allowed values: 'active', 'processing', 'inactive'. Defaults to 'inactive'. ### Response #### Success Response (201 Created) - **id** (string) - The UUID of the newly created file. - **created_at** (string) - The date and time the file was created (UTC). - **last_modified** (string) - The date and time the file was last modified (UTC). #### Response Example ```json { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "created_at": "2023-10-27T10:00:00Z", "last_modified": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### GET /licenses/builtin Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Retrieves all built-in licenses from the resource file. ```APIDOC ## GET /licenses/builtin ### Description Get all built-in licenses from their resource file. ### Method GET ### Response #### Success Response (200) - **licenses** (dictionary) - A dictionary mapping the unique name of each license to a dictionary containing 'title' and 'url'. ``` -------------------------------- ### Initialize built-in licenses Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/licenses/utils.html Populates the database with built-in licenses. Returns True if any new licenses were added, otherwise False. ```python # Copyright 2020 Karlsruhe Institute of Technology # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .core import get_builtin_licenses from .models import License [docs] def initialize_builtin_licenses(): """Initialize all built-in licenses in the database. Will create database objects of the licenses returned by :func:`get_builtin_licenses`. :return: ``True`` if at least one license was created, ``False`` otherwise. """ license_created = False for name, license_meta in get_builtin_licenses().items(): if License.query.filter_by(name=name).first() is None: License.create( name=name, title=license_meta["title"], url=license_meta["url"] ) license_created = True return license_created ``` -------------------------------- ### GET /quota Source: https://kadi4mat.readthedocs.io/en/stable/apiref/modules.html Calculates the storage quota for a specific user. ```APIDOC ## GET /quota ### Description Calculates the user's storage quota, accounting for active files and pending uploads. ### Parameters #### Query Parameters - **user** (string) - Optional - The user to calculate the quota for. Defaults to the current user. ### Response #### Success Response (200) - **quota** (number) - The calculated user quota. ``` -------------------------------- ### GET /kadi/lib/tags/core/get_tags Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Retrieves all distinct tags of resources accessible by a user. ```APIDOC ## GET /kadi/lib/tags/core/get_tags ### Description Get all distinct tags of resources a user can access. ### Method GET ### Parameters #### Query Parameters - **filter_term** (string) - Optional - A case insensitive term to filter the tags by their name. - **resource_type** (string) - Optional - A resource type to limit the tags to. One of "record" or "collection". - **user** (string) - Optional - The user who will be checked for access permissions. ### Response #### Success Response (200) - **tags** (query) - The tags as query, ordered by their name in ascending order. ``` -------------------------------- ### Initialize Revisioning System Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/revisions/core.html Iterates through metadata tables to register revision models for classes configured with Meta.revision. ```python def setup_revisions(): """Setup revisioning for all models that support it. The columns to store revisions of have to be specified in a ``Meta.revision`` attribute in each model. It should be a list of strings specifying the attribute names. **Example:** .. code-block:: python3 class Foo: class Meta: revision = ["bar", "baz[foo, bar]"] The columns can either be regular columns, like the first value in the list, or relationships like the second value. For the latter, all regular columns of the relationship that should be included in the revision need to be specified in square brackets, separated by commas. For each model, a new model class for the revisions will be created automatically, linked to the original model class and to :class:`.Revision`. The class of the revisioned model will also be stored on each new revision model as ``model_class``. Additionally, the revision model class will be stored on the original model as ``revision_class`` as well as a convenience property to retrieve the revisions in descending order of their timestamp as ``ordered_revisions``. """ # Make a copy of the keys as we might be adding new tables while iterating. for tablename in list(db.metadata.tables.keys()): model = get_class_by_tablename(tablename) if rgetattr(model, "Meta.revision", None) is not None: revision_classname = f"{model.__name__}Revision" revision_tablename = f"{model.__tablename__}_revision" # Stops SQLAlchemy from complaining when the dev server is reloading. if db.metadata.tables.get(revision_tablename) is not None: return revision_model = _make_revision_model( model, revision_classname, revision_tablename ) # Setup some convenience attributes. model.revision_class = revision_model model.ordered_revisions = property( lambda self: self.revisions.join(Revision).order_by( Revision.timestamp.desc() ) ) ``` -------------------------------- ### API Routing with Versioning Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Demonstrates how to use the `route` decorator from `kadi.lib.api.blueprint.APIBlueprint` to define API endpoints with versioning support. ```APIDOC ## POST /api/records (Example) ### Description This endpoint is an example of how to define a route that supports multiple API versions using the `route` decorator. ### Method POST ### Endpoint /api/records ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "message": "This is a sample request body." } ``` ### Response #### Success Response (200) - **message** (string) - A success message. #### Response Example ```json { "message": "Records retrieved successfully." } ``` ## GET /api/v1/records ### Description This endpoint is specifically for version 1 of the records API. It is registered using the `route` decorator with versioning enabled. ### Method GET ### Endpoint /api/v1/records ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **records** (array) - A list of records. #### Response Example ```json { "records": [ {"id": 1, "name": "Record 1"}, {"id": 2, "name": "Record 2"} ] } ``` ## GET /api/v2/records ### Description This endpoint is specifically for version 2 of the records API. It is registered using the `route` decorator with versioning enabled. ### Method GET ### Endpoint /api/v2/records ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **records** (array) - A list of records. #### Response Example ```json { "records": [ {"id": 1, "name": "Record A"}, {"id": 2, "name": "Record B"} ] } ``` ``` -------------------------------- ### GET /resource/export Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Exports resource data for direct preview or download. ```APIDOC ## GET /resource/export ### Description Get the exported data of a resource for direct preview or download. ### Method GET ### Parameters #### Query Parameters - **resource** (Record/Collection) - Required - The resource to export. - **export_type** (string) - Required - A valid export type as defined in constants. - **export_func** (function) - Required - The export function corresponding to the resource. - **export_filter** (dict) - Optional - A dictionary specifying various export filters. - **preview** (bool) - Optional - Whether the exported data should be sent for preview. - **download** (bool) - Optional - Whether the exported data should be downloaded as an attachment. ``` -------------------------------- ### Create a new AES engine Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Convenience method to instantiate the KadiAesEngine with default configuration, useful outside of an ORM context. ```python engine = KadiAesEngine.create() ``` -------------------------------- ### get_group_roles Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Get all groups and roles of a specific object or object type. ```APIDOC ## get_group_roles(object_name, object_id=None) ### Description Get all groups and roles of a specific object or object type. Inactive groups are filtered out. ### Parameters - **object_name** (string) - Required - The type of the object. - **object_id** (integer/string) - Optional - The ID of a specific object. ### Response - Returns the groups and corresponding roles of the object(s) as a query. ``` -------------------------------- ### Prototyping with Kadi shell Source: https://kadi4mat.readthedocs.io/en/stable/development/coding.html Use the Kadi shell for interactive testing with an automatically pushed Flask application context and pre-imported models. ```bash kadi shell >>> app # Imported automatically >>> dir() # Get an overview of all automatically imported names ``` -------------------------------- ### get_user_roles Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Get all users and roles of a specific object or object type. ```APIDOC ## get_user_roles(object_name, object_id=None) ### Description Get all users and roles of a specific object or object type. Inactive users are filtered out. ### Parameters - **object_name** (string) - Required - The type of the object. - **object_id** (integer/string) - Optional - The ID of a specific object. ### Response - Returns the users and corresponding roles of the object(s) as a query. ``` -------------------------------- ### Create ConfigItem Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/config/models.html Class method to create a new config item and add it to the database session. The value must be JSON serializable. Use this for simple creation of configuration entries. ```python @classmethod def create(cls, *, key, value, user=None): """Create a new config item and add it to the database session. :param key: The key of the config item. :param value: The value of the config item, which needs to be JSON serializable. :param user: (optional) The user the config item belongs to. :return: The new :class:`ConfigItem` object. """ config_item = cls(key=key, value=value, user=user) db.session.add(config_item) return config_item ``` -------------------------------- ### GET /templates/search Source: https://kadi4mat.readthedocs.io/en/stable/apiref/modules.html Search and filter for templates using various criteria. ```APIDOC ## GET /templates/search ### Description Search and filter for templates based on query, visibility, and user permissions. ### Method GET ### Endpoint /templates/search ### Parameters #### Query Parameters - **search_query** (string) - Optional - Search string for resources. - **page** (integer) - Optional - Page number for pagination. - **per_page** (integer) - Optional - Number of items per page. - **sort** (string) - Optional - Sorting criteria. - **visibility** (string) - Optional - Visibility filter. - **explicit_permissions** (boolean) - Optional - Whether to check explicit permissions. - **user_ids** (list) - Optional - List of user IDs to filter by. - **template_type** (string) - Optional - Type value to filter templates. - **user** (object) - Optional - User object to check permissions against. ``` -------------------------------- ### GET /accounts/providers/{name} Source: https://kadi4mat.readthedocs.io/en/stable/apiref/modules.html Retrieves the authentication provider class by its name. ```APIDOC ## GET /accounts/providers/{name} ### Description Get the provider class of an authentication provider by its name. ### Method GET ### Parameters #### Path Parameters - **name** (string) - Required - The name of the authentication provider. ### Response #### Success Response (200) - **provider_class** (object) - The authentication provider class or null if no provider with the given name exists. ``` -------------------------------- ### Initialize PDF Export Class Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/export.html Initializes the base PDF export class, setting up fonts and adding the first page. Requires FPDF and configuration for font paths. ```python import os from importlib import metadata from flask import current_app from flask_babel import format_datetime from flask_babel import gettext as _ from fpdf import FPDF from rdflib import RDF from rdflib import SDO from rdflib import Graph from rdflib import Literal from rdflib import URIRef from zipstream import ZipStream import kadi.lib.constants as const from kadi.lib.utils import formatted_json from kadi.lib.utils import utcnow from kadi.lib.web import url_for [docs] class PDF(FPDF): """Base PDF export class using FPDF. :param title: (optional) The title of the PDF, which will appear in the header on each page and in the metadata of the PDF itself. """ def __init__(self, title=""): super().__init__() self.title = title self.generated_at = utcnow() fonts_path = current_app.config["FONTS_PATH"] self.add_font( "NotoSans", fname=os.path.join(fonts_path, "noto_sans", "NotoSans-Regular.ttf"), ) self.add_font( "NotoSans", fname=os.path.join(fonts_path, "noto_sans", "NotoSans-Bold.ttf"), style="B", ) self.add_font( "NotoSans", fname=os.path.join(fonts_path, "noto_sans", "NotoSans-Italic.ttf"), style="I", ) self.add_font( "NotoSansMono", fname=os.path.join( fonts_path, "noto_sans_mono", "NotoSansMono-Regular.ttf" ), ) self.add_font( "NotoEmoji", fname=os.path.join(fonts_path, "noto_emoji", "NotoEmoji-Regular.ttf"), ) self.set_fallback_fonts(["NotoEmoji"], exact_match=False) self.set_font(size=10, family="NotoSans") self.set_title(self.title) self.add_page() ``` -------------------------------- ### API Reference - Configuration Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html APIs for managing system and user configurations. ```APIDOC ## API - Configuration ### Description APIs for managing system-wide and user-specific configuration settings. ### System Configuration: - **`get_sys_config(key)`** - **Description**: Retrieves a system configuration value by its key. - **Parameters**: - **key** (string) - Required - The key of the configuration setting. - **`set_sys_config(key, value)`** - **Description**: Sets a system configuration value. - **Parameters**: - **key** (string) - Required - The key of the configuration setting. - **value** (any) - Required - The value to set. - **`remove_sys_config(key)`** - **Description**: Removes a system configuration setting by its key. - **Parameters**: - **key** (string) - Required - The key of the configuration setting. ### User Configuration: - **`get_user_config(user_id, key)`** - **Description**: Retrieves a user-specific configuration value. - **Parameters**: - **user_id** (unknown) - Required - The ID of the user. - **key** (string) - Required - The key of the configuration setting. - **`set_user_config(user_id, key, value)`** - **Description**: Sets a user-specific configuration value. - **Parameters**: - **user_id** (unknown) - Required - The ID of the user. - **key** (string) - Required - The key of the configuration setting. - **value** (any) - Required - The value to set. - **`remove_user_config(user_id, key)`** - **Description**: Removes a user-specific configuration setting. - **Parameters**: - **user_id** (unknown) - Required - The ID of the user. - **key** (string) - Required - The key of the configuration setting. ### Class: `ConfigItem` - **`ConfigItem.Meta`** - **`ConfigItem.Meta.representation`**: Defines the string representation of a config item. - **Attributes**: - **`ConfigItem.id`** (unknown) - Unique identifier for the config item. - **`ConfigItem.key`** (string) - The configuration key. - **`ConfigItem.value`** (any) - The configuration value. - **`ConfigItem.created_at`** (datetime) - Timestamp when the config item was created. - **`ConfigItem.last_modified`** (datetime) - Timestamp when the config item was last modified. - **`ConfigItem.user_id`** (unknown) - The ID of the user associated with this config item (if applicable). ### Methods: - **`ConfigItem.create()`** - **Description**: Creates a new configuration item. - **Method**: Not applicable (class method or static method) - **`ConfigItem.update_or_create()`** - **Description**: Updates an existing configuration item or creates a new one if it doesn't exist. - **Method**: Not applicable (class method or static method) ``` -------------------------------- ### Get OIDC Client Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/oauth/utils.html Retrieves a registered OIDC client by its name. ```APIDOC ## GET /oidc/client ### Description Retrieves a registered OIDC client by its name. ### Parameters #### Query Parameters - **name** (string) - Required - The name of the OIDC client. ### Response #### Success Response (200) - **client** (object) - The OIDC client object. #### Error Response (400) - **AttributeError** - If the specified OIDC client has not been registered. ``` -------------------------------- ### Get OAuth2 Client Source: https://kadi4mat.readthedocs.io/en/stable/_modules/kadi/lib/oauth/utils.html Retrieves a registered OAuth2 client by its name. ```APIDOC ## GET /oauth2/client ### Description Retrieves a registered OAuth2 client by its name. ### Parameters #### Query Parameters - **name** (string) - Required - The name of the OAuth2 client. ### Response #### Success Response (200) - **client** (object) - The OAuth2 client object. #### Error Response (400) - **AttributeError** - If the specified OAuth2 client has not been registered. ``` -------------------------------- ### initialize_system_roles Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Initialize all system roles defined in constants. ```APIDOC ## initialize_system_roles() ### Description Initialize all system roles. Will create database objects of the system roles defined in kadi.lib.constants.SYSTEM_ROLES that do not exist yet. ### Response - Returns True if at least one system role was created, False otherwise. ``` -------------------------------- ### GET /resource/group-roles Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Retrieves the paginated group roles associated with a specific resource. ```APIDOC ## GET /resource/group-roles ### Description Get the paginated group roles of a resource, including special cases for users without read access. ### Method GET ### Parameters #### Query Parameters - **resource** (Record/Collection/Template) - Required - The resource to get the group roles of. - **page** (int) - Optional - The current page (default: 1). - **per_page** (int) - Optional - Items per page (default: 10). - **filter_term** (string) - Optional - A query to filter the groups by their title or identifier. - **user** (User) - Optional - The user to check for any permissions regarding the resulting groups. ### Response #### Success Response (200) - **results** (list) - A list of deserialized group roles. - **total** (int) - The total amount of user roles. ``` -------------------------------- ### GET /resource/user-roles Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Retrieves the paginated user roles associated with a specific resource. ```APIDOC ## GET /resource/user-roles ### Description Get the paginated user roles of a resource. ### Method GET ### Parameters #### Query Parameters - **resource** (Record/Collection/Template/Group) - Required - The resource to get the user roles of. - **page** (int) - Optional - The current page (default: 1). - **per_page** (int) - Optional - Items per page (default: 10). - **filter_term** (string) - Optional - A case insensitive term to filter the users by their username or display name. - **exclude** (list) - Optional - A list of user IDs to exclude in the results. ### Response #### Success Response (200) - **results** (list) - A list of deserialized user roles. - **total** (int) - The total amount of user roles. ``` -------------------------------- ### Implementing a Kadi4Mat Plugin Hook Source: https://kadi4mat.readthedocs.io/en/stable/development/plugins.html Implement a plugin hook named 'kadi_example_plugin_hook' using the `@hookimpl` decorator. This example shows how to load and potentially use plugin configuration via `get_plugin_config`. ```python from kadi.lib.plugins.core import get_plugin_config from kadi.plugins import hookimpl @hookimpl def kadi_example_plugin_hook(): # Load the configuration of the "example" plugin, if applicable. config = get_plugin_config("example") # Validate the configuration or do something else with it. ``` -------------------------------- ### Create PostgreSQL Test User and Database Source: https://kadi4mat.readthedocs.io/en/stable/development/testing.html Use these commands to create a dedicated PostgreSQL user and database for testing. Ensure the password matches the application's default testing configuration. ```bash sudo -Hiu postgres createuser -P kadi_test sudo -Hiu postgres createdb -O kadi_test -E utf-8 -T template0 kadi_test ``` -------------------------------- ### GET /publication/providers/{provider} Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Retrieves details for a specific registered publication provider. ```APIDOC ## GET /publication/providers/{provider} ### Description Get a specific, registered publication provider by its unique name. ### Parameters #### Path Parameters - **provider** (string) - Required - The unique name of the publication provider. #### Query Parameters - **resource** (Record/Collection) - Required - The resource to eventually publish. - **user** (User) - Optional - The user to check for OAuth2 connection status. ### Response #### Success Response (200) - **provider** (Object) - The publication provider details or null if not found. ``` -------------------------------- ### get_role_rules Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Get all existing role rules corresponding to roles of a specific object. ```APIDOC ## get_role_rules(object_name, object_id, rule_type=None) ### Description Get all existing role rules corresponding to roles of a specific object. ### Parameters - **object_name** (string) - Required - The type of object. - **object_id** (integer/string) - Required - The ID of the object. - **rule_type** (string) - Optional - A type to limit the role rules with. ### Response - Returns the filtered role rules as a query. ``` -------------------------------- ### POST /licenses Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Creates a new license and adds it to the database. ```APIDOC ## POST /licenses ### Description Create a new license and add it to the database session. ### Method POST ### Parameters #### Request Body - **name** (string) - Required - The unique name of the license. - **title** (string) - Required - The title of the license. - **url** (string) - Optional - The URL of the license. ### Response #### Success Response (200) - **license** (object) - The newly created License object. ``` -------------------------------- ### GET /licenses Source: https://kadi4mat.readthedocs.io/en/stable/apiref/lib.html Retrieves a list of all licenses stored in the database, with an optional filter. ```APIDOC ## GET /licenses ### Description Get all licenses stored in the database, optionally filtered by title or name. ### Method GET ### Parameters #### Query Parameters - **filter_term** (string) - Optional - A case-insensitive term to filter the licenses by their title or name. ### Response #### Success Response (200) - **licenses** (query) - The licenses ordered by their title in ascending order. ```