예제 #1
0
def get_group_service_resources_response(group, service, db_session):
    # type: (models.Group, models.Service, Session) -> HTTPException
    """
    Get validated response of all found service resources which the group has permissions on.

    :returns: valid HTTP response on successful operations.
    :raises HTTPException: error HTTP response of corresponding situation.
    """
    svc_perms = get_group_service_permissions(group=group,
                                              service=service,
                                              db_session=db_session)
    res_perms = get_group_service_resources_permissions_dict(
        group=group, service=service, db_session=db_session)
    svc_res_json = format_service_resources(
        service=service,
        db_session=db_session,
        service_perms=svc_perms,
        resources_perms_dict=res_perms,
        show_all_children=False,
        show_private_url=False,
    )
    return ax.valid_http(
        http_success=HTTPOk,
        detail=s.GroupServiceResources_GET_OkResponseSchema.description,
        content={"service": svc_res_json})
예제 #2
0
 def build_json_user_resource_tree(usr):
     json_res = {}
     perm_type = PermissionType.INHERITED if inherit_groups_perms else PermissionType.DIRECT
     services = ResourceService.all(models.Service, db_session=db)
     # add service-types so they are ordered and listed if no service of that type was defined
     for svc_type in sorted(SERVICE_TYPE_DICT):
         json_res[svc_type] = {}
     for svc in services:
         svc_perms = uu.get_user_service_permissions(
             user=usr,
             service=svc,
             request=request,
             inherit_groups_permissions=inherit_groups_perms,
             resolve_groups_permissions=resolve_groups_perms)
         res_perms_dict = uu.get_user_service_resources_permissions_dict(
             user=usr,
             service=svc,
             request=request,
             inherit_groups_permissions=inherit_groups_perms,
             resolve_groups_permissions=resolve_groups_perms)
         # always allow admin to view full resource tree, unless explicitly requested to be filtered
         # otherwise (non-admin), only add details if there is at least one resource permission (any level)
         if (is_admin and not filtered_perms) or (svc_perms
                                                  or res_perms_dict):
             json_res[svc.type][
                 svc.resource_name] = format_service_resources(
                     svc,
                     db_session=db,
                     service_perms=svc_perms,
                     resources_perms_dict=res_perms_dict,
                     permission_type=perm_type,
                     show_all_children=False,
                     show_private_url=False,
                 )
     return json_res
예제 #3
0
def get_group_resources(group, db_session):
    # type: (models.Group, Session) -> JSON
    """
    Get formatted JSON body describing all service resources the ``group`` as permissions on.
    """
    json_response = {}
    for svc in list(ResourceService.all(models.Service,
                                        db_session=db_session)):
        svc_perms = get_group_service_permissions(group=group,
                                                  service=svc,
                                                  db_session=db_session)
        svc_name = str(svc.resource_name)
        svc_type = str(svc.type)
        if svc_type not in json_response:
            json_response[svc_type] = {}
        res_perm_dict = get_group_service_resources_permissions_dict(
            group=group, service=svc, db_session=db_session)
        json_response[svc_type][svc_name] = format_service_resources(
            svc,
            db_session=db_session,
            service_perms=svc_perms,
            resources_perms_dict=res_perm_dict,
            permission_type=PermissionType.APPLIED,
            show_all_children=False,
            show_private_url=False,
        )
    return json_response
예제 #4
0
def get_user_service_resources_view(request):
    """
    List all resources under a service a user has permission on.
    """
    inherit_groups_perms = asbool(ar.get_query_param(request, "inherit"))
    user = ar.get_user_matchdict_checked_or_logged(request)
    service = ar.get_service_matchdict_checked(request)
    service_perms = uu.get_user_service_permissions(
        user,
        service,
        request=request,
        inherit_groups_permissions=inherit_groups_perms)
    resources_perms_dict = uu.get_user_service_resources_permissions_dict(
        user,
        service,
        request=request,
        inherit_groups_permissions=inherit_groups_perms)
    user_svc_res_json = format_service_resources(
        service=service,
        db_session=request.db,
        service_perms=service_perms,
        resources_perms_dict=resources_perms_dict,
        show_all_children=False,
        show_private_url=False,
    )
    return ax.valid_http(
        httpSuccess=HTTPOk,
        detail=s.UserServiceResources_GET_OkResponseSchema.description,
        content={u"service": user_svc_res_json})
예제 #5
0
 def build_json_user_resource_tree(usr):
     json_res = {}
     services = ResourceService.all(models.Service, db_session=db)
     for svc in services:
         svc_perms = uu.get_user_service_permissions(
             user=usr,
             service=svc,
             request=request,
             inherit_groups_permissions=inherit_groups_perms)
         if svc.type not in json_res:
             json_res[svc.type] = {}
         res_perms_dict = uu.get_user_service_resources_permissions_dict(
             user=usr,
             service=svc,
             request=request,
             inherit_groups_permissions=inherit_groups_perms)
         json_res[svc.type][svc.resource_name] = format_service_resources(
             svc,
             db_session=db,
             service_perms=svc_perms,
             resources_perms_dict=res_perms_dict,
             show_all_children=False,
             show_private_url=False,
         )
     return json_res
예제 #6
0
def get_service_resources_view(request):
    """
    List all resources registered under a service.
    """
    service = ar.get_service_matchdict_checked(request)
    svc_res_json = sf.format_service_resources(service, db_session=request.db,
                                               show_all_children=True, show_private_url=True)
    return ax.valid_http(http_success=HTTPOk, content={svc_res_json["service_name"]: svc_res_json},
                         detail=s.ServiceResources_GET_OkResponseSchema.description)
예제 #7
0
def get_resources_view(request):
    """
    List all registered resources.
    """
    res_json = {}
    for svc_type in SERVICE_TYPE_DICT.keys():
        services = get_services_by_type(svc_type, db_session=request.db)
        res_json[svc_type] = {}
        for svc in services:
            res_json[svc_type][svc.resource_name] = format_service_resources(
                svc, request.db, show_all_children=True, show_private_url=False)
    res_json = {u"resources": res_json}
    return ax.valid_http(httpSuccess=HTTPOk, detail=s.Resources_GET_OkResponseSchema.description, content=res_json)
예제 #8
0
def parse_resource_path(
        permission_config_entry,  # type: ConfigItem
        entry_index,  # type: int
        service_info,  # type: ConfigItem
        cookies_or_session=None,  # type: CookiesOrSessionType
        magpie_url=None,  # type: Optional[Str]
):  # type: (...) -> Tuple[Optional[int], bool]
    """
    Parses the `resource` field of a permission config entry and retrieves the final resource id. Creates missing
    resources as necessary if they can be automatically resolved.

    If `cookies` are provided, uses requests to a running `Magpie` instance (with `magpie_url`) to apply permission.
    If `session` to db is provided, uses direct db connection instead to apply permission.

    :returns: tuple of found id (if any, `None` otherwise), and success status of the parsing operation (error)
    """
    if not magpie_url and use_request(cookies_or_session):
        raise ValueError(
            "cannot use cookies without corresponding request URL")

    resource = None
    resource_path = permission_config_entry.get("resource", "")
    if resource_path.startswith("/"):
        resource_path = resource_path[1:]
    if resource_path.endswith("/"):
        resource_path = resource_path[:-1]
    if resource_path:
        try:
            svc_name = service_info["service_name"]
            svc_type = service_info["service_type"]
            if use_request(cookies_or_session):
                res_path = get_magpie_url() + ServiceResourcesAPI.path.format(
                    service_name=svc_name)
                res_resp = requests.get(res_path, cookies=cookies_or_session)
                res_dict = get_json(res_resp)[svc_name]["resources"]
            else:
                from magpie.api.management.service.service_formats import format_service_resources
                svc = models.Service.by_service_name(
                    svc_name, db_session=cookies_or_session)
                res_dict = format_service_resources(
                    svc, show_all_children=True, db_session=cookies_or_session)
            parent = res_dict["resource_id"]
            child_resources = res_dict["resources"]
            for res in resource_path.split("/"):
                # search in existing children resources
                if len(child_resources):
                    # noinspection PyTypeChecker
                    res_id = list(
                        filter(
                            lambda r: res in
                            [r, child_resources[r]["resource_name"]],
                            child_resources))
                    if res_id:
                        res_info = child_resources[
                            res_id[0]]  # type: Dict[Str, JSON]
                        child_resources = res_info[
                            "children"]  # update next sub-resource iteration
                        parent = res_info["resource_id"]
                        continue
                # missing resource, attempt creation
                svc_res_types = SERVICE_TYPE_DICT[svc_type].resource_type_names
                type_count = len(svc_res_types)
                if type_count != 1:
                    warn_permission(
                        "Cannot automatically generate resources",
                        entry_index,
                        detail=
                        "Service [{}] of type [{}] allows {} sub-resource types"
                        .format(svc_name, svc_type, type_count))
                    raise Exception(
                        "Missing resource to apply permission.")  # fail fast
                res_type = svc_res_types[0]
                if use_request(cookies_or_session):
                    body = {
                        "resource_name": res,
                        "resource_type": res_type,
                        "parent_id": parent
                    }
                    # noinspection PyUnboundLocalVariable
                    resp = requests.post(res_path,
                                         json=body,
                                         cookies=cookies_or_session)
                else:
                    from magpie.api.management.resource.resource_utils import create_resource
                    resp = create_resource(res,
                                           res,
                                           res_type,
                                           parent,
                                           db_session=cookies_or_session)
                if resp.status_code != 201:
                    resp.raise_for_status()
                child_resources = {}
                parent = get_json(resp)["resource"]["resource_id"]
            resource = parent
            if not resource:
                raise Exception(
                    "Could not extract child resource from resource path.")
        except Exception as ex:
            if isinstance(ex, HTTPException):
                detail = "{} ({}), {}".format(
                    type(ex).__name__, ex.status_code, str(ex))
            else:
                detail = repr(ex)
            warn_permission("Failed resources parsing.",
                            entry_index,
                            detail=detail)
            return None, False
    return resource, True