magpie.api.management.user.user_utils ===================================== .. py:module:: magpie.api.management.user.user_utils Attributes ---------- .. autoapisummary:: magpie.api.management.user.user_utils.LOGGER magpie.api.management.user.user_utils.USERNAME_REGEX Functions --------- .. autoapisummary:: magpie.api.management.user.user_utils.create_user magpie.api.management.user.user_utils.update_user magpie.api.management.user.user_utils.create_user_resource_permission_response magpie.api.management.user.user_utils.assign_user_group magpie.api.management.user.user_utils.send_group_terms_email magpie.api.management.user.user_utils.create_pending_or_assign_user_group magpie.api.management.user.user_utils.handle_user_group_terms_confirmation magpie.api.management.user.user_utils.delete_user_group magpie.api.management.user.user_utils.delete_user_resource_permission_response magpie.api.management.user.user_utils.get_similar_user_resource_permission magpie.api.management.user.user_utils.get_user_resource_permissions magpie.api.management.user.user_utils.get_user_resource_permissions_response magpie.api.management.user.user_utils.get_user_services magpie.api.management.user.user_utils.get_user_service_permissions magpie.api.management.user.user_utils.filter_user_permission magpie.api.management.user.user_utils.resolve_user_group_permissions magpie.api.management.user.user_utils.regroup_permissions_by_resource magpie.api.management.user.user_utils.get_user_resources_permissions_dict magpie.api.management.user.user_utils.get_user_service_resources_permissions_dict magpie.api.management.user.user_utils.check_user_info magpie.api.management.user.user_utils.check_user_editable magpie.api.management.user.user_utils.get_user_groups_checked Module Contents --------------- .. py:data:: LOGGER .. py:data:: USERNAME_REGEX .. py:function:: create_user(user_name: magpie.typedefs.Str, password: Optional[magpie.typedefs.Str], email: magpie.typedefs.Str, group_name: Optional[magpie.typedefs.Str], db_session: sqlalchemy.orm.session.Session, **extra_fields) -> pyramid.httpexceptions.HTTPException Creates a :term:`User` if it is permitted and not conflicting with existing ones. Password must be set to ``None`` if using an external identity or skip its encrypted value generation. Created :term:`User` will immediately be assigned membership to the group matching :paramref:`group_name` (can be :py:data:`MAGPIE_ANONYMOUS_GROUP` for minimal access). If no group is provided, this anonymous group will be applied by default, creating a user effectively without any permissions other than ones set directly for him and inherited from :ref:`perm_public_access`. Furthermore, the :term:`User` *always* gets associated with :py:data:`MAGPIE_ANONYMOUS_GROUP` (if not already explicitly or implicitly requested with :paramref:`group_name`) to allow access to resources with public permission. This means that when :paramref:`group_name` is provided with another name than :py:data:`MAGPIE_ANONYMOUS_GROUP`, the :term:`User` will have two memberships initially. Argument :paramref:`group_name` **MUST** be an existing group if provided. .. note:: In order to properly handle subscribed :term:`Webhook` that could request to change the user status to an error following a failing external operation, the created user is immediately committed. This way, following requests will have access to the instance from the database. Because of this requirement, any operation that desire an handle to the created :class:`User` instance should retrieve it again from the database session. :param user_name: Unique name of the user to validate and employ for creation. :param password: Raw password of the user to validate and employ for creation. If Skipped if ``None``. Otherwise, apply hash encryption on the value. :param email: User email to be validated and employed for creation. :param group_name: Group name to associate the user with at creation time. :param db_session: database connection. :param extra_fields: Additional fields that should be set for the user. Must be known properties of the instance. :returns: valid HTTP response on successful operation, or the :class:`User` when requested. .. py:function:: update_user(user: magpie.models.User, request: pyramid.request.Request, new_user_name: Optional[magpie.typedefs.Str] = None, new_password: Optional[magpie.typedefs.Str] = None, new_email: Optional[magpie.typedefs.Str] = None, new_status: Optional[magpie.models.UserStatuses] = None) -> None Applies updates of user details with specified values after validation. :param user: targeted user to update . :param request: request that produced this update operation. :param new_user_name: new name to apply (if provided). :param new_password: new password to apply (if provided). :param new_email: new email to apply (if provided). :param new_status: new status to apply (if provided). :return: None if update was successful. .. py:function:: create_user_resource_permission_response(user: magpie.models.User, resource: magpie.typedefs.ServiceOrResourceType, permission: magpie.permissions.PermissionSet, db_session: sqlalchemy.orm.session.Session, overwrite: bool = False) -> pyramid.httpexceptions.HTTPException Creates a permission on a user/resource combination if it is permitted, and optionally not conflicting. :param user: user for which to create/update the permission. :param resource: service or resource for which to create the permission. :param permission: permission with modifiers to be applied. :param db_session: database connection. :param overwrite: If the corresponding `(user, resource, permission[name])` exists, there is a conflict. Conflict is considered only by permission-name regardless of other modifiers. If permissions match exactly (including modifiers), conflict is raised regardless of overwrite value. If overwrite is ``False``, the conflict will be raised and not be applied. If overwrite is ``True``, the permission modifiers will be replaced by the new ones, or created if missing. :returns: valid HTTP response on successful operation. .. py:function:: assign_user_group(user: magpie.models.User, group: magpie.models.Group, db_session: sqlalchemy.orm.session.Session) -> None Creates a user-group relationship (user membership to a group). :returns: nothing - user-group is created. :raises HTTPError: corresponding error matching problem encountered. .. py:function:: send_group_terms_email(user: magpie.models.User, group: magpie.models.Group, db_session: sqlalchemy.orm.session.Session) -> pyramid.httpexceptions.HTTPSuccessful Sends an email for terms and conditions confirmation. Terms and conditions email are sent in the case of a request for the creation of a user-group relationship where the group requires a terms and conditions confirmation. :returns: valid HTTP response on successful operations. :raises HTTPError: corresponding error matching problem encountered. .. py:function:: create_pending_or_assign_user_group(user: magpie.models.User, group: magpie.models.Group, db_session: sqlalchemy.orm.session.Session) -> pyramid.httpexceptions.HTTPSuccessful Associates the pending user or existing user to the group. Creates either a new user-group relationship (user membership to a group) or a pending terms and conditions confirmation. If the group requires a T&C confirmation, sends an email for T&C confirmation, else, the user is assigned directly to the group. :returns: valid HTTP response on successful operations. :raises HTTPError: corresponding error matching problem encountered. .. py:function:: handle_user_group_terms_confirmation(tmp_token: magpie.models.TemporaryToken, request: pyramid.request.Request) -> pyramid.response.Response Handles the confirmation of a user to accept the terms and conditions of a group. Generates the appropriate response that will be displayed to the user. .. py:function:: delete_user_group(user: magpie.models.User, group: magpie.models.Group, db_session: sqlalchemy.orm.session.Session) -> None Deletes a user-group relationship (user membership to a group). :returns: nothing - user-group is deleted. :raises HTTPNotFound: if the combination cannot be found. .. py:function:: delete_user_resource_permission_response(user: magpie.models.User, resource: magpie.typedefs.ServiceOrResourceType, permission: magpie.permissions.PermissionSet, db_session: sqlalchemy.orm.session.Session, similar: bool = True) -> pyramid.httpexceptions.HTTPException Get validated response on deleted user resource permission. :param user: user for which to delete the permission. :param resource: service or resource for which to delete the permission. :param permission: permission with modifiers to be deleted. :param db_session: database connection. :param similar: Allow matching provided permission against any similar database permission. Otherwise, must match exactly. :returns: valid HTTP response on successful operations. :raises HTTPException: error HTTP response of corresponding situation. .. py:function:: get_similar_user_resource_permission(user: magpie.models.User, resource: magpie.typedefs.ServiceOrResourceType, permission: magpie.permissions.PermissionSet, db_session: sqlalchemy.orm.session.Session) -> Optional[magpie.permissions.PermissionSet] Obtains the user service/resource permission that corresponds to the provided one. Lookup considers only *similar* applied permission such that other permission modifiers don't affect comparison. .. py:function:: get_user_resource_permissions(user: magpie.models.User, resource: magpie.models.Resource, db_session: sqlalchemy.orm.session.Session, inherit: bool = False, resolve: bool = False) -> Tuple[List[magpie.permissions.PermissionSet], magpie.permissions.PermissionType, bool] Retrieves user resource permissions applied directly, with inherited group permissions, or resolve between them. :param user: user for which to retrieve permissions for the resource, and optionally its groups as well. :param resource: resource for which permissions to retrieve are applied on. :param db_session: database session :param inherit: obtain permissions with user's group inheritance (duplicate permissions possible across user/groups) :param resolve: resolve permissions across user/groups to obtain a single highest priority permission on resource. .. py:function:: get_user_resource_permissions_response(user: magpie.models.User, resource: magpie.typedefs.ServiceOrResourceType, request: pyramid.request.Request, inherit_groups_permissions: bool = True, resolve_groups_permissions: bool = False, effective_permissions: bool = False) -> pyramid.httpexceptions.HTTPException Retrieves user resource permissions with or without inherited group permissions. Alternatively retrieves the effective user resource permissions, where group permissions are implied as `True`. .. warning:: Does not consider direct :term:`Resource` ownership. .. seealso:: - :func:`get_direct_inherited_resolved_resource_permissions` - :func:`get_user_service_permissions` :returns: valid HTTP response on successful operations. :raises HTTPException: error HTTP response of corresponding situation. .. py:function:: get_user_services(user: magpie.models.User, request: pyramid.request.Request, cascade_resources: bool = False, format_as_list: bool = False, inherit_groups_permissions: bool = False, resolve_groups_permissions: bool = False, service_types: Optional[List[magpie.typedefs.Str]] = None) -> magpie.typedefs.UserServicesType Returns services by type with corresponding services by name containing sub-dict information. .. seealso:: :func:`regroup_permissions_by_resource` :param user: user for which to find services :param request: request with database session connection :param cascade_resources: If ``False``, return only services which the :term:`User` has :ref:`Immediate Permissions ` on specialized top-level resources corresponding to a :term:`Service`. Otherwise, return every service that has at least one sub-resource with permissions (children at any-level). In both cases, the *permissions* looked for consider either only :term:`Direct Permissions` or any :term:`Inherited Permission` according to the value of :paramref:`inherit_groups_permissions`. :param inherit_groups_permissions: If ``False``, return only user-specific service/sub-resources :term:`Direct Permissions`. Otherwise, resolve :term:`Inherited Permissions ` using all groups the user is member of. :param resolve_groups_permissions: Whether to combine :term:`Direct Permissions ` and :term:`Inherited Permissions ` for respective resources or not. :param format_as_list: Returns as list of service dict information (not grouped by type and by name) :param service_types: Filter list of service types for which to return details. All service types are used if omitted. :return: Only services which the user as :term:`Direct Permissions` or considering all tree hierarchy, and for each case, either considering only user permissions or every :term:`Inherited Permission`, according to provided options. :rtype: Mapping of services by type to corresponding services by name containing each sub-mapping of their information, unless :paramref:`format_as_list` is ``True``, in which case a flat list of service information is returned. .. py:function:: get_user_service_permissions(user: magpie.models.User, service: magpie.models.Service, request: pyramid.request.Request, inherit_groups_permissions: bool = True, resolve_groups_permissions: bool = False) -> List[magpie.permissions.PermissionSet] Retrieve the permissions the user has directly on a service or inherited permissions by its group memberships. .. warning:: - Does not consider :term:`Effective Permissions ` ownership. - Considers direct :term:`Service` ownership, but not implemented everywhere (not operational). .. seealso:: - :func:`get_user_resource_permissions` - :func:`get_user_resource_permissions_response` .. py:function:: filter_user_permission(resource_permission_list: List[ziggurat_foundations.permissions.PermissionTuple], user: magpie.models.User) -> Iterable[ziggurat_foundations.permissions.PermissionTuple] Retrieves only user :term:`Direct Permissions` amongst a list of user/group resource/service permissions. .. py:function:: resolve_user_group_permissions(resource_permission_list: List[magpie.typedefs.ResolvablePermissionType]) -> Iterable[magpie.permissions.PermissionSet] Reduces overlapping user :term:`Inherited Permission` for corresponding resources/services amongst the given list. User :term:`Direct Permissions` have the top-most priority and are therefore selected first if permissions are found for corresponding resource. In such case, only one entry is possible (it is invalid to have more than one combination of ``(User, Resource, Permission)``, including modifiers, as per validation during their creation). Otherwise, for corresponding :term:`Inherited Permissions `, resolve the prioritized :term:`Permission` across every group. Similarly to users, :func:`magpie.groups.group_utils.get_similar_group_resource_permission` validate that only one combination of ``(Group, Resource, Permission)`` can exist including permission modifiers. Only, cross-group memberships for a given resource must then be computed. Priority of combined *group-only* permissions follows 3 conditions: 1. Permissions inherited from special group :py:data:`MAGPIE_ANONYMOUS_GROUP` have lower priority than any other more explicit group membership, regardless of permission modifiers applied on it. 2. Permissions of same group priority with :attr:`Access.DENY` are prioritized over :attr:`Access.ALLOW`. 3. Permissions of same group priority with :attr:`Scope.RECURSIVE` are prioritized over :attr:`Access.MATCH` as they affect a larger range of resources when :term:`Effective Permissions ` are eventually requested. .. note:: Resource tree inherited resolution is not considered here (no recursive :term:`Effective Permission` computed). Only same-level scope of every given resource is processed independently. The intended behaviour here is therefore to help illustrate in responses *how deep* is a given permission going to have an impact onto lower-level resources, making :attr:`Scope.RECURSIVE` more important than specific instance :attr:`Scope.MATCH`. .. seealso:: - Sorting methods of :class:`magpie.permissions.PermissionSet` that orders the permissions with desired result. - :func:`magpie.groups.group_utils.get_similar_group_resource_permission` - :func:`magpie.users.user_utils.get_similar_user_resource_permission` .. py:function:: regroup_permissions_by_resource(resource_permissions: Iterable[magpie.typedefs.ResolvablePermissionType], resolve: bool = False) -> magpie.typedefs.ResourcePermissionMap Regroups multiple uncategorized permissions into a dictionary of corresponding resource IDs. While regrouping the various permissions (both :term:`Direct Permissions ` and any amount of groups :term:`Inherited Permissions `) under their respective resource by ID, optionally resolve overlapping or conflicting permissions by name such that only one permission persists for that resource and name. .. seealso:: :func:`resolve_user_group_permissions` :param resource_permissions: List of resource permissions to process. Can include both user :term:`Direct Permissions ` and its groups :term:`Inherited Permissions `. :param resolve: When ``False``, only mapping by resource ID is accomplished. Full listing of permissions is returned. Otherwise, resolves the corresponding resource permissions (by same ID) considering various priority rules to obtain unique permission names per resource. :return: resolved permission .. py:function:: get_user_resources_permissions_dict(user: magpie.models.User, request: pyramid.request.Request, resource_types: Optional[List[magpie.typedefs.Str]] = None, resource_ids: Optional[List[int]] = None, inherit_groups_permissions: bool = True, resolve_groups_permissions: bool = False) -> magpie.typedefs.ResourcePermissionMap Creates a dictionary of resources ID with corresponding permissions of the user. .. seealso:: :func:`regroup_permissions_by_resource` :param user: user for which to find resources permissions :param request: request with database session connection :param resource_types: filter the search query with only the specified resource types :param resource_ids: filter the search query to only the specified resource IDs :param inherit_groups_permissions: Whether to include group inherited permissions from user memberships or not. If ``False``, return only user-specific resource permissions. Otherwise, resolve inherited permissions using all groups the user is member of. :param resolve_groups_permissions: whether to combine corresponding user/group permissions into one or not. :return: Only resources which the user has permissions on, or including all :term:`Inherited Permissions `, according to :paramref:`inherit_groups_permissions` argument. .. py:function:: get_user_service_resources_permissions_dict(user: magpie.models.User, service: magpie.models.Service, request: pyramid.request.Request, inherit_groups_permissions: bool = True, resolve_groups_permissions: bool = False) -> magpie.typedefs.ResourcePermissionMap Retrieves all permissions the user has for every :term:`Resource` nested under the :term:`Service`. The retrieved permissions can either include only :term:`Direct Permissions` or a combination of user and group :term:`Inherited Permissions ` accordingly to provided options. .. seealso:: :func:`get_user_resources_permissions_dict` :func:`regroup_permissions_by_resource` :returns: dictionary of resource IDs with corresponding permissions. .. py:function:: check_user_info(user_name: magpie.typedefs.Str = None, email: magpie.typedefs.Str = None, password: magpie.typedefs.Str = None, group_name: magpie.typedefs.Str = None, check_name: bool = True, check_email: bool = True, check_password: bool = True, check_group: bool = True) -> None Validates provided user information to ensure they are adequate for user creation. Using ``check_`` prefixed arguments, individual field checks can be disabled (check all by default). :raises HTTPException: appropriate error for the invalid field value or format that was checked as applicable. :returns: nothing if all enabled checks are successful. .. py:function:: check_user_editable(user: magpie.models.User, container: magpie.typedefs.AnySettingsContainer) -> None Verify if the specified user is allowed to receive modifications (to it directly or any resource referring to it). :param user: User to validate. :param container: Any container to retrieve application settings. :raises HTTPForbidden: When user is not allowed to be edited. :return: Nothing if allowed edition. .. py:function:: get_user_groups_checked(user: magpie.models.User, db_session: sqlalchemy.orm.session.Session) -> List[magpie.typedefs.Str] Obtains the validated list of group names from a pre-validated user.