Modules

This section contains all API references of the kadi.modules package that were not already listed in other sections.

Accounts

class kadi.modules.accounts.providers.core.AuthProviderBase[source]

Bases: abc.ABC

Base class for authentication providers.

Each provider should override register() and authenticate() and specify its meta attributes in Meta. Those methods should return an identity object subclassing Identity or a UserInfo object respectively. If passwords are allowed to be changed by users, allow_password_change() and change_password() need to be overridden as well, returning a boolean value indicating whether passwords can be changed and whether the change was successful repectively.

The function init_auth_providers() needs to be called beforehand to initialize the application’s configuration for use with the registered authentication providers.

class Meta[source]

Bases: object

Container to store meta class attributes.

provider_type = None

The type of a provider.

defaults = {}

The default configuration values of a provider.

Each provider should at least specify a title alongside all other provider-specific configuration.

class UserInfo(is_authenticated, data=None)[source]

Bases: object

Wrapper class to store user information.

Should be returned by authenticate().

Parameters
  • is_authenticated – Flag to indicate if the represented user is authenticated or not.

  • data – (optional) The wrapped user data. This should generally be an object-like type representing the user information or the actual user.

classmethod create_identity(*, system_role, identity_model, **kwargs)[source]

Create a new user and a corresponding identity.

The latest identity of the user will be set to the newly created one automatically. Additionally, all existing role rules will be applied to the newly created user in a background task.

Note that this function issues a database commit or rollback.

Parameters
  • system_role – The system role of the user.

  • identity_model – The identity model to use for creating the user’s identity.

  • **kwargs – Additional keyword arguments to pass to the identity model’s create method.

Returns

The newly created identity or None if it could not be created.

classmethod is_registered()[source]

Check if a provider is registered in the application.

Returns

True if the provider is registered, False otherwise.

classmethod get_config()[source]

Get a provider’s config from the current application object.

Returns

The provider’s configuration dictionary.

classmethod allow_password_change()[source]

Check whether a provider supports changing passwords.

Returns

Flag indicating whether the provider supports changing passwords.

abstract classmethod change_password(username, old_password, new_password)[source]

Change a password of an existing user if supported by a provider.

Parameters
  • username – The unique username of the user.

  • old_password – The current password of the user.

  • new_password – The new password of the user.

Returns

A boolean value indicating whether the password change was successful.

Raises

NotImplementedError – If changing a user’s password is not supported by the provider.

kadi.modules.accounts.providers.core.init_auth_providers(app)[source]

Initialize all authentication providers for use in the application.

Makes use of the AUTH_PROVIDER_TYPES and AUTH_PROVIDERS specified in the application’s configuration. During initialization, the AUTH_PROVIDERS configuration will be modified to use an ordered dictionary instead and will also include the following additional keys:

  • "provider_class": A reference to the provider class.

  • "identity_class": A reference to the identity class.

  • "form_class": A reference to the form class.

Parameters

app – The application object.

class kadi.modules.accounts.providers.ldap.LDAPProvider[source]

Bases: kadi.modules.accounts.providers.core.AuthProviderBase

LDAP authentication provider.

class Meta[source]

Bases: object

Container to store meta class attributes.

provider_type = 'ldap'

The type of the provider.

defaults = {'active_directory': False, 'allow_password_change': False, 'bind_pw': None, 'bind_user': None, 'default_system_role': 'member', 'displayname_attr': 'displayName', 'email_attr': 'mail', 'encryption': None, 'firstname_attr': None, 'host': '', 'lastname_attr': None, 'port': 389, 'send_old_password': False, 'title': 'Login with LDAP', 'username_attr': 'uid', 'users_dn': '', 'validate_cert': True}

The default configuration values of the provider.

classmethod register(*, username, email, displayname, system_role=None, **kwargs)[source]

Register a new LDAP user.

If an identity with the given username already exists, that identity will be updated with the given email.

Note that this function issues a database commit or rollback.

Parameters
  • username – The user’s unique name.

  • email – The user’s email address.

  • displayname – The users’s display name.

  • system_role – (optional) The user’s system role. Defaults to "member".

Returns

A new LDAPIdentity object linked with a new user or an existing, updated LDAPIdentity. Returns None if the identity could not be created or if this provider is not registered in the application.

classmethod authenticate(*, username, password, **kwargs)[source]

Authenticate an LDAP user.

Parameters
  • username – The user’s unique name to use for binding to the LDAP server and for searching their entry in the database.

  • password – The user’s password to use for binding to the LDAP server.

Returns

An instance of UserInfo or None if this provider is not registered in the application. In case the authentication is successful, the contained data is an object containing the username, email and display name of the user as attributes username, email and displayname respectively.

class kadi.modules.accounts.providers.local.LocalProvider[source]

Bases: kadi.modules.accounts.providers.core.AuthProviderBase

Local authentication provider.

class Meta[source]

Bases: object

Container to store meta class attributes.

provider_type = 'local'

The type of the provider.

defaults = {'allow_registration': False, 'default_system_role': 'member', 'email_confirmation_required': False, 'title': 'Login with credentials'}

The default configuration values of the provider.

classmethod registration_allowed()[source]

Check if this provider allows registration of new users.

Returns

True if registration is allowed, False if not or if this provider is not registered in the application.

classmethod email_confirmation_required()[source]

Check if this provider requires email confirmation.

Returns

True if email confirmation is required, False if not or if this provider is not registered in the application.

classmethod register(*, username, email, displayname, password, system_role=None, **kwargs)[source]

Register a new local user.

Note that this function issues a database commit or rollback.

Parameters
  • username – The user’s unique name.

  • email – The user’s email address.

  • displayname – The users’s display name.

  • password – The users’s password.

  • system_role – (optional) The user’s system role. Defaults to "member".

Returns

A new LocalIdentity object linked with a new user or None if the identity could not be created or if this provider is not registered in the application.

classmethod authenticate(*, username, password, **kwargs)[source]

Authenticate a local user.

Parameters
  • username – The user’s unique name to search in the local database.

  • password – The user’s password to call LocalIdentity.check_password() with.

Returns

An instance of UserInfo or None if this provider is not registered in the application. In case the authentication is successful, the contained data is the user’s existing LocalIdentity.

class kadi.modules.accounts.providers.shib.ShibProvider[source]

Bases: kadi.modules.accounts.providers.core.AuthProviderBase

Shibboleth authentication provider.

Currently tested with the official Shibboleth Service Provider 3 in combination with the Apache web server using mod_shib.

class Meta[source]

Bases: object

Container to store meta class attributes.

provider_type = 'shib'

The type of the provider.

defaults = {'default_system_role': 'member', 'displayname_attr': 'displayName', 'email_attr': 'mail', 'env_encoding': 'latin-1', 'firstname_attr': 'givenName', 'idp_displayname_attr': 'Meta-displayName', 'idp_entity_id_attr': 'Shib-Identity-Provider', 'idp_support_contact_attr': 'Meta-supportContact', 'idps': [], 'lastname_attr': 'sn', 'multivalue_separator': ';', 'sp_entity_id': '/shibboleth', 'sp_logout_initiator': '/Shibboleth.sso/Logout', 'sp_session_initiator': '/Shibboleth.sso/Login', 'title': 'Login with Shibboleth', 'username_attr': 'eppn'}

The default configuration values of the provider.

The configured identity providers ("idps") must be specified as a list of dictionaries, each dictionary containing the entity ID ("entity_id") and display name ("name") of the provider.

classmethod get_choices()[source]

Get all configured identity providers for use in a selection.

Returns

A list of tuples, each tuple containing the entity ID and display name of the identity provider, sorted by display name. The first entry in the list represents the empty default choice in a selection where both values are set to an empty string. If this provider is not registered in the application, the returned list will only contain the default choice.

classmethod get_session_initiator(entity_id, target)[source]

Get the configured Shibboleth session initiator.

The session initiator is simply an URL consisting of the configured login endpoint of the service provider and containing the given arguments, the entity_id and target URL, as query parameters.

Parameters
  • entity_id – The entity ID of the identity provider to use for login.

  • target – The URL to redirect to after logging in successfully.

Returns

The generated session initiator URL. If this provider is not registered in the application, an empty string will be returned.

classmethod get_logout_initiator(target)[source]

Get the configured Shibboleth local logout initiator.

The local logout initiator is simply an URL consisting of the configured logout endpoint of the service provider and containing the given argument, the target URL, as query parameter.

Parameters

target – The URL to redirect to after logging out successfully.

Returns

The generated local logout initiator URL. If this provider is not registered in the application, an empty string will be returned.

classmethod contains_valid_idp()[source]

Check if the Shibboleth session contains a valid identity provider.

In this case, valid means that the entity ID of an identity provider is contained in the configured list of identity providers. This requires the entity ID to check to be available as an environment variable, so a valid Shibboleth session is required.

Returns

True if the identity provider is valid, False if it is not or if there is no valid Shibboleth session or if this provider is not registered in the application.

classmethod get_metadata()[source]

Get the metadata of the Shibboleth session.

Returns

An object containing the entity ID of the service provider, the entity ID of the identity provider, its displayname and its support contact email address as attributes sp_entity_id, idp_entity_id, idp_displayname and idp_support_contact respectively. This requires those attributes to be available as an environment variables, so a valid Shibboleth session is required. If this provider is not registered in the application, None will be returned.

classmethod get_required_attributes()[source]

Get all attributes required for successful authentication.

Currently, the only required attributes are the user’s unique username and email address.

Returns

A dictionary containing the required keys to get as environment variables and their respective values. If the identity provider did not provide an attribute, the value will be None for the respective key or for all of them if no valid Shibboleth session exists. If this provider is not registered in the application, None will be returned.

classmethod register(*, username, email, displayname, system_role=None, **kwargs)[source]

Register a new Shibboleth user.

If an identity with the given username already exists, that identity will be updated with the given email.

Note that this function issues a database commit or rollback.

Parameters
  • username – The user’s unique name.

  • email – The user’s email address.

  • displayname – The users’s display name.

  • system_role – (optional) The user’s system role. Defaults to "member".

Returns

A new ShibIdentity object linked with a new user or an existing, updated ShibIdentity. Returns None if the identity could not be created or if this provider is not registered in the application.

classmethod authenticate(**kwargs)[source]

Authenticate a Shibboleth user.

No arguments need to be given, as the necessary user attributes need to be available as environment variables if a valid Shibboleth session exists.

Returns

An instance of UserInfo or None if this provider is not registered in the application. In case the authentication is successful, the contained data is an object containing the username, email and display name of the user as attributes username, email and displayname respectively.

kadi.modules.accounts.core.purge_user(user)[source]

Purge an existing user.

This will completely delete the user and all their resources from the database.

Note that this function issues one or more database commits.

Parameters

user – The user to purge.

kadi.modules.accounts.core.merge_users(first_user, second_user)[source]

Merge two users together.

This will migrate the ownership of all identities, resources and permissions from the second user to the first user. The first user is then also able to log in using both identities.

Parameters
  • first_user – The user to merge the second user into.

  • second_user – The user to merge into the first user.

kadi.modules.accounts.forms.get_login_form(provider)[source]

Get a login form based on a given authentication provider.

All fields and labels will have the given provider’s type appended to their IDs in the form of "<field_id>_<provider>", so rendering multiple forms on a single page does not lead to issues because of duplicate IDs.

Parameters

provider – An authentication provider as specificed in AUTH_PROVIDER_TYPES in the application’s configuration.

Returns

The login form.

class kadi.modules.accounts.forms.CredentialsLoginForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A general login form using a username and a password.

class kadi.modules.accounts.forms.ShibLoginForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A login form for use in Shibboleth.

The form uses a selection field which has to be populated with the entity IDs and display names of all valid identity providers.

class kadi.modules.accounts.forms.RegistrationForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in registering new local users.

class kadi.modules.accounts.forms.EmailConfirmationForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in mandatory email confirmation for local users.

Offers an optional email field to let a user change their current email address.

class kadi.modules.accounts.forms.RequestPasswordResetForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in requesting a password reset for local users.

class kadi.modules.accounts.forms.ResetPasswordForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in changing a local user’s password.

class kadi.modules.accounts.schemas.IdentitySchema(*args, _internal=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent identities.

See Identity.

class kadi.modules.accounts.schemas.UserSchema(*args, _internal=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent users.

See User.

kadi.modules.accounts.utils.login_user(identity, **kwargs)[source]

Login a user by their identity.

Wraps Flask-Login’s login_user function but also makes sure to update the user’s current identity.

Parameters

identity – The identity to log in with.

Returns

True if the login was successful, False otherwise.

kadi.modules.accounts.utils.save_user_image(user, file_object)[source]

Set an image file as a user’s profile image.

Uses kadi.lib.storage.local.save_as_thumbnail() to create and save a thumbnail of the given image. If the image cannot be saved, delete_user_image() will be called.

Parameters
  • user – The user to set the new profile image for.

  • file_object – See kadi.lib.storage.local.save_as_thumbnail().

kadi.modules.accounts.utils.delete_user_image(user)[source]

Delete a user’s profile image if one exists.

Uses kadi.lib.storage.local.delete_thumbnail() to delete the actual thumbnail file.

Parameters

user – The user whose profile image should be deleted.

kadi.modules.accounts.utils.json_user(user)[source]

Convert a user into a JSON representation.

Parameters

user – The user to convert.

Returns

The converted user.

kadi.modules.accounts.utils.get_filtered_user_ids(filter_term)[source]

Get all IDs of users filtered by the given term.

Convenience function to filter users based on their identities. Note that users with multiple identities are only returned once and merged users are always excluded, as they do not have any identities anymore.

Parameters

filter_term – The term to filter the users with based on the display name and username of each user’s identities.

Returns

The filtered user IDs as query.

Collections

kadi.modules.collections.core.create_collection(*, identifier, title, creator=None, description='', visibility='private', state='active', tags=None)[source]

Create a new collection.

This will also create all default permissions of the collection.

Note that this function issues a database commit or rollback.

Parameters
Returns

The created collection or None if the collection could not be created.

kadi.modules.collections.core.update_collection(collection, tags=None, **kwargs)[source]

Update an existing collection.

Note that this function issues a database commit or rollback.

Parameters
  • collection – The collection to update.

  • tags – (optional) A list of tag names to tag the collection with. See also Tag.

  • **kwargs – Keyword arguments that will be passed to kadi.lib.db.update_object().

Returns

True if the collection was updated successfully, False otherwise.

kadi.modules.collections.core.delete_collection(collection)[source]

Delete an existing collection.

This will perform a soft deletion, i.e. the collections’s state will be set to "deleted".

Note that this function issues a database commit.

Parameters

collection – The collection to delete.

kadi.modules.collections.core.restore_collection(collection)[source]

Restore a deleted collection.

Note that this function issues a database commit.

Parameters

collection – The collection to restore.

kadi.modules.collections.core.purge_collection(collection)[source]

Purge an existing collection.

This will completely delete the collection from the database.

Parameters

collection – The collection to purge.

Link two collections together.

Note that this function aquires a lock on the given collections.

Parameters
  • parent_collection – The parent collection.

  • child_collection – The child collection.

  • user – (optional) The user performing the link operation. Defaults to the current user.

Returns

True if the collections were linked successfully, False if both given collections refer to the same object, if the given child collection already has a parent or if the given child collection is already a parent of the parent collection.

Raises

KadiPermissionError – If the user performing the operation does not have the necessary permissions.

kadi.modules.collections.core.search_collections(query, sort='_score', visibility=None, tags=None, tag_operator='or', page=1, per_page=10)[source]

Search for and filter all collections that the current user can read.

Uses kadi.lib.resources.utils.search_resources().

Parameters
  • query – The search query as string to search for the title, identifier and plain description of the collection.

  • sort – (optional) See kadi.lib.resources.utils.search_resources().

  • visibility – (optional) A value to filter the visibility of the searched collections with.

  • tags – (optional) A list of tag names to filter the collections with before searching. All given tags are filtered using the operator specified via tag_operator.

  • tag_operator – (optional) The operator to filter the tags with. One of "or" or "and".

  • page – (optional) See kadi.lib.resources.utils.search_resources().

  • per_page – (optional) See kadi.lib.resources.utils.search_resources().

Returns

The search results as returned by kadi.lib.resources.utils.search_resources().

kadi.modules.collections.export.get_export_data(collection, export_type, export_filter=None, user=None)[source]

Export a collection in a given format.

Parameters
  • collection – The collection to export.

  • export_type – The export format, one of "json" or "qr".

  • export_filter

    (optional) A dictionary specifying various filters in order to exclude certain information from the returned export data. Currently only usable in combination with the "json" export type.

    Example:

    {
        # Whether user information about the creator of the collection or any
        # linked resource should be excluded.
        "user": False,
    }
    

  • user – (optional) The user to check for various access permissions when generating the export data. Defaults to the current user.

Returns

The exported collection data, depending on the given export type, or None if an unknown export type was given.

class kadi.modules.collections.forms.BaseCollectionForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

Base form class for use in creating or updating collections.

Parameters

collection – (optional) A collection used for prefilling the form.

class kadi.modules.collections.forms.NewCollectionForm(*args, **kwargs)[source]

Bases: kadi.modules.collections.forms.BaseCollectionForm

A form for use in creating new collections.

Parameters
  • collection – (optional) See BaseCollectionForm.

  • user – (optional) A user that will be used for checking various permissions when prefilling the form. Defaults to the current user.

class kadi.modules.collections.forms.EditCollectionForm(*args, **kwargs)[source]

Bases: kadi.modules.collections.forms.BaseCollectionForm

A form for use in editing existing collections.

Parameters

collection – The collection to edit, used for prefilling the form.

class kadi.modules.collections.forms.LinkRecordsForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in linking collections with records.

class kadi.modules.collections.forms.LinkCollectionsForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in linking collections with other collections.

class kadi.modules.collections.forms.AddPermissionsBaseForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

Base form class for use in adding user or group roles concerning collections.

validate(extra_validators=None)[source]

Validate the form by calling validate on each field. Returns True if validation passes.

If the form defines a validate_<fieldname> method, it is appended as an extra validator for the field’s validate.

Parameters

extra_validators – A dict mapping field names to lists of extra validator methods to run. Extra validators run after validators passed when creating the field. If the form has validate_<fieldname>, it is the last extra validator.

class kadi.modules.collections.forms.AddCollectionPermissionsForm(*args, **kwargs)[source]

Bases: kadi.modules.collections.forms.AddPermissionsBaseForm

A form for use in adding user or group roles to a collection.

class kadi.modules.collections.forms.AddRecordsPermissionsForm(*args, **kwargs)[source]

Bases: kadi.modules.collections.forms.AddPermissionsBaseForm

A form for use in adding or removing user or group roles of linked records.

class kadi.modules.collections.mappings.CollectionMapping(meta=None, **kwargs)[source]

Bases: elasticsearch_dsl.document.Document, kadi.lib.search.core.MappingMixin

Search mapping for collections.

See Collection.

class kadi.modules.collections.schemas.CollectionSchema(previous_collection=None, linked_record=None, parent_collection=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent collections.

See Collection.

Parameters
  • previous_collection – (optional) A collection whose identifier should be excluded when checking for duplicates while deserializing.

  • linked_record – (optional) A record that is linked to each collection that should be serialized. Will be used to build endpoints for corresponding actions.

  • parent_collection – (optional) A collection that is the parent of each collection that should be serialized. Will be used to build endpoints for corresponding actions.

kadi.modules.collections.utils.get_parent_collections(collection, user=None)[source]

Get all parents of a collection that a user can access.

In this context having access to a collection means having read permission for it. Note that as soon as a parent collection is not accessible or inactive, no further potential parents are collected.

Parameters
  • collection – The collection to get the parents of.

  • user – (optional) The user to check for access permissions when retrieving the collections. Defaults to the current user.

Returns

A list of parent collections starting with the immediate parent of the given collection.

kadi.modules.collections.utils.get_child_collections(collection, user=None)[source]

Recursively get all children of a collection that a user can access.

In this context having access to a collection means having read permission for it. Note that if a collection is not accessible or inactive, no further potential children of this collection are collected.

Parameters
  • collection – The collection to get the children of.

  • user – (optional) The user to check for access permissions when retrieving the collections. Defaults to the current user.

Returns

A list of child collections in unspecified order.

kadi.modules.collections.utils.get_child_collection_records(collection, actions=None, user=None)[source]

Recursively get all records of a collection hierarchy that a user can access.

In this context, the collection hierarchy refers to the given collection and all its direct or indirect children. Having access to a child collection or record means having read permission for it.

Uses get_child_collections() to determine the children of the given collection.

Parameters
  • collection – The collection to get the children and records of.

  • actions – (optional) Further actions to check the access permissions of the records for.

  • user – (optional) The user to check for access permissions when retrieving the collections and records. Defaults to the current user.

Returns

The records as query. Note that duplicate records are already filtered out.

Groups

kadi.modules.groups.core.create_group(*, identifier, title, creator=None, description='', visibility='private', state='active')[source]

Create a new group.

This will also create all default permissions of the group.

Note that this function issues a database commit or rollback.

Parameters
Returns

The created group or None if the group could not be created.

kadi.modules.groups.core.update_group(group, **kwargs)[source]

Update an existing group.

Note that this function issues a database commit or rollback.

Parameters
Returns

True if the group was updated successfully, False otherwise.

kadi.modules.groups.core.delete_group(group)[source]

Delete an existing group.

This will perform a soft deletion, i.e. the groups’s state will be set to "deleted".

Note that this function issues a database commit.

Parameters

group – The group to delete.

kadi.modules.groups.core.restore_group(group)[source]

Restore a deleted group.

Note that this function issues a database commit.

Parameters

group – The group to restore.

kadi.modules.groups.core.purge_group(group)[source]

Purge an existing group.

This will completely delete the group from the database.

Parameters

group – The group to purge.

kadi.modules.groups.core.search_groups(query, sort='_score', visibility=False, member_only=False, page=1, per_page=10)[source]

Search for and filter all groups that the current user can read.

Uses kadi.lib.resources.utils.search_resources().

Parameters
Returns

The search results as returned by kadi.lib.resources.utils.search_resources().

class kadi.modules.groups.forms.BaseGroupForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

Base form class for use in creating or updating groups.

class kadi.modules.groups.forms.NewGroupForm(*args, **kwargs)[source]

Bases: kadi.modules.groups.forms.BaseGroupForm

A form for use in creating new groups.

class kadi.modules.groups.forms.EditGroupForm(*args, **kwargs)[source]

Bases: kadi.modules.groups.forms.BaseGroupForm

A form for use in editing existing groups.

Parameters

group – The group to edit, used for prefilling the form.

class kadi.modules.groups.forms.AddMembersForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in adding members (i.e. user roles) to a group.

validate(extra_validators=None)[source]

Validate the form by calling validate on each field. Returns True if validation passes.

If the form defines a validate_<fieldname> method, it is appended as an extra validator for the field’s validate.

Parameters

extra_validators – A dict mapping field names to lists of extra validator methods to run. Extra validators run after validators passed when creating the field. If the form has validate_<fieldname>, it is the last extra validator.

class kadi.modules.groups.forms.AddRulesForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in adding new username role rules for groups.

class kadi.modules.groups.mappings.GroupMapping(meta=None, **kwargs)[source]

Bases: elasticsearch_dsl.document.Document, kadi.lib.search.core.MappingMixin

Search mapping for groups.

See Group.

class kadi.modules.groups.schemas.GroupSchema(previous_group=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent groups.

See Group.

Parameters

previous_group – (optional) A group whose identifier should be excluded when checking for duplicates while deserializing.

kadi.modules.groups.utils.get_user_groups(user=None)[source]

Get all groups a user is a member of.

Group membership currently works through roles. As long as a user has any role inside a group, they are a member of it. Note that inactive groups will be filtered out.

Parameters

user – (optional) The user to get the groups for. Defaults to the current user.

Returns

The groups of the given user as query.

kadi.modules.groups.utils.save_group_image(group, file_object)[source]

Set an image file as a groups’s profile image.

Uses kadi.lib.storage.local.save_as_thumbnail() to create and save a thumbnail of the given image. If the image cannot be saved, delete_group_image() will be called.

Parameters
  • group – The group to set the new profile image for.

  • file_object – See kadi.lib.storage.local.save_as_thumbnail().

kadi.modules.groups.utils.delete_group_image(group)[source]

Delete a groups’s profile image if one exists.

Uses kadi.lib.storage.local.delete_thumbnail() to delete the actual thumbnail file.

Parameters

group – The group of which the profile image should be deleted.

Main

kadi.modules.main.tasks.clean_resources(inside_task=False)[source]

Clean all deleted users and expired, deleted resources.

Note that this function issues one or more database commits.

Parameters

inside_task – (optional) A flag indicating whether the function is executed in a task. In that case, additional information will be logged.

Notifications

kadi.modules.notifications.core.create_notification_data(notification)[source]

Create a notification suitable for presenting it to a client.

Parameters

notification – A Notification object, currently only of type "task_status".

Returns

A tuple containing the title and the HTML body of the notification.

kadi.modules.notifications.core.dismiss_notification(notification)[source]

Dismiss a notification.

If the notification is of type "task_status", the referenced task will be revoked as well.

Parameters

notification – The Notification to dismiss.

kadi.modules.notifications.mails.send_email_confirmation_mail(email, displayname, token)[source]

Send an email confirmation mail in a background task.

Uses kadi.modules.notifications.tasks.start_send_mail_task() to send the mail.

Parameters
Returns

True if the task was started successfully, False otherwise.

kadi.modules.notifications.mails.send_password_reset_mail(email, displayname, token)[source]

Send a password reset mail in a background task.

Uses kadi.modules.notifications.tasks.start_send_mail_task() to send the mail.

Parameters
Returns

True if the task was started successfully, False otherwise.

class kadi.modules.notifications.schemas.NotificationSchema(*args, _internal=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent notifications.

See Notification.

kadi.modules.notifications.tasks.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)[source]

Send a mail in a background task.

See kadi.lib.mails.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.

Returns

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.

Permissions

kadi.modules.permissions.core.has_permission(subject, action, object_name, object_id, check_groups=True, check_defaults=True)[source]

Check if a user or group has permission to perform a specific action.

Includes all fine-grained permissions as well as all permissions from the roles of the user or group.

Parameters
  • subject – The user or group object.

  • action – The action to check for.

  • object_name – The type of object.

  • object_id – The ID of a specific object or None for a global permission.

  • check_groups – (optional) Flag indicating whether the groups of a user should be checked as well for their permissions.

  • check_defaults – (optional) Flag indicating whether the default permissions of any object should be checked as well.

Returns

True if permission is granted, False otherwise or if the object instance to check does not exist.

kadi.modules.permissions.core.get_permitted_objects(subject, action, object_name, check_groups=True, check_defaults=True)[source]

Get all objects a user or group has a specific permission for.

Includes all fine-grained permissions as well as all permissions from the roles of the user or group.

Parameters
  • subject – The user or group object.

  • action – The action to check for.

  • object_name – The type of object.

  • check_groups – (optional) Flag indicating whether the groups of a user should be checked as well for their permissions.

  • check_defaults – (optional) Flag indicating whether the default permissions of the objects should be checked as well.

Returns

The permitted objects as query or None if the object type does not exist.

kadi.modules.permissions.core.add_role(subject, object_name, object_id, role_name, update_timestamp=True)[source]

Add an existing role to a user or group.

Parameters
  • subject – The user or group.

  • object_name – The type of object the role refers to.

  • object_id – The ID of the object.

  • role_name – The name of the role.

  • update_timestamp – (optional) Flag indicating whether the timestamp of the underlying object should be updated or not. The object needs to implement TimestampMixin in that case.

Returns

True if the role was added successfully, False if the subject already has a role related to the given object.

Raises

ValueError – If no object or role with the given arguments exists or when trying to add a role to the object that is being referred to by that role.

kadi.modules.permissions.core.remove_role(subject, object_name, object_id, update_timestamp=True)[source]

Remove an existing role of a user or group.

Parameters
  • subject – The user or group.

  • object_name – The type of object the role refers to.

  • object_id – The ID of the object.

  • update_timestamp – (optional) Flag indicating whether the timestamp of the underlying object should be updated or not. The object needs to implement TimestampMixin in that case.

Returns

True if the role was removed successfully, False if there was no role to remove.

Raises

ValueError – If no object with the given arguments exists.

kadi.modules.permissions.core.set_system_role(user, system_role)[source]

Set an existing system role for a given user.

Parameters
  • user – The user to set the system role for.

  • system_role – The name of the system role to set.

Returns

True if the system role was set successfully, False otherwise or if the given system role does not exist.

kadi.modules.permissions.core.setup_permissions(object_name, object_id)[source]

Setup the default permissions of an object.

The default actions and roles have to be specified in a Meta.permissions attribute in each model.

Example:

class Foo:
    class Meta:
        permissions = {
            "actions": [
                ("read", "Read this object."),
                ("update", "Edit this object."),
            ],
            "roles": [("admin", ["read", "update"])],
        }
Parameters
  • object_name – The type of object the permissions refer to.

  • object_id – The ID of the object.

Returns

True if the permissions were set up successfully, False otherwise.

Raises

ValueError – If no object with the given arguments exists.

kadi.modules.permissions.core.delete_permissions(object_name, object_id)[source]

Delete all permissions of an object.

Parameters
  • object_name – The type of object the permissions refer to.

  • object_id – The ID of the object.

kadi.modules.permissions.core.create_role_rule(object_name, object_id, role_name, rule_type, condition, update_timestamp=True)[source]

Create a new role rule.

Parameters
  • object_name – The type of object the role refers to.

  • object_id – The ID of the object.

  • role_name – The name of the role.

  • rule_type – The type of the role rule.

  • condition – The condition of the role rule.

  • update_timestamp – (optional) Flag indicating whether the timestamp of the underlying object should be updated or not. The object needs to implement TimestampMixin in that case.

Returns

The created role rule or None if the role rule could not be created.

kadi.modules.permissions.core.remove_role_rule(role_rule, update_timestamp=True)[source]

Remove an existing role rule.

Parameters
  • role_role – The role rule to remove.

  • update_timestamp – (optional) Flag indicating whether the timestamp of the underlying object should be updated or not. The object needs to implement TimestampMixin in that case.

kadi.modules.permissions.core.apply_role_rule(role_rule, user=None)[source]

Apply a given role rule.

Parameters
  • role_rule – The role rule to apply.

  • user – (optional) A specific user to apply the role rule to. If not given, all existing users are considered.

class kadi.modules.permissions.schemas.PermissionSchema(*args, _internal=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent permissions.

See Permission.

class kadi.modules.permissions.schemas.RoleSchema(*args, _internal=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent roles.

See Role.

class kadi.modules.permissions.schemas.RoleRuleSchema(*args, _internal=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent role rules.

See RoleRule.

class kadi.modules.permissions.schemas.UserRoleSchema(obj=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent user roles.

Parameters

obj – (optional) An object that the current user role refers to.

dump_from_iterable(iterable)[source]

Serialize an iterable containing user roles.

Parameters

iterable – An iterable yielding tuples each containing a user and a corresponding role.

Returns

The serialized output.

class kadi.modules.permissions.schemas.GroupRoleSchema(obj=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent group roles.

Parameters

obj – (optional) An object that the current group role refers to.

dump_from_iterable(iterable)[source]

Serialize an iterable containing group roles.

Parameters

iterable – An iterable yielding tuples each containing a group and a corresponding role.

Returns

The serialized output.

kadi.modules.permissions.tasks.start_apply_role_rules_task(role_rule=None, user=None)[source]

Apply a specific or all existing role rules in a background task.

Parameters
  • role_rule – (optional) A specific role rule to apply.

  • user – (optional) A specific user to apply the role rule(s) to. If not given, all existing users are considered.

Returns

True if the task was started successfully, False otherwise.

kadi.modules.permissions.utils.permission_required(action, object_name, object_id_identifier, status_code=403)[source]

Decorator to add access restrictions to a view function.

If the current user is not authenticated, the decorator will behave the same as Flask-Login’s login_required decorator. If the object or object instance to check do not exist, the request will automatically get aborted with a 404 status code.

Uses kadi.modules.permissions.core.has_permission() to check for access permissions.

Parameters
kadi.modules.permissions.utils.initialize_system_role(role_name)[source]

Initialize a system role with corresponding global permissions.

Will create the given system role as defined in SYSTEM_ROLES in the application’s configuration as well as all permissions for the global actions of the listed objects, which have to be specified in the Meta.permissions attribute in each corresponding model.

Example:

class Foo:
    class Meta:
        permissions = {
            "global_actions": [
                ("create", "Create objects."),
                ("read", "Read all objects."),
            ],
        }
Parameters

role_name – The name of the system role to initialize.

Returns

The created role object or None if the role already exists.

Raises

ValueError – If the given role is not a configured system role or if any of the specified global actions is invalid.

kadi.modules.permissions.utils.get_user_roles(object_name, object_id=None)[source]

Get all users and roles for a specific object or object type.

Parameters
  • object_name – The type of the object.

  • object_id – (optional) The ID of a specific object.

Returns

The users and corresponding roles of the object(s) as query object.

kadi.modules.permissions.utils.get_group_roles(object_name, object_id=None)[source]

Get all groups and roles for a specific object or object type.

Note that inactive groups will be filtered out.

Parameters
  • object_name – The type of the object.

  • object_id – (optional) The ID of a specific object.

Returns

The groups and corresponding roles of the object(s) as query object.

kadi.modules.permissions.utils.get_object_roles(object_name)[source]

Get all possible roles and corresponding permissions of an object type.

Parameters

object_name – The type of the object.

Returns

A list of dictionaries in the following form:

[
    {
        "name": "admin",
        "permissions": [
            {
                "action": "read,
                "description": "Read this resource.",
            }
        ]
    }
]

kadi.modules.permissions.utils.get_action_description(action, object_name)[source]

Get the description of an action corresponding to a specific permission.

Parameters
  • action – The name of the action.

  • object_name – The type of the object the action belongs to.

Returns

The description or None if no suitable action or no model corresponding to the object type could be found.

kadi.modules.permissions.utils.create_username_role_rule(object_name, object_id, role_name, identity_type, pattern)[source]

Create a role rule with conditions to check the values of usernames.

The conditions of username rules consist of an identity type (identity_type) and a pattern (pattern). The former specifies the type of identities to check the usernames of, while the letter specifies the possible values of the usernames. The pattern may include one or more wildcards using "*", which match a sequence of zero or more characters.

Parameters
Returns

See kadi.modules.permissions.core.create_role_rule().

kadi.modules.permissions.utils.get_role_rules(object_name, object_id, rule_type=None)[source]

Get all existing role rules of a specific role.

Parameters
  • object_name – The type of object the role refers to.

  • object_id – The ID of the object the role refers to.

  • rule_type – (optional) A type to limit the role rules with.

Returns

The filtered role rules as query.

Records

kadi.modules.records.core.create_record(*, identifier, title, creator=None, type=None, description='', license=None, extras=None, visibility='private', state='active', tags=None)[source]

Create a new record.

This will also create all default permissions of the record.

Note that this function issues a database commit or rollback.

Parameters
Returns

The created record or None if the record could not be created.

kadi.modules.records.core.update_record(record, tags=None, **kwargs)[source]

Update an existing record.

Note that this function issues a database commit or rollback.

Parameters
  • record – The record to update.

  • tags – (optional) A list of tag names to tag the record with. See also Tag.

  • **kwargs – Keyword arguments that will be passed to kadi.lib.db.update_object(). If the name of a license is given via license, the reference to the license object will be updated accordingly.

Returns

True if the record was updated successfully, False otherwise.

kadi.modules.records.core.delete_record(record)[source]

Delete an existing record.

This will perform a soft deletion, i.e. the records’s state will be set to "deleted".

Note that this function issues a database commit.

Parameters

record – The record to delete.

kadi.modules.records.core.restore_record(record)[source]

Restore a deleted record.

Note that this function issues a database commit.

Parameters

record – The record to restore.

kadi.modules.records.core.purge_record(record)[source]

Purge an existing record.

This will completely delete the record from the database including all its files.

Note that this function may issue one or more database commits.

Parameters

record – The record to delete.

Link two records together.

Parameters
  • name – The name of the record link.

  • record_from – The record that is being linked from.

  • record_to – The record that is being linked to.

  • user – (optional) The user performing the link operation. Defaults to the current user.

Returns

The new record link or None if it could not be created, in case both given records refer to the same object.

Raises

KadiPermissionError – If the user performing the operation does not have the necessary permissions.

kadi.modules.records.core.search_records(query, extras=None, sort='_score', visibility=None, collections=None, child_collections=False, record_types=None, tags=None, tag_operator='or', mimetypes=None, page=1, per_page=10)[source]

Search for and filter all records that the current user can read.

Uses kadi.lib.resources.utils.search_resources().

Parameters
  • query – The search query as string to search for the title, identifier and plain description of the record.

  • extras

    (optional) A list of dictionaries to specifiy search queries within the extra metadata of records. Each query can contain a link type, a key, a type and one or multiple values depending on the type. See also Record.extras.

    Example:

    [
        {
            # The link type, one of "and" or "or". Note that the link type of
            # the first query does not actually matter and can be left out.
            "link": "and",
            # The key of the metadata entry.
            "key": "sample key",
            # The type of the metadata entry, one of "str", "numeric", "bool" or
            # "date". Note that there are no separate types for integer and
            # float values.
            "type": "str",
            # The string value of the metadata entry if the type is "str".
            "str": "string",
            # The numeric value of the metadata entry if the type is "numeric".
            # Either a minimum value, a maximum value or both can be specified.
            # Specifying a unit is optional.
            "numeric": {"min": 0, "max": 1, "unit": "cm"},
            # The boolean value of the metadata entry if the type is "bool", one
            # of True, "true", False or "false".
            "bool": True,
            # The formatted date value of the metadata entry if the type is
            # "date". Either a minimum value, a maximum value or both can be
            # specified.
            "date": {
                "min": "2020-07-01T00:00:00.000Z",
                "max": "2020-07-02T00:00:00.000Z",
            },
        },
    ]
    

  • sort – (optional) See kadi.lib.resources.utils.search_resources().

  • visibility – (optional) A value to filter the visibility of the searched records with.

  • collections – (optional) A list of collection IDs the searched records need to belong to. All given collections are filtered using an OR operation.

  • child_collections – (optional) Flag indicating whether the records of the children of the given collections should be included.

  • record_types – (optional) A list of record types to filter the records with before searching. All given types are filtered using an OR operation.

  • tags – (optional) A list of tag names to filter the records with before searching. All given tags are filtered using the operator specified via tag_operator.

  • tag_operator – (optional) The operator to filter the tags with. One of "or" or "and".

  • mimetypes – (optional) A list of MIME types to filter the records with before searching based on a record’s files. All given MIME types are filtered using an OR operation.

  • page – (optional) See kadi.lib.resources.utils.search_resources().

  • per_page – (optional) See kadi.lib.resources.utils.search_resources().

Returns

The search results as returned by kadi.lib.resources.utils.search_resources().

class kadi.modules.records.export.RecordPDF(record, extras=None, exclude_creator=False, exclude_links=False, exclude_collections=False, user=None)[source]

Bases: kadi.lib.pdf.PDF

Record PDF generation class.

Parameters
  • record – The record to generate a PDF from.

  • extras – (optional) The extra metadata of the record to print, which can be used to e.g. exclude certain values beforehand. Defaults to the full extra metadata of the given record.

  • exclude_creator – (optional) Flag indicating whether information about the given record’s creator should be excluded.

  • exclude_links – (optional) Either a flag or a string indicating whether to exclude all (True), outgoing ("out") or incoming ("in") links of the given record with other records.

  • exclude_collections – (optional) Flag indicating whether to exclude information about collections the given record is part of.

  • user – (optional) The user to check for various access permissions when generating the PDF. Defaults to the current user.

print_overview()[source]

Print the record overview, i.e. the basic metadata of the record.

print_extras()[source]

Print the extra metadata of the record.

print_files()[source]

Print the files of the record.

Print the links of the record with other records.

print_collections()[source]

Print the collections the record is part of.

kadi.modules.records.export.get_export_data(record, export_type, export_filter=None, user=None)[source]

Export a record in a given format.

Parameters
  • record – The record to export.

  • export_type – The export format, one of "json", "pdf" or "qr".

  • export_filter

    (optional) A dictionary specifying various filters in order to exclude certain information from the returned export data. Currently only usable in combination with the "json" and "pdf" export types.

    Example:

    {
        # Whether user information about the creator of the record or any linked
        # resource should be excluded.
        "user": False,
        # Whether to exclude information about collections the record is part
        # of.
        "collections": False,
        # Whether to exclude all (True), outgoing ("out") or incoming ("in")
        # links of the record with other records.
        "links": False,
        # A dictionary specifying a filter mask of extra metadata to exclude.
        # Depending on "extras_use_indices", each key of the dictionary
        # specifies either a key or an index (as string) that should be
        # excluded. As shown in the example below, the value of each key can
        # either be an empty dictionary, to exclude the whole extra including
        # all of its potentially nested values, or another dictionary with the
        # same possibilities as in the parent dictionary.
        "extras": {"sample_key": {}, "sample_list": {"0": {}}},
        # Whether to use indices instead of keys for the extra metadata filter
        # mask.
        "extras_use_indices": False,
    }
    

  • user – (optional) The user to check for various access permissions when generating the export data. Defaults to the current user.

Returns

The exported record data, depending on the given export type, or None if an unknown export type was given.

kadi.modules.records.extras.is_nested_type(value_type)[source]

Check if the type of an extra metadata entry is nested.

Parameters

value_type – The type of the extra metadata entry.

Returns

True if the given type is nested, False otherwise.

class kadi.modules.records.extras.ExtrasJSONB(*args, **kwargs)[source]

Bases: sqlalchemy.sql.type_api.TypeDecorator

Custom JSON type for values containing extra record metadata.

Converts float values to float explicitely, as larger float values might otherwise be interpreted as integers. This also works with dictionaries that do not contain extras directly, but as any nested dictionary value instead. See also Record.extras.

impl

alias of sqlalchemy.dialects.postgresql.json.JSONB

process_result_value(value, dialect)[source]

Convert float values of any extras recursively.

class kadi.modules.records.extras.ExtraSchema(is_template=False, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent extra record metadata.

Also does all necessary conversion and validation when deserializing. See also Record.extras.

Parameters

is_template – (optional) Flag indicating whether the schema is used inside a template, in which case different validation rules may apply.

class kadi.modules.records.extras.ExtrasField(*args, **kwargs)[source]

Bases: wtforms.fields.core.Field

Custom convenience field to process and validate extra record metadata.

Uses ExtraSchema for the validation of the metadata.

Parameters

is_template – (optional) See ExtraSchema.

process_formdata(valuelist)[source]

Process data received over the wire from a form.

This will be called during form construction with data supplied through the formdata argument.

Parameters

valuelist – A list of strings to process.

kadi.modules.records.files.aquire_file_lock(file)[source]

Aquire a lock on the given file and refresh it.

Only relevant for local files, as locks are used for updating existing local files’ data in a consistent manner.

Parameters

file – The file to aquire a lock from.

Returns

The refreshed file.

kadi.modules.records.files.update_file(file, **kwargs)[source]

Update an existing file.

Note that this function aquires a lock on the given file and issues a database commit or rollback.

Parameters
Returns

True if the file was updated successfully, False otherwise.

kadi.modules.records.files.delete_file(file, create_revision=True, revision_user=None)[source]

Delete an existing file.

This will mark the file for deletion, i.e. the files’s state will be set to "inactive". Note that this function aquires a lock on the given file and issues one or more database commits.

Parameters
  • file – The file to delete.

  • create_revision – (optional) Flag indicating whether a revision should be created for the deletion.

  • revision_user – (optional) The user that triggered the file deletion revision. Defaults to the current user.

kadi.modules.records.files.remove_files(files, delete_from_db=True)[source]

Remove multiple files from storage.

Note that this function may issue one or more database commits.

Parameters
  • files – A single File or an iterable of files.

  • delete_from_db – (optional) A flag indicating whether the file should be deleted from the database as well, instead of just doing a soft deletion (i.e. setting the file’s state to "deleted").

kadi.modules.records.files.open_file(file, mode='rb', encoding=None)[source]

Context manager that yields an open file.

Note that this context manager yields None if the file has an incompatible storage type.

Example:

with open_file(file) as file_object:
    pass
Parameters
  • file – The File to open.

  • mode – (optional) The mode to open the file with.

  • encoding – (optional) The encoding of the file if opening it in text mode.

kadi.modules.records.files.download_file(file)[source]

Send a file to a client for downloading.

Parameters

file – The File to download.

Returns

The response object or None if the given file could not be found or has an incompatible storage type.

kadi.modules.records.files.get_custom_mimetype(file, base_mimetype=None)[source]

Get a custom MIME type of a file based on its content.

Uses the "kadi_get_custom_mimetype" plugin hook for custom MIME types based on the file’s content.

Parameters
  • file – The file to get the MIME type of.

  • base_mimetype – (optional) The base MIME type of the file on which to base the custom MIME type.

Returns

The custom MIME type or None if no valid custom MIME type was found.

kadi.modules.records.files.package_files(record, creator, task=None)[source]

Package multiple local files of a record together in a ZIP archive.

If an up to date archive already exists, independent of its creator, no new archive will be created. Uses kadi.lib.archives.create_archive() to create new archives.

Note that this function issues one or more database commits.

Parameters
  • record – The record the files belong to.

  • creator – The user that will be set as the creator of the archive.

  • task – (optional) A Task object that can be provided if this function is executed in a task.

Returns

The new or existing archive as a TemporaryFile object or None if the archive could not be created successfully.

kadi.modules.records.files.get_permitted_files(user=None, term=None)[source]

Convenience function to get all record files that a user can access.

In this context having access to a file means having read permission for the record the file belongs to.

Parameters
  • user – (optional) The user to check for access permissions. Defaults to the current user.

  • term – (optional) A term to filter the files by name or record identifier.

Returns

The permitted file objects as query.

kadi.modules.records.files.download_temporary_file(temporary_file)[source]

Send a temporary file to a client as attachment for download.

Parameters

temporary_file – The TemporaryFile to download.

Returns

The response object or None if the given temporary file could not be found.

kadi.modules.records.files.remove_temporary_files(temporary_files)[source]

Remove multiple temporary files from storage.

Note that this function may issue one or more database commits.

Parameters

temporary_files – A single TemporaryFile or an iterable of temporary files.

class kadi.modules.records.forms.BaseRecordForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

Base form class for use in creating or updating records.

Parameters
  • record – (optional) A record used for prefilling the form.

  • template – (optional) A record or extras template used for prefilling the form.

class kadi.modules.records.forms.NewRecordForm(*args, **kwargs)[source]

Bases: kadi.modules.records.forms.BaseRecordForm

A form for use in creating new records.

Parameters
  • record – (optional) See BaseRecordForm.

  • template – (optional) See BaseRecordForm.

  • collection – (optional) A collection used for prefilling the linked collections.

  • user – (optional) A user that will be used for checking various permissions when prefilling the form. Defaults to the current user.

class kadi.modules.records.forms.EditRecordForm(*args, **kwargs)[source]

Bases: kadi.modules.records.forms.BaseRecordForm

A form for use in editing existing records.

Parameters

record – The record to edit, used for prefilling the form.

class kadi.modules.records.forms.LinkRecordForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in linking records with other records.

Parameters

user – (optional) A user that will be used for checking various permissions when prefilling the form. Defaults to the current user.

class kadi.modules.records.forms.LinkCollectionsForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in linking records with collections.

class kadi.modules.records.forms.AddPermissionsForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in adding user or group roles to a record.

validate(extra_validators=None)[source]

Validate the form by calling validate on each field. Returns True if validation passes.

If the form defines a validate_<fieldname> method, it is appended as an extra validator for the field’s validate.

Parameters

extra_validators – A dict mapping field names to lists of extra validator methods to run. Extra validators run after validators passed when creating the field. If the form has validate_<fieldname>, it is the last extra validator.

class kadi.modules.records.forms.ChunkMetaForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in uploading file chunks.

Parameters
  • chunk_count – The total amount of chunks that the upload this chunk is part of has. Will be used to validate the chunk’s index.

  • chunk_size – The configured chunk size.

class kadi.modules.records.forms.EditFileForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in editing file metadata.

Parameters

file – A file used for prefilling the form and checking for duplicate file names.

class kadi.modules.records.mappings.ExtraMapping(meta=None, **kwargs)[source]

Bases: elasticsearch_dsl.document.InnerDoc

Base search mapping for extra record metadata.

See Record.extras.

class kadi.modules.records.mappings.ExtraMappingString(meta=None, **kwargs)[source]

Bases: kadi.modules.records.mappings.ExtraMapping

Search mapping for extra record metadata as string.

See Record.extras.

class kadi.modules.records.mappings.ExtraMappingInteger(meta=None, **kwargs)[source]

Bases: kadi.modules.records.mappings.ExtraMapping

Search mapping for extra record metadata as integer.

Uses long values for the internal representation. See Record.extras.

class kadi.modules.records.mappings.ExtraMappingFloat(meta=None, **kwargs)[source]

Bases: kadi.modules.records.mappings.ExtraMapping

Search mapping for extra record metadata as float.

Uses double values for the internal representation. See Record.extras.

class kadi.modules.records.mappings.ExtraMappingBoolean(meta=None, **kwargs)[source]

Bases: kadi.modules.records.mappings.ExtraMapping

Search mapping for extra record metadata as boolean.

See Record.extras.

class kadi.modules.records.mappings.ExtraMappingDate(meta=None, **kwargs)[source]

Bases: kadi.modules.records.mappings.ExtraMapping

Search mapping for extra record metadata as date.

See Record.extras.

class kadi.modules.records.mappings.RecordMapping(meta=None, **kwargs)[source]

Bases: elasticsearch_dsl.document.Document, kadi.lib.search.core.MappingMixin

Search mapping for records.

See Record.

classmethod create_document(obj)[source]

Create a new document to be indexed in ElasticSearch.

Parameters
  • obj – The object to be indexed.

  • document – The mapping class instance.

Returns

The created document.

kadi.modules.records.previews.preview_file(file)[source]

Send a file to a client for previewing in a browser.

Note that this can potentially pose a security risk, so this should only be used for files that are safe for displaying. Uses the content-based MIME type of the file to set the content type of the response (see File.magic_mimetype).

Parameters

file – The File to send to the client.

Returns

The response object or None if the given file could not be found or has an incompatible storage type.

kadi.modules.records.previews.get_preview_data(file, use_fallback=True)[source]

Get the preview data of a file.

Uses the "kadi_get_preview_data" plugin hook for custom preview data.

Parameters
  • file – The File to get the preview data of.

  • use_fallback – (optional) Flag indicating whether the file should be checked for textual data as fallback by trying to detect its encoding.

Returns

The preview type and preview data as tuple, which are always guaranteed to be JSON serializable. If either the preview type or data could not be determined, None is returned.

kadi.modules.records.previews.get_preview_scripts()[source]

Get all custom scripts for rendering preview data of a file.

Uses the "kadi_get_preview_scripts" plugin hook to collect the scripts.

Returns

A flattened list of all preview scripts or an empty list if something went wrong while collecting the scripts.

class kadi.modules.records.schemas.RecordSchema(previous_record=None, linked_collection=None, check_identifier=True, is_template=False, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent records.

See Record.

Parameters
  • previous_record – (optional) A record whose identifier should be excluded when checking for duplicates while deserializing.

  • linked_collection – (optional) A collection that is linked to each record that should be serialized. Will be used to build endpoints for corresponding actions.

  • check_identifier – (optional) Flag indicating whether the identifier should be checked for duplicates.

  • is_template – (optional) Flag indicating whether the schema is used inside a template. Currently, this is only relevant for the extra metadata.

class kadi.modules.records.schemas.RecordLinkSchema(*args, _internal=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent record links.

See RecordLink.

class kadi.modules.records.schemas.FileSchema(record=None, previous_file=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent files.

See File.

Parameters
  • record – (optional) A record the file to be deserialized belongs to. Will be used to check for duplicate filenames while deserializing.

  • previous_file – (optional) A file that will be excluded when checking for duplicate filenames while deserializing.

class kadi.modules.records.schemas.ChunkSchema(*args, _internal=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent chunks.

See Chunk.

class kadi.modules.records.schemas.UploadSchema(*args, _internal=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent local file uploads.

See Upload.

kadi.modules.records.tasks.start_merge_chunks_task(upload, user=None)[source]

Merge the chunks of a local file upload in a background task.

Uses kadi.modules.records.files.merge_chunks(). The created task will be kept in the database.

Note that this function issues one or more database commits.

Parameters
  • upload – The upload that the chunks belong to.

  • user – (optional) The user that started the task. Defaults to the current user.

Returns

The new task object if the task was started successfully, None otherwise.

kadi.modules.records.tasks.start_package_files_task(record, user=None)[source]

Package all local files of a record together in a background task.

Uses kadi.modules.records.files.package_files(). The created task will be kept in the database and the user that started the task will get notified about its current status as well.

Note that this function issues one or more database commits.

Parameters
  • record – The record whose files should be packaged.

  • user – (optional) The user that started the task. Defaults to the current user.

Returns

The new task object if the task was started successfully, None otherwise.

kadi.modules.records.tasks.start_publish_record_task(record, provider, user=None, force_locale=True)[source]

Publish a record using a given provider in a background task.

The created task will be kept in the database and the user that started the task will get notified about its current status as well.

Note that this function issues one or more database commits.

Parameters
  • record – The record to publish.

  • provider – The provider to use for publishing.

  • user – (optional) The user that started the task. Defaults to the current user.

  • force_locale – (optional) Flag indicating whether the current locale as returned by kadi.lib.web.get_locale() should be used inside the task. If False, the default locale will be used instead given by LOCALE_DEFAULT as configured in the application’s configuration.

Returns

The new task object if the task was started successfully, None otherwise.

kadi.modules.records.tasks.start_purge_record_task(record)[source]

Purge an existing record in a background task.

Uses kadi.modules.records.core.purge_record().

Parameters

record – The record to purge.

kadi.modules.records.tasks.clean_files(inside_task=False)[source]

Clean all deleted and expired files.

Note that this function may issue one or more database commits.

Parameters

inside_task – (optional) A flag indicating whether the function is executed in a task. In that case, additional information will be logged.

kadi.modules.records.uploads.delete_upload(upload)[source]

Delete an existing upload.

This will mark the upload for deletion, i.e. the upload’s state will be set to "inactive".

Parameters

upload – The upload to delete.

kadi.modules.records.uploads.remove_uploads(uploads)[source]

Remove multiple uploads from local storage.

Note that this function may issue one or more database commits.

Parameters

uploads – A single Upload or an iterable of uploads.

kadi.modules.records.uploads.save_chunk(*, upload, file_object, index, size, checksum=None)[source]

Save a chunk of an upload.

Each chunk uses the UUID of the given upload (see Upload.id) combined with its index as base name in the form of "<uuid>-<index>". The complete path of the file will then be generated by prepending "STORAGE_PATH" as configured in the application’s configuration.

Note that this function issues one or more database commits.

Parameters
  • upload – The Upload the chunk belongs to.

  • file_object – A file-like object representing the actual uploaded file.

  • index – The index of the chunk.

  • size – The size of the chunk in bytes.

  • checksum – (optional) The MD5 checksum of the chunk. If given it will be used to verify the checksum after saving the chunk.

Raises
kadi.modules.records.uploads.merge_chunks(upload, task=None)[source]

Merge the chunks of an upload.

Note that this function aquires a lock on the file being replaced by the given upload, if applicable, and issues one or more database commits or rollbacks.

Parameters
  • upload – The Upload the chunks belong to.

  • task – (optional) A Task object that can be provided if this function is executed in a task. In that case, the progress of the given task will be updated.

Returns

The resulting new or updated local file or None if a file to be replaced by the upload has already been deleted.

Raises

Convenience function to get all links of a record that a user can access.

In this context having access to a record link means having read permission for each record the given record links to or is linked from.

Parameters
  • record_or_id – The record or ID of a record whose links should be obtained.

  • direction – (optional) A direction to limit the returned record links to. One of "out" for outgoing links from the given record, or "in" for incoming links to the given record.

  • user – (optional) The user to check for access permissions. Defaults to the current user.

Returns

The permitted record link objects as query.

Get all links of a record for visualizing them in a graph.

Used in conjunction with “D3.js” to visualize all returned nodes and links in a force directed graph.

Parameters
  • record – The record to start with.

  • depth – (optional) The link depth.

  • direction – (optional) A direction to limit the returned record links to. One of "out" for outgoing links from the start record, or "in" for incoming links to the start record.

  • user – (optional) The user to check for access permissions regarding the linked records. Defaults to the current user.

Returns

A dictionary containing the record links ("links") as well as all records involved in the links ("nodes").

Settings

class kadi.modules.settings.forms.EditProfileForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in editing a user’s profile information.

Parameters

user – The user to prepopulate the fields with.

class kadi.modules.settings.forms.ChangePasswordForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in changing a local user’s password.

class kadi.modules.settings.forms.NewAccessTokenForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in creating new acces tokens.

Templates

kadi.modules.templates.core.create_template(*, identifier, title, type, data, creator=None, description='', visibility='private')[source]

Create a new template.

This will also create all default permissions of the template.

Note that this function issues a database commit or rollback.

Parameters
Returns

The created template or None if the template could not be created.

kadi.modules.templates.core.update_template(template, **kwargs)[source]

Update an existing template.

Note that this function issues a database commit or rollback.

Parameters
Returns

True if the template was updated successfully, False otherwise.

kadi.modules.templates.core.delete_template(template)[source]

Delete an existing template.

This will completely delete the template from the database.

Parameters

template – The template to delete.

class kadi.modules.templates.forms.BaseTemplateForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

Base form class for use in creating or updating templates.

Parameters

template – (optional) A template used for prefilling the form.

class kadi.modules.templates.forms.BaseRecordTemplateForm(*args, **kwargs)[source]

Bases: kadi.modules.templates.forms.BaseTemplateForm

Base form class for use in creating or updating record templates.

Parameters

template – (optional) See BaseTemplateForm.

class kadi.modules.templates.forms.BaseExtrasTemplateForm(*args, **kwargs)[source]

Bases: kadi.modules.templates.forms.BaseTemplateForm

Base form class for use in creating or updating extras templates.

Parameters
  • template – (optional) See BaseTemplateForm.

  • record – (optional) A record used for prefilling the extra metadata. All values of this metadata will be removed.

class kadi.modules.templates.forms.NewTemplateFormMixin[source]

Bases: object

Mixin class for forms used in creating new templates.

class kadi.modules.templates.forms.NewRecordTemplateForm(*args, **kwargs)[source]

Bases: kadi.modules.templates.forms.NewTemplateFormMixin, kadi.modules.templates.forms.BaseRecordTemplateForm

A form for use in creating new record templates.

Parameters
  • template – (optional) See BaseRecordTemplateForm.

  • user – (optional) A user that will be used for checking various permissions when prefilling the form. Defaults to the current user.

class kadi.modules.templates.forms.NewExtrasTemplateForm(*args, **kwargs)[source]

Bases: kadi.modules.templates.forms.NewTemplateFormMixin, kadi.modules.templates.forms.BaseExtrasTemplateForm

A form for use in creating new extras templates.

Parameters
  • template – (optional) See BaseExtrasTemplateForm.

  • record – (optional) See BaseExtrasTemplateForm.

  • user – (optional) A user that will be used for checking various permissions when prefilling the form. Defaults to the current user.

class kadi.modules.templates.forms.EditTemplateFormMixin(template, *args, **kwargs)[source]

Bases: object

Mixin class for forms used in editing existing templates.

Parameters

template – The template to edit, used for prefilling the form.

class kadi.modules.templates.forms.EditRecordTemplateForm(*args, **kwargs)[source]

Bases: kadi.modules.templates.forms.EditTemplateFormMixin, kadi.modules.templates.forms.BaseRecordTemplateForm

A form for use in updating record templates.

class kadi.modules.templates.forms.EditExtrasTemplateForm(*args, **kwargs)[source]

Bases: kadi.modules.templates.forms.EditTemplateFormMixin, kadi.modules.templates.forms.BaseExtrasTemplateForm

A form for use in updating extras templates.

class kadi.modules.templates.forms.AddPermissionsForm(*args, **kwargs)[source]

Bases: kadi.lib.forms.KadiForm

A form for use in adding user or group roles to a record.

validate(extra_validators=None)[source]

Validate the form by calling validate on each field. Returns True if validation passes.

If the form defines a validate_<fieldname> method, it is appended as an extra validator for the field’s validate.

Parameters

extra_validators – A dict mapping field names to lists of extra validator methods to run. Extra validators run after validators passed when creating the field. If the form has validate_<fieldname>, it is the last extra validator.

class kadi.modules.templates.schemas.TemplateSchema(previous_template=None, template_type=None, **kwargs)[source]

Bases: kadi.lib.schemas.KadiSchema

Schema to represent generic templates.

See Template.

Parameters
  • previous_template – (optional) A template whose identifier should be excluded when checking for duplicates while deserializing.

  • template_type – (optional) The type of the template. Used when deserializing the data and it contains no type value.