Exemple #1
0
def register_service_view(request):
    """
    Registers a new service.
    """
    service_name = ar.get_value_multiformat_post_checked(
        request, "service_name")
    service_url = ar.get_value_multiformat_post_checked(request, "service_url")
    service_type = ar.get_value_multiformat_post_checked(
        request, "service_type")
    service_push = asbool(ar.get_multiformat_post(request, "service_push"))
    ax.verify_param(
        service_type,
        isIn=True,
        paramCompare=SERVICE_TYPE_DICT.keys(),
        httpError=HTTPBadRequest,
        msgOnFail=s.Services_POST_BadRequestResponseSchema.description)
    ax.verify_param(
        models.Service.by_service_name(service_name, db_session=request.db),
        isNone=True,
        httpError=HTTPConflict,
        msgOnFail=s.Services_POST_ConflictResponseSchema.description,
        content={u"service_name": str(service_name)},
        paramName=u"service_name")
    return su.create_service(service_name,
                             service_type,
                             service_url,
                             service_push,
                             db_session=request.db)
Exemple #2
0
    def _add_service_magpie_and_phoenix(svc, svc_push, db):
        db.add(svc)
        if svc_push and svc.type in SERVICES_PHOENIX_ALLOWED:
            sync_services_phoenix(db.query(models.Service))

        # sometimes, resource ID is not updated, fetch the service to obtain it
        if not svc.resource_id:
            svc = ax.evaluate_call(
                lambda: models.Service.by_service_name(service_name,
                                                       db_session=db_session),
                fallback=lambda: db_session.rollback(),
                http_error=HTTPInternalServerError,
                msg_on_fail=s.Services_POST_InternalServerErrorResponseSchema.
                description,
                content={
                    "service_name": str(service_name),
                    "resource_id": svc.resource_id
                })
            ax.verify_param(
                svc.resource_id,
                not_none=True,
                param_compare=int,
                is_type=True,
                http_error=HTTPInternalServerError,
                msg_on_fail=s.Services_POST_InternalServerErrorResponseSchema.
                description,
                content={
                    "service_name": str(service_name),
                    "resource_id": svc.resource_id
                },
                param_name="service_name")
        return svc
Exemple #3
0
def get_service_type_resources_view(request):
    """
    List details of resource types supported under a specific service type.
    """
    def _get_resource_types_info(res_type_names):
        res_type_classes = [
            rtc for rtn, rtc in models.RESOURCE_TYPE_DICT.items()
            if rtn in res_type_names
        ]
        return [
            sf.format_service_resource_type(rtc,
                                            SERVICE_TYPE_DICT[service_type])
            for rtc in res_type_classes
        ]

    service_type = ar.get_value_matchdict_checked(request, "service_type")
    ax.verify_param(
        service_type,
        paramCompare=SERVICE_TYPE_DICT.keys(),
        isIn=True,
        httpError=HTTPNotFound,
        msgOnFail=s.ServiceTypeResources_GET_NotFoundResponseSchema.description
    )
    resource_types_names = ax.evaluate_call(
        lambda: SERVICE_TYPE_DICT[service_type].resource_type_names,
        httpError=HTTPForbidden,
        content={u"service_type": str(service_type)},
        msgOnFail=s.ServiceTypeResourceTypes_GET_ForbiddenResponseSchema.
        description)
    return ax.valid_http(
        httpSuccess=HTTPOk,
        detail=s.ServiceTypeResourceTypes_GET_OkResponseSchema.description,
        content={
            u"resource_types": _get_resource_types_info(resource_types_names)
        })
Exemple #4
0
def service_factory(service, request):
    # type: (models.Service, Request) -> ServiceInterface
    """
    Retrieve the specific service class from the provided database service entry.
    """
    ax.verify_param(service,
                    param_compare=models.Service,
                    is_type=True,
                    http_error=HTTPBadRequest,
                    content={"service": repr(service)},
                    msg_on_fail="Cannot process invalid service object")
    service_type = ax.evaluate_call(
        lambda: service.type,
        http_error=HTTPInternalServerError,
        msg_on_fail="Cannot retrieve service type from object")
    ax.verify_param(
        service_type,
        is_in=True,
        param_compare=SERVICE_TYPE_DICT.keys(),
        http_error=HTTPNotImplemented,
        content={"service_type": service_type},
        msg_on_fail="Undefined service type mapping to service object")
    return ax.evaluate_call(
        lambda: SERVICE_TYPE_DICT[service_type](service, request),
        http_error=HTTPInternalServerError,
        msg_on_fail="Failed to find requested service type.")
Exemple #5
0
def assign_user_group_view(request):
    """
    Assign a user to a group.
    """
    user = ar.get_user_matchdict_checked_or_logged(request)

    group_name = ar.get_value_multiformat_body_checked(request, "group_name")
    group = ax.evaluate_call(
        lambda: GroupService.by_group_name(group_name, db_session=request.db),
        fallback=lambda: request.db.rollback(),
        http_error=HTTPForbidden,
        msg_on_fail=s.UserGroups_POST_ForbiddenResponseSchema.description)
    ax.verify_param(
        group,
        not_none=True,
        http_error=HTTPNotFound,
        msg_on_fail=s.UserGroups_POST_GroupNotFoundResponseSchema.description)
    uu.assign_user_group(user, group, db_session=request.db)
    return ax.valid_http(
        http_success=HTTPCreated,
        detail=s.UserGroups_POST_CreatedResponseSchema.description,
        content={
            "user_name": user.user_name,
            "group_name": group.group_name
        })
Exemple #6
0
def create_group_resource_permission_response(group, resource, permission, db_session):
    # type: (models.Group, ServiceOrResourceType, Permission, Session) -> HTTPException
    """
    Creates a permission on a group/resource combination if it is permitted and not conflicting.

    :returns: valid HTTP response on successful operations.
    :raises HTTPException: error HTTP response of corresponding situation.
    """
    resource_id = resource.resource_id
    check_valid_service_or_resource_permission(permission.value, resource, db_session)
    perm_content = {u"permission_name": str(permission.value),
                    u"resource": format_resource(resource, basic_info=True),
                    u"group": format_group(group, basic_info=True)}
    existing_perm = ax.evaluate_call(
        lambda: GroupResourcePermissionService.get(group.id, resource_id, permission.value, db_session=db_session),
        fallback=lambda: db_session.rollback(), httpError=HTTPForbidden,
        msgOnFail=s.GroupResourcePermissions_POST_ForbiddenGetResponseSchema.description, content=perm_content
    )
    ax.verify_param(existing_perm, isNone=True, httpError=HTTPConflict,
                    msgOnFail=s.GroupResourcePermissions_POST_ConflictResponseSchema.description, content=perm_content)
    # noinspection PyArgumentList
    new_perm = ax.evaluate_call(
        lambda: models.GroupResourcePermission(resource_id=resource_id, group_id=group.id, perm_name=permission.value),
        fallback=lambda: db_session.rollback(), httpError=HTTPForbidden, content=perm_content,
        msgOnFail=s.GroupResourcePermissions_POST_ForbiddenCreateResponseSchema.description)
    ax.evaluate_call(lambda: db_session.add(new_perm), fallback=lambda: db_session.rollback(),
                     httpError=HTTPForbidden, content=perm_content,
                     msgOnFail=s.GroupResourcePermissions_POST_ForbiddenAddResponseSchema.description)
    return ax.valid_http(httpSuccess=HTTPCreated, content=perm_content,
                         detail=s.GroupResourcePermissions_POST_CreatedResponseSchema.description)
Exemple #7
0
def get_services_runner(request):
    """
    Generates services response format from request conditions.

    Obtains the full or filtered list of services categorized by type, or listed as flat list according to request path
    and query parameters.
    """
    service_type_filter = request.matchdict.get("service_type")  # no check because None/empty is for 'all services'
    services_as_list = asbool(ar.get_query_param(request, "flatten", False))

    if not service_type_filter:
        service_types = SERVICE_TYPE_DICT.keys()
    else:
        ax.verify_param(service_type_filter, param_compare=SERVICE_TYPE_DICT.keys(), is_in=True,
                        http_error=HTTPBadRequest, msg_on_fail=s.Services_GET_BadRequestResponseSchema.description,
                        content={"service_type": str(service_type_filter)}, content_type=CONTENT_TYPE_JSON)
        service_types = [service_type_filter]

    svc_content = [] if services_as_list else {}  # type: Union[List[JSON], JSON]
    for service_type in service_types:
        services = su.get_services_by_type(service_type, db_session=request.db)
        if not services_as_list:
            svc_content[service_type] = {}
        for service in services:
            svc_fmt = sf.format_service(service, show_private_url=True)
            if services_as_list:
                svc_content.append(svc_fmt)  # pylint: disable=E1101
            else:
                svc_content[service_type][service.resource_name] = svc_fmt

    return ax.valid_http(http_success=HTTPOk, content={"services": svc_content},
                         detail=s.Services_GET_OkResponseSchema.description)
def check_valid_service_or_resource_permission(permission_name,
                                               service_or_resource,
                                               db_session):
    # type: (Union[Str, Permission], ServiceOrResourceType, Session) -> Optional[Permission]
    """
    Checks if a permission is valid to be applied to a specific `service` or a `resource` under a root service.

    :param permission_name: permission name to be validated
    :param service_or_resource: resource item corresponding to either a Service or a Resource
    :param db_session: db connection
    :return: valid Permission if allowed by the service/resource
    :raises HTTPBadRequest: if the permission is not valid for the targeted service/resource
    """
    svc_res_permissions = get_resource_permissions(service_or_resource,
                                                   db_session=db_session)
    svc_res_type = service_or_resource.resource_type
    svc_res_name = service_or_resource.resource_name
    svc_res_perm = Permission.get(permission_name)
    ax.verify_param(
        svc_res_perm,
        param_name="permission_name",
        param_compare=svc_res_permissions,
        is_in=True,
        http_error=HTTPBadRequest,
        content={
            "resource_type": str(svc_res_type),
            "resource_name": str(svc_res_name)
        },
        msg_on_fail=s.UserResourcePermissions_POST_BadRequestResponseSchema.
        description)
    return svc_res_perm
Exemple #9
0
def get_discoverable_group_by_name(group_name, db_session):
    # type: (Str, Session) -> models.Group
    """
    Obtains the requested discoverable group by name.

    .. note::
        For security reason, an existing group that is **NOT** discoverable will return NotFound instead of Forbidden.
        Otherwise we give an indication to a potentially non-admin user that *some group* of that name exists.

    :return: found group matched by name
    :raises HTTPNotFound: if the group cannot be found or if matched group name is not discoverable.
    """
    public_groups = get_discoverable_groups(db_session)
    found_group = ax.evaluate_call(
        lambda: [grp for grp in public_groups if grp.group_name == group_name],
        http_error=HTTPNotFound,
        msg_on_fail=s.RegisterGroup_NotFoundResponseSchema.description,
        content={"group_name": group_name})
    ax.verify_param(
        found_group,
        param_name="group_name",
        not_empty=True,
        http_error=HTTPNotFound,
        content_type=CONTENT_TYPE_JSON,
        msg_on_fail=s.RegisterGroup_NotFoundResponseSchema.description)
    return found_group[0]
Exemple #10
0
def check_unique_child_resource_name(resource_name, parent_id, error_message,
                                     db_session):
    # type: (Str, int, Str, Session) -> None
    """
    Verify that resource will be unique amongst other resources at the same target position.

    Verifies that the provided :paramref:`resource_name` does not already exist amongst other children resources at the
    level immediately under the parent, for the specified parent resource.

    :returns: nothing if no conflict detected
    :raises HTTPConflict: if the :paramref:`resource_name` conflict with another existing resource
    """
    tree_struct = models.RESOURCE_TREE_SERVICE.from_parent_deeper(
        parent_id, limit_depth=1, db_session=db_session)
    tree_struct_dict = models.RESOURCE_TREE_SERVICE.build_subtree_strut(
        tree_struct)
    direct_children = tree_struct_dict["children"]
    ax.verify_param(resource_name,
                    param_name="resource_name",
                    not_in=True,
                    param_compare=[
                        child_dict["node"].resource_name
                        for child_dict in direct_children.values()
                    ],
                    http_error=HTTPConflict,
                    msg_on_fail=error_message)
Exemple #11
0
def create_service_resource_view(request):
    """
    Register a new resource directly under a service or under one of its children resources.
    """
    service = ar.get_service_matchdict_checked(request)
    resource_name = ar.get_multiformat_body(request, "resource_name")
    resource_display_name = ar.get_multiformat_body(request, "resource_display_name", default=resource_name)
    resource_type = ar.get_multiformat_body(request, "resource_type")
    parent_id = ar.get_multiformat_body(request, "parent_id")  # no check because None/empty is allowed
    db_session = request.db
    if parent_id is None:
        parent_id = service.resource_id
    else:
        parent_id = ax.evaluate_call(lambda: int(parent_id),
                                     http_error=HTTPUnprocessableEntity,
                                     msg_on_fail=s.ServiceResources_POST_UnprocessableEntityResponseSchema.description)
        # validate target service is actually the root service of the provided parent resource ID
        root_service = ru.get_resource_root_service_by_id(parent_id, db_session=db_session)
        ax.verify_param(root_service, not_none=True, param_name="parent_id",
                        msg_on_fail=s.ServiceResources_POST_NotFoundResponseSchema.description,
                        http_error=HTTPNotFound)
        ax.verify_param(root_service.resource_id, is_equal=True,
                        param_compare=service.resource_id, param_name="parent_id",
                        msg_on_fail=s.ServiceResources_POST_ForbiddenResponseSchema.description,
                        http_error=HTTPForbidden)
    return ru.create_resource(resource_name, resource_display_name, resource_type,
                              parent_id=parent_id, db_session=db_session)
Exemple #12
0
def get_services_runner(request):
    service_type_filter = request.matchdict.get(
        "service_type")  # no check because None/empty is for 'all services'
    json_response = {}
    if not service_type_filter:
        service_types = SERVICE_TYPE_DICT.keys()
    else:
        ax.verify_param(
            service_type_filter,
            paramCompare=SERVICE_TYPE_DICT.keys(),
            isIn=True,
            httpError=HTTPBadRequest,
            msgOnFail=s.Services_GET_BadRequestResponseSchema.description,
            content={u"service_type": str(service_type_filter)},
            contentType=CONTENT_TYPE_JSON)
        service_types = [service_type_filter]

    for service_type in service_types:
        services = su.get_services_by_type(service_type, db_session=request.db)
        json_response[service_type] = {}
        for service in services:
            json_response[service_type][
                service.resource_name] = sf.format_service(
                    service, show_private_url=True)

    return ax.valid_http(httpSuccess=HTTPOk,
                         content={u"services": json_response},
                         detail=s.Services_GET_OkResponseSchema.description)
Exemple #13
0
def sign_in(request):
    """
    Signs in a user session.
    """
    provider_name = ar.get_value_multiformat_body_checked(request, "provider_name", default=MAGPIE_DEFAULT_PROVIDER)
    provider_name = provider_name.lower()
    # magpie supports login from both username or corresponding email
    # therefore validate pattern combination manually after fetch otherwise email format fails patter match
    user_name = ar.get_value_multiformat_body_checked(request, "user_name", pattern=None)  # bad request if missing
    pattern = ax.EMAIL_REGEX if "@" in user_name else ax.PARAM_REGEX
    ax.verify_param(user_name, matches=True, param_compare=pattern, param_name="user_name",
                    http_error=HTTPUnprocessableEntity, msg_on_fail=s.UnprocessableEntityResponseSchema.description)
    verify_provider(provider_name)

    if provider_name in MAGPIE_INTERNAL_PROVIDERS.keys():
        # password can be None for external login, validate only here as needed
        password = ar.get_value_multiformat_body_checked(request, "password", pattern=None)
        # check manually to avoid inserting value in result body
        # obtain the raw path, without any '/magpie' prefix (if any), let 'application_url' handle it
        signin_internal_path = request.route_url("ziggurat.routes.sign_in", _app_url="")
        signin_internal_data = {"user_name": user_name, "password": password, "provider_name": provider_name}
        signin_sub_request = Request.blank(signin_internal_path, base_url=request.application_url,
                                           headers={"Accept": CONTENT_TYPE_JSON}, POST=signin_internal_data)
        signin_response = request.invoke_subrequest(signin_sub_request, use_tweens=True)
        if signin_response.status_code == HTTPOk.code:
            return convert_response(signin_response)
        login_failure(request, s.Signin_POST_UnauthorizedResponseSchema.description)

    elif provider_name in MAGPIE_EXTERNAL_PROVIDERS.keys():
        return ax.evaluate_call(lambda: process_sign_in_external(request, user_name, provider_name),
                                http_error=HTTPInternalServerError,
                                content={"user_name": user_name, "provider_name": provider_name},
                                msg_on_fail=s.Signin_POST_External_InternalServerErrorResponseSchema.description)
Exemple #14
0
def get_user_resources_permissions_dict(user, request, resource_types=None, resource_ids=None,
                                        inherit_groups_permissions=True, resolve_groups_permissions=False):
    # type: (models.User, Request, Optional[List[Str]], Optional[List[int]], bool, bool) -> 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.
    """
    ax.verify_param(user, not_none=True, http_error=HTTPNotFound,
                    msg_on_fail=s.UserResourcePermissions_GET_NotFoundResponseSchema.description)

    # full list of user/groups permissions, filter afterwards according to flags
    res_perm_tuple_list = UserService.resources_with_possible_perms(
        user, resource_ids=resource_ids, resource_types=resource_types, db_session=request.db)
    if not inherit_groups_permissions and not resolve_groups_permissions:
        res_perm_tuple_list = filter_user_permission(res_perm_tuple_list, user)
    return regroup_permissions_by_resource(res_perm_tuple_list, resolve=resolve_groups_permissions)
Exemple #15
0
def delete_user_resource_permission_response(user, resource, permission, db_session, similar=True):
    # type: (models.User, ServiceOrResourceType, PermissionSet, Session, bool) -> 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.
    """
    ru.check_valid_service_or_resource_permission(permission.name, resource, db_session)
    res_id = resource.resource_id
    if similar:
        found_perm = get_similar_user_resource_permission(user, resource, permission, db_session)
    else:
        found_perm = permission
    del_perm = UserResourcePermissionService.get(user.id, res_id, str(found_perm), db_session)
    permission.type = PermissionType.APPLIED
    err_content = {"resource_id": res_id, "user_id": user.id,
                   "permission_name": str(permission), "permission": permission.json()}
    ax.verify_param(del_perm, not_none=True, http_error=HTTPNotFound, content=err_content,
                    msg_on_fail=s.UserResourcePermissionName_DELETE_NotFoundResponseSchema.description)
    ax.evaluate_call(lambda: db_session.delete(del_perm), fallback=lambda: db_session.rollback(),
                     http_error=HTTPNotFound, content=err_content,
                     msg_on_fail=s.UserResourcePermissionName_DELETE_NotFoundResponseSchema.description)
    return ax.valid_http(http_success=HTTPOk, detail=s.UserResourcePermissionName_DELETE_OkResponseSchema.description)
Exemple #16
0
def check_valid_service_resource(parent_resource, resource_type, db_session):
    """
    Checks if a new Resource can be contained under a parent Resource given the requested type and the corresponding
    Service under which the parent Resource is already assigned.

    :param parent_resource: Resource under which the new resource of `resource_type` must be placed
    :param resource_type: desired resource type
    :param db_session:
    :return: root Service if all checks were successful
    """
    parent_type = parent_resource.resource_type_name
    ax.verify_param(models.RESOURCE_TYPE_DICT[parent_type].child_resource_allowed, isEqual=True,
                    paramCompare=True, httpError=HTTPBadRequest,
                    msgOnFail="Child resource not allowed for specified parent resource type '{}'".format(parent_type))
    root_service = get_resource_root_service(parent_resource, db_session=db_session)
    ax.verify_param(root_service, notNone=True, httpError=HTTPInternalServerError,
                    msgOnFail="Failed retrieving 'root_service' from db")
    ax.verify_param(root_service.resource_type, isEqual=True, httpError=HTTPInternalServerError,
                    paramName=u"resource_type", paramCompare=models.Service.resource_type_name,
                    msgOnFail="Invalid 'root_service' retrieved from db is not a service")
    ax.verify_param(SERVICE_TYPE_DICT[root_service.type].child_resource_allowed, isEqual=True,
                    paramCompare=True, httpError=HTTPBadRequest,
                    msgOnFail="Child resource not allowed for specified service type '{}'".format(root_service.type))
    ax.verify_param(resource_type, isIn=True, httpError=HTTPBadRequest,
                    paramName=u"resource_type", paramCompare=SERVICE_TYPE_DICT[root_service.type].resource_type_names,
                    msgOnFail="Invalid 'resource_type' specified for service type '{}'".format(root_service.type))
    return root_service
Exemple #17
0
def create_user_resource_permission_response(user, resource, permission,
                                             db_session):
    # type: (models.User, ServiceOrResourceType, Permission, Session) -> HTTPException
    """
    Creates a permission on a user/resource combination if it is permitted and not conflicting.

    :returns: valid HTTP response on successful operation.
    """
    check_valid_service_or_resource_permission(permission.value, resource,
                                               db_session)
    resource_id = resource.resource_id
    existing_perm = UserResourcePermissionService.by_resource_user_and_perm(
        user_id=user.id,
        resource_id=resource_id,
        perm_name=permission.value,
        db_session=db_session)
    ax.verify_param(
        existing_perm,
        isNone=True,
        httpError=HTTPConflict,
        content={
            u"resource_id": resource_id,
            u"user_id": user.id,
            u"permission_name": permission.value
        },
        msgOnFail=s.UserResourcePermissions_POST_ConflictResponseSchema.
        description)

    # noinspection PyArgumentList
    new_perm = models.UserResourcePermission(resource_id=resource_id,
                                             user_id=user.id,
                                             perm_name=permission.value)
    usr_res_data = {
        u"resource_id": resource_id,
        u"user_id": user.id,
        u"permission_name": permission.value
    }
    ax.verify_param(
        new_perm,
        notNone=True,
        httpError=HTTPForbidden,
        content={
            u"resource_id": resource_id,
            u"user_id": user.id
        },
        msgOnFail=s.UserResourcePermissions_POST_ForbiddenResponseSchema.
        description)
    ax.evaluate_call(
        lambda: db_session.add(new_perm),
        fallback=lambda: db_session.rollback(),
        httpError=HTTPForbidden,
        content=usr_res_data,
        msgOnFail=s.UserResourcePermissions_POST_ForbiddenResponseSchema.
        description)
    return ax.valid_http(
        httpSuccess=HTTPCreated,
        content=usr_res_data,
        detail=s.UserResourcePermissions_POST_CreatedResponseSchema.description
    )
Exemple #18
0
def get_value_multiformat_post_checked(request, key, default=None):
    val = get_multiformat_any(request, key, default=default)
    verify_param(val,
                 notNone=True,
                 notEmpty=True,
                 httpError=HTTPUnprocessableEntity,
                 paramName=key,
                 msgOnFail=s.UnprocessableEntityResponseSchema.description)
    return val
Exemple #19
0
def get_value_matchdict_checked(request, key):
    val = request.matchdict.get(key)
    verify_param(val,
                 notNone=True,
                 notEmpty=True,
                 httpError=HTTPUnprocessableEntity,
                 paramName=key,
                 msgOnFail=s.UnprocessableEntityResponseSchema.description)
    return val
Exemple #20
0
def get_services_by_type(service_type, db_session):
    ax.verify_param(service_type,
                    notNone=True,
                    notEmpty=True,
                    httpError=HTTPBadRequest,
                    msgOnFail="Invalid 'service_type' value '" +
                    str(service_type) + "' specified")
    services = db_session.query(
        models.Service).filter(models.Service.type == service_type)
    return sorted(services, key=lambda svc: svc.resource_name)
Exemple #21
0
def get_user_groups_checked(user, db_session):
    # type: (models.User, Session) -> List[Str]
    """
    Obtains the validated list of group names from a pre-validated user.
    """
    ax.verify_param(user, not_none=True, http_error=HTTPNotFound,
                    msg_on_fail=s.Groups_CheckInfo_NotFoundResponseSchema.description)
    group_names = ax.evaluate_call(lambda: [group.group_name for group in user.groups],  # noqa
                                   fallback=lambda: db_session.rollback(), http_error=HTTPForbidden,
                                   msg_on_fail=s.Groups_CheckInfo_ForbiddenResponseSchema.description)
    return sorted(group_names)
Exemple #22
0
 def _get_group(grp_name):
     # type: (Str) -> models.Group
     ax.verify_param(grp_name, not_none=True, not_empty=True, matches=True,
                     param_compare=ax.PARAM_REGEX, param_name="group_name",
                     http_error=HTTPBadRequest, msg_on_fail=s.UserGroup_Check_BadRequestResponseSchema.description)
     grp = ax.evaluate_call(lambda: GroupService.by_group_name(grp_name, db_session=db_session),
                            http_error=HTTPForbidden,
                            msg_on_fail=s.UserGroup_GET_ForbiddenResponseSchema.description)
     ax.verify_param(grp, not_none=True, http_error=HTTPNotFound, with_param=False,
                     msg_on_fail=s.UserGroup_Check_NotFoundResponseSchema.description)
     return grp
Exemple #23
0
    def check_request(self, request):
        if request.path.startswith(self.twitcher_protected_path):
            service_name = parse_service_name(request.path,
                                              self.twitcher_protected_path)
            service = evaluate_call(
                lambda: Service.by_service_name(service_name,
                                                db_session=request.db),
                http_error=HTTPForbidden,
                msg_on_fail="Service query by name refused by db.")
            verify_param(service,
                         not_none=True,
                         http_error=HTTPNotFound,
                         msg_on_fail="Service name not found.")

            # return a specific type of service, ex: ServiceWPS with all the acl (loaded according to the service_type)
            service_specific = service_factory(service, request)
            # should contain all the acl, this the only thing important
            # parse request (GET/POST) to get the permission requested for that service
            permission_requested = service_specific.permission_requested()
            # convert permission enum to str for comparison
            permission_requested = Permission.get(
                permission_requested).value if permission_requested else None

            if permission_requested:
                LOGGER.info("'%s' request '%s' permission on '%s'",
                            request.user, permission_requested, request.path)
                self.update_request_cookies(request)
                authn_policy = request.registry.queryUtility(
                    IAuthenticationPolicy)
                authz_policy = request.registry.queryUtility(
                    IAuthorizationPolicy)
                principals = authn_policy.effective_principals(request)
                has_permission = authz_policy.permits(service_specific,
                                                      principals,
                                                      permission_requested)

                if LOGGER.isEnabledFor(logging.DEBUG):
                    LOGGER.debug("%s - AUTHN policy configurations:",
                                 type(self).__name__)
                    base_attr = [
                        attr for attr in dir(authn_policy.cookie)
                        if not attr.startswith("_")
                    ]
                    for attr_name in base_attr:
                        LOGGER.debug("  %s: %s", attr_name,
                                     getattr(authn_policy.cookie, attr_name))

                if has_permission:
                    return  # allowed

            raise OWSAccessForbidden(
                "Not authorized to access this resource. "
                "User does not meet required permissions.")
Exemple #24
0
def get_service_type_resource_types_view(request):
    """
    List all resource types supported under a specific service type.
    """
    service_type = ar.get_value_matchdict_checked(request, "service_type")
    ax.verify_param(service_type, param_compare=SERVICE_TYPE_DICT.keys(), is_in=True, http_error=HTTPNotFound,
                    msg_on_fail=s.ServiceTypeResourceTypes_GET_NotFoundResponseSchema.description)
    resource_types = ax.evaluate_call(lambda: SERVICE_TYPE_DICT[service_type].resource_type_names,
                                      http_error=HTTPForbidden, content={"service_type": str(service_type)},
                                      msg_on_fail=s.ServiceTypeResourceTypes_GET_ForbiddenResponseSchema.description)
    return ax.valid_http(http_success=HTTPOk, detail=s.ServiceTypeResourceTypes_GET_OkResponseSchema.description,
                         content={"resource_types": resource_types})
Exemple #25
0
def handle_temporary_url(request):
    """
    Handles the operation according to the provided temporary URL token.
    """
    str_token = ar.get_value_matchdict_checked(request, key="token", pattern=ax.UUID_REGEX)
    str_token = str_token.split(":")[-1]  # remove optional prefix if any (e.g.: 'urn:uuid:')
    db_session = request.db
    tmp_token = models.TemporaryToken.by_token(str_token, db_session=db_session)
    ax.verify_param(tmp_token, not_none=True,
                    http_error=HTTPNotFound, content={"token": str(str_token)},
                    msg_on_fail=s.TemporaryURL_GET_NotFoundResponseSchema.description)
    ru.handle_temporary_token(tmp_token, db_session=db_session)
    return ax.valid_http(http_success=HTTPOk, detail=s.TemporaryURL_GET_OkResponseSchema.description)
Exemple #26
0
 def _get_group(grp_name):
     # type: (Str) -> models.Group
     grp = ax.evaluate_call(
         lambda: GroupService.by_group_name(grp_name, db_session=db_session
                                            ),
         httpError=HTTPForbidden,
         msgOnFail=s.UserGroup_GET_ForbiddenResponseSchema.description)
     ax.verify_param(
         grp,
         notNone=True,
         httpError=HTTPBadRequest,
         msgOnFail=s.UserGroup_Check_BadRequestResponseSchema.description)
     return grp
Exemple #27
0
def get_user_groups_checked(request, user):
    # type: (Request, models.User) -> List[Str]
    ax.verify_param(
        user,
        notNone=True,
        httpError=HTTPNotFound,
        msgOnFail=s.Groups_CheckInfo_NotFoundResponseSchema.description)
    group_names = ax.evaluate_call(
        lambda: [group.group_name for group in user.groups],
        fallback=lambda: request.db.rollback(),
        httpError=HTTPForbidden,
        msgOnFail=s.Groups_CheckInfo_ForbiddenResponseSchema.description)
    return sorted(group_names)
Exemple #28
0
def handle_temporary_token(tmp_token, db_session):
    # type: (models.TemporaryToken, Session) -> None
    """
    Handles the operation according to the provided temporary token.
    """
    if tmp_token.expired():
        str_token = str(tmp_token.token)
        db_session.delete(tmp_token)
        ax.raise_http(HTTPGone,
                      content={"token": str_token},
                      detail=s.TemporaryURL_GET_GoneResponseSchema.description)
    ax.verify_param(tmp_token.operation,
                    is_in=True,
                    param_compare=TokenOperation.values(),
                    param_name="token",
                    http_error=HTTPInternalServerError,
                    msg_on_fail="Invalid token.")
    if tmp_token.operation == TokenOperation.GROUP_ACCEPT_TERMS:
        ax.verify_param(tmp_token.group,
                        not_none=True,
                        http_error=HTTPInternalServerError,
                        msg_on_fail="Invalid token.")
        ax.verify_param(tmp_token.user,
                        not_none=True,
                        http_error=HTTPInternalServerError,
                        msg_on_fail="Invalid token.")
        uu.assign_user_group(tmp_token.user, tmp_token.group, db_session)
    if tmp_token.operation == TokenOperation.USER_PASSWORD_RESET:
        ax.verify_param(tmp_token.user,
                        not_none=True,
                        http_error=HTTPInternalServerError,
                        msg_on_fail="Invalid token.")
        # TODO: reset procedure
        ax.raise_http(HTTPNotImplemented, detail="Not Implemented")
    db_session.delete(tmp_token)
Exemple #29
0
def get_services_by_type(service_type, db_session):
    # type: (Str, Session) -> Iterable[models.Service]
    """
    Obtains all services that correspond to requested service-type.
    """
    ax.verify_param(service_type,
                    not_none=True,
                    not_empty=True,
                    http_error=HTTPBadRequest,
                    msg_on_fail="Invalid 'service_type' value '" +
                    str(service_type) + "' specified")
    services = db_session.query(
        models.Service).filter(models.Service.type == service_type)
    return sorted(services, key=lambda svc: svc.resource_name)
Exemple #30
0
def get_group_matchdict_checked(request, group_name_key="group_name"):
    group_name = get_value_matchdict_checked(request, group_name_key)
    group = evaluate_call(
        lambda: zig.GroupService.by_group_name(group_name,
                                               db_session=request.db),
        fallback=lambda: request.db.rollback(),
        httpError=HTTPForbidden,
        msgOnFail=s.Group_MatchDictCheck_ForbiddenResponseSchema.description)
    verify_param(
        group,
        notNone=True,
        httpError=HTTPNotFound,
        msgOnFail=s.Group_MatchDictCheck_NotFoundResponseSchema.description)
    return group