Ejemplo n.º 1
0
    def create(self, request, workspace_id):

        workspace = get_object_or_404(Workspace, pk=workspace_id)
        data = parse_json_request(request)

        if 'name' not in data and 'title' not in data:
            return build_error_response(
                request, 422,
                _('Malformed tab JSON: expecting tab name or title.'))

        if not (request.user.is_superuser
                or workspace.creator == request.user):
            return build_error_response(
                request, 403,
                _('You are not allowed to create new tabs for this workspace'))

        tab_title = data.get('title')
        tab_name = data.get('name')
        try:
            tab = createTab(tab_title, workspace, name=tab_name)
        except IntegrityError:
            msg = _(
                'A tab with the given name already exists for the workspace')
            return build_error_response(request, 409, msg)

        return HttpResponse(json.dumps(get_tab_data(tab, user=request.user)),
                            status=201,
                            content_type='application/json; charset=UTF-8')
Ejemplo n.º 2
0
    def update(self, request, workspace_id, tab_id):

        iwidgets = parse_json_request(request)

        tab = get_object_or_404(Tab, workspace__pk=workspace_id, pk=tab_id)
        if not request.user.is_superuser and tab.workspace.creator != request.user:
            msg = _(
                'You have not enough permission for updating the iwidgets of this workspace'
            )
            return build_error_response(request, 403, msg)

        for iwidget in iwidgets:
            try:
                UpdateIWidget(iwidget, request.user, tab, updatecache=False)
            except IWidget.DoesNotExist:
                return build_error_response(
                    request, 422,
                    _("Widget {id} does not exist").format(
                        id=iwidget.get('id')))
            except TypeError as e:
                return build_error_response(request, 400, e)
            except ValueError as e:
                return build_error_response(request, 422, e)

        if len(iwidgets) > 0:
            # Invalidate workspace cache
            tab.workspace.save()

        return HttpResponse(status=204)
Ejemplo n.º 3
0
    def read(self, request, workspace_id, tab_id, iwidget_id):
        workspace = get_object_or_404(Workspace, pk=workspace_id)

        if not workspace.is_available_for(request.user):
            msg = _("You don't have permission to access this workspace")
            return build_error_response(request, 403, msg)

        iwidget = get_object_or_404(IWidget, pk=iwidget_id)
        if iwidget.tab_id != int(tab_id):
            raise Http404

        if iwidget.widget is None:
            return HttpResponse(json.dumps({}),
                                content_type='application/json; charset=UTF-8')

        try:
            iwidget_info = iwidget.widget.resource.get_processed_info(
                translate=True, process_variables=True)
        except:
            return build_error_response(
                request, 403, _('Missing widget variables cannot be updated'))

        cache_manager = VariableValueCacheManager(workspace, request.user)
        prefs = iwidget_info['variables']['preferences']

        data = {}
        data = {
            var: cache_manager.get_variable_data("iwidget", iwidget_id, var)
            for var in prefs
        }

        return HttpResponse(json.dumps(data, sort_keys=True),
                            content_type='application/json; charset=UTF-8')
Ejemplo n.º 4
0
    def create(self, request, workspace_id):

        try:
            ts = json.loads(request.body)
        except ValueError as e:
            msg = _("malformed json data: %s") % unicode(e)
            return build_error_response(request, 400, msg)

        workspace = Workspace.objects.get(pk=workspace_id)
        if not (request.user.is_superuser or workspace.users.filter(pk=request.user.pk).exists()):
            return build_error_response(request, 403, _('You are not allowed to update this workspace'))

        if 'active' in ts:

            active = ts.get('active', False)
            if isinstance(active, string_types):
                active = ts['active'].lower() == 'true'

            if active:
                # Only one active workspace
                setActiveWorkspace(request.user, workspace)
            else:
                currentUserWorkspace = UserWorkspace.objects.get(workspace=workspace, user=request.user)
                currentUserWorkspace.active = False
                currentUserWorkspace.save()

        if 'name' in ts:
            workspace.name = ts['name']

        workspace.save()

        return HttpResponse(status=204)
Ejemplo n.º 5
0
    def create(self, request, workspace_id):

        workspace = get_object_or_404(Workspace, pk=workspace_id)
        try:
            data = json.loads(request.body)
        except ValueError as e:
            msg = _("malformed json data: %s") % unicode(e)
            return build_error_response(request, 400, msg)

        if 'name' not in data:
            return build_error_response(request, 400, _('Malformed tab JSON: expecting tab name.'))

        tab_name = data['name']
        if not (request.user.is_superuser or workspace.creator == request.user):
            return build_error_response(request, 403, _('You are not allowed to create new tabs for this workspace'))

        try:
            tab = createTab(tab_name, workspace)
        except IntegrityError:
            msg = _('A tab with the given name already exists for the workspace')
            return build_error_response(request, 409, msg)

        # Returning created Ids
        ids = {'id': tab.id, 'name': tab.name}

        return HttpResponse(json.dumps(ids), status=201, content_type='application/json; charset=UTF-8')
Ejemplo n.º 6
0
    def create(self, request, workspace_id, tab_id):

        iwidget = parse_json_request(request)
        initial_variable_values = iwidget.get('variable_values', None)

        # iWidget creation
        tab = get_object_or_404(Tab.objects.select_related('workspace'),
                                workspace__pk=workspace_id,
                                pk=tab_id)
        if not request.user.is_superuser and tab.workspace.creator != request.user:
            msg = _(
                'You have not enough permission for adding iwidgets to the workspace'
            )
            return build_error_response(request, 403, msg)

        try:
            iwidget = SaveIWidget(iwidget, request.user, tab,
                                  initial_variable_values)
            iwidget_data = get_iwidget_data(iwidget,
                                            tab.workspace,
                                            user=request.user)

            return HttpResponse(json.dumps(iwidget_data),
                                content_type='application/json; charset=UTF-8',
                                status=201)
        except (CatalogueResource.DoesNotExist, Widget.DoesNotExist) as e:
            msg = _('refered widget %(widget_uri)s does not exist.') % {
                'widget_uri': iwidget['widget']
            }
            return build_error_response(request, 422, msg)
        except TypeError as e:
            return build_error_response(request, 400, e)
        except ValueError as e:
            return build_error_response(request, 422, e)
Ejemplo n.º 7
0
    def update(self, request, workspace_id):

        workspace = get_object_or_404(Workspace, id=workspace_id)
        if not request.user.is_superuser and workspace.creator != request.user:
            return build_error_response(request, 403, _('You are not allowed to update this workspace'))

        wiring_status = parse_json_request(request)

        old_wiring_status = workspace.wiringStatus
        old_read_only_connections = []
        for connection in old_wiring_status['connections']:
            if connection.get('readonly', False):
                old_read_only_connections.append(connection)

        read_only_connections = []
        for connection in wiring_status['connections']:
            if connection.get('readonly', False):
                read_only_connections.append(connection)

        if len(old_read_only_connections) > len(read_only_connections):
            return build_error_response(request, 403, _('You are not allowed to remove read only connections'))

        for connection in old_read_only_connections:
            if connection not in read_only_connections:
                return build_error_response(request, 403, _('You are not allowed to remove read only connections'))

        workspace.wiringStatus = wiring_status
        workspace.save()

        return HttpResponse(status=204)
Ejemplo n.º 8
0
    def delete(self, request, workspace_id, tab_id):

        # Get tab, if it does not exist, an http 404 error is returned
        tab = get_object_or_404(Tab.objects.select_related('workspace'), workspace__pk=workspace_id, pk=tab_id)
        if not request.user.is_superuser and not tab.workspace.users.filter(id=request.user.id).exists():
            return build_error_response(request, 403, _('You are not allowed to remove this tab'))

        tabs = Tab.objects.filter(workspace__pk=workspace_id).order_by('position')[::1]
        if len(tabs) == 1:
            msg = _("Tab cannot be deleted as workspaces need at least one tab")
            return build_error_response(request, 403, msg)

        if tab.iwidget_set.filter(readOnly=True).exists():
            msg = _("Tab cannot be deleted as it contains widgets that cannot be deleted")
            return build_error_response(request, 403, msg)

        # decrease the position of the following tabs
        for t in range(tab.position + 1, len(tabs)):
            tabs[t].position = tabs[t].position - 1
            tabs[t].save()

        # Remove the tab
        tabs.remove(tab)
        deleteTab(tab, request.user)

        if tab.visible:
            # set a new visible tab (first tab by default)
            activeTab = tabs[0]
            setVisibleTab(request.user, workspace_id, activeTab)

        return HttpResponse(status=204)
Ejemplo n.º 9
0
    def create(self, request, workspace_id):

        ts = parse_json_request(request)
        fields = []

        workspace = get_object_or_404(Workspace, pk=workspace_id)
        if not (request.user.is_superuser or workspace.users.filter(pk=request.user.pk).exists()):
            return build_error_response(request, 403, _('You are not allowed to update this workspace'))

        if 'name' in ts:
            workspace.name = ts['name']
            fields.append('name')

        if 'title' in ts:
            workspace.title = ts['title']
            fields.append('title')

        if 'description' in ts:
            workspace.description = ts['description']
            fields.append('description')

        if 'longdescription' in ts:
            workspace.longdescription = ts['longdescription']
            fields.append('longdescription')

        try:
            workspace.save(update_fields=fields)
        except IntegrityError:
            msg = _('A workspace with the given name already exists')
            return build_error_response(request, 409, msg)

        return HttpResponse(status=204)
Ejemplo n.º 10
0
    def create(self, request, workspace_id, tab_id, iwidget_id):

        workspace = get_object_or_404(Workspace, pk=workspace_id)
        if not request.user.is_superuser and workspace.creator != request.user:
            msg = _(
                'You have not enough permission for updating the persistent variables of this widget'
            )
            return build_error_response(request, 403, msg)

        iwidget = get_object_or_404(IWidget, pk=iwidget_id)
        if iwidget.tab_id != int(tab_id):
            raise Http404

        iwidget_info = iwidget.widget.resource.get_processed_info(
            translate=True, process_variables=True)

        new_values = parse_json_request(request)

        for var_name in new_values:
            if var_name not in iwidget_info['variables']['properties']:
                msg = _('Invalid persistent variable: "%s"') % var_name
                return build_error_response(request, 422, msg)

            iwidget.set_variable_value(var_name, new_values[var_name])

        iwidget.save()
        return HttpResponse(status=204)
Ejemplo n.º 11
0
    def create(self, request, workspace_id, tab_id, iwidget_id):

        iwidget = parse_json_request(request)

        tab = get_object_or_404(Tab.objects.select_related('workspace'),
                                workspace__pk=workspace_id,
                                pk=tab_id)
        if not request.user.is_superuser and tab.workspace.creator != request.user:
            msg = _('You have not enough permission for updating the iwidget')
            return build_error_response(request, 403, msg)

        iwidget['id'] = iwidget_id
        try:
            UpdateIWidget(iwidget, request.user, tab)
        except Tab.DoesNotExist:
            return build_error_response(
                request, 422,
                _("Target tab {id} does not exist").format(id=iwidget['tab']))
        except (CatalogueResource.DoesNotExist, Widget.DoesNotExist) as e:
            msg = _('refered widget %(widget_uri)s does not exist.') % {
                'widget_uri': iwidget['widget']
            }
            return build_error_response(request, 422, msg)
        except TypeError as e:
            return build_error_response(request, 400, e)
        except ValueError as e:
            return build_error_response(request, 422, e)
        except IWidget.DoesNotExist:
            raise Http404

        return HttpResponse(status=204)
Ejemplo n.º 12
0
def _parse_ac_request(request):

    fileURL = None
    file_contents = None
    content_type = get_content_type(request)[0]

    data = parse_json_request(request)

    if 'url' not in data:
        return build_error_response(request, 400, _('Missing widget URL'))

    fileURL = data.get('url')
    id_4CaaSt = data.get('4CaaStID')

    if id_4CaaSt is None:
        return build_error_response(request, 400, _('Missing 4CaaStID'))

    if not isinstance(id_4CaaSt, string_types) or id_4CaaSt.strip() == '':
        return build_error_response(request, 400, _('Invalid 4CaaStID'))

    try:
        downloaded_file = download_http_content(fileURL)
    except:
        return build_error_response(
            request, 409,
            _('Mashable application component could not be downloaded'))

    downloaded_file = StringIO(downloaded_file)
    file_contents = WgtFile(downloaded_file)

    # Create a custom version of the resource
    template = TemplateParser(file_contents.get_template())
    template_info = template.get_resource_info()
    template_info['name'] += '@' + id_4CaaSt

    for pref_name, pref_value in six.iteritems(data.get('preferences', {})):
        for widget_pref_index, widget_pref in enumerate(
                template_info['preferences']):
            if widget_pref['name'] == pref_name:
                template_info['preferences'][widget_pref_index][
                    'readonly'] = True
                template_info['preferences'][widget_pref_index][
                    'value'] = pref_value
                break

    # Write a new Wgt file
    new_file = StringIO()
    zin = zipfile.ZipFile(downloaded_file, 'r')
    zout = zipfile.ZipFile(new_file, 'w')
    zout.writestr('config.xml', write_rdf_description(template_info))
    for item in zin.infolist():
        if item.filename == 'config.xml':
            continue
        zout.writestr(item, zin.read(item.filename))
    zin.close()
    zout.close()

    file_contents = WgtFile(new_file)

    return id_4CaaSt, file_contents, fileURL
Ejemplo n.º 13
0
    def create(self, request):

        received_data = parse_json_request(request)

        if 'options' not in received_data:
            return build_error_response(request, 400, _("Missing marketplace options"))

        validate_url_param(request, 'options.url', received_data['options']['url'])

        if 'user' not in received_data['options'] or received_data['options']['user'] == request.user.username:
            user_entry = request.user
        elif received_data['options'].get('user', None) is not None:
            user_entry = User.objects.get(username=received_data['options']['user'])
        else:
            user_entry = None

        if (user_entry is None or user_entry != request.user) and not request.user.is_superuser:
            return build_error_response(request, 403, _("You don't have permissions for adding public marketplaces"))

        if 'user' in received_data['options']:
            del received_data['options']['user']

        try:
            Market.objects.create(user=user_entry, name=received_data['name'], options=received_data['options'])
        except IntegrityError:
            return build_error_response(request, 409, 'Market name already in use')

        return HttpResponse(status=201)
Ejemplo n.º 14
0
    def read(self, request, workspace_id, tab_id, iwidget_id):
        workspace = get_object_or_404(Workspace, pk=workspace_id)

        if not workspace.is_available_for(request.user):
            msg = _("You don't have permission to access this workspace")
            return build_error_response(request, 403, msg)

        iwidget = get_object_or_404(IWidget, pk=iwidget_id)
        if iwidget.tab_id != int(tab_id):
            raise Http404

        if iwidget.widget is None:
            return HttpResponse(json.dumps({}), content_type='application/json; charset=UTF-8')

        try:
            iwidget_info = iwidget.widget.resource.get_processed_info(translate=True, process_variables=True)
        except:
            return build_error_response(request, 403, _('Missing widget variables cannot be updated'))

        cache_manager = VariableValueCacheManager(workspace, request.user)
        prefs = iwidget_info['variables']['preferences']

        data = {}
        data = {var: cache_manager.get_variable_data("iwidget", iwidget_id, var) for var in prefs}

        return HttpResponse(json.dumps(data, sort_keys=True), content_type='application/json; charset=UTF-8')
Ejemplo n.º 15
0
def remove_tenant(request):

    try:
        data = json.loads(request.body)
    except ValueError as e:
        msg = _("malformed json data: %s") % unicode(e)
        return build_error_response(request, 400, msg)

    id_4CaaSt = data.get('4CaaStID')

    if id_4CaaSt is None:
        return build_error_response(request, 400, _('Missing 4CaaStID'))

    if not isinstance(id_4CaaSt, string_types) or id_4CaaSt.strip() == '':
        return build_error_response(request, 400, _('Invalid 4CaaStID'))

    username = parse_username(id_4CaaSt)

    user = get_object_or_404(User, username=username)
    try:
        if user.tenantprofile_4CaaSt.id_4CaaSt != id_4CaaSt:
            raise Http404
    except TenantProfile.DoesNotExist:
        raise Http404

    user.delete()

    return HttpResponse(status=204)
Ejemplo n.º 16
0
    def update(self, request, workspace_id, tab_id):

        tab = get_object_or_404(Tab.objects.select_related('workspace'), workspace__pk=workspace_id, pk=tab_id)
        if tab.workspace.creator != request.user:
            return build_error_response(request, 403, _('You are not allowed to update this workspace'))

        user_workspace = UserWorkspace.objects.get(user__id=request.user.id, workspace__id=workspace_id)
        if user_workspace.manager != '':
            return build_error_response(request, 403, _('You are not allowed to update this workspace'))

        data = parse_json_request(request)

        if 'visible' in data:
            visible = data['visible']
            if isinstance(visible, string_types):
                visible = visible.strip().lower()
                if visible not in ('true', 'false'):
                    return build_error_response(request, 422, _('Invalid visible value'))
                visible = visible == 'true'
            elif not isinstance(visible, bool):
                return build_error_response(request, 422, _('Invalid visible value'))

            if visible:
                #Only one visible tab
                setVisibleTab(request.user, workspace_id, tab)
            else:
                tab.visible = False

        if 'name' in data:
            tab.name = data['name']

        tab.save()

        return HttpResponse(status=204)
Ejemplo n.º 17
0
    def process(self, request):

        if not request.user.is_superuser:
            return build_error_response(
                request, 403,
                _("You don't have permission to switch current session user"))

        user_info = parse_json_request(request)

        if "username" not in user_info:
            return build_error_response(request, 422,
                                        "Missing target user info")

        user_id = get_object_or_404(User, username=user_info['username']).id
        target_user = None
        for backend in auth.get_backends():
            try:
                target_user = backend.get_user(user_id)
            except:
                continue
            if target_user is None:
                continue
            # Annotate the user object with the path of the backend.
            target_user.backend = "%s.%s" % (backend.__module__,
                                             backend.__class__.__name__)
            break

        if target_user is None:
            raise Http404

        auth.login(request, target_user)

        return HttpResponse(status=204)
Ejemplo n.º 18
0
    def create(self, request, fromWGT=False):

        try:
            if 'file' in request.FILES:

                request_file = request.FILES['file']
                resource = add_widget_from_wgt(request_file, request.user)

            elif 'template_uri' in request.POST:

                template_uri = request.POST['template_uri']
                downloaded_file = download_http_content(template_uri, user=request.user)
                if request.POST.get('packaged', 'false').lower() == 'true':
                    resource = add_widget_from_wgt(StringIO(downloaded_file), request.user)
                else:
                    resource = add_resource_from_template(template_uri, downloaded_file, request.user)

            else:

                return build_error_response(request, 400, _("Missing parameter: template_uri or file"))

        except TemplateParseException as e:

            return build_error_response(request, 400, unicode(e.msg))

        except IntegrityError:

            return build_error_response(request, 409, _('Resource already exists'))

        resource.users.add(request.user)
        return HttpResponse(resource.json_description, content_type='application/json; charset=UTF-8')
Ejemplo n.º 19
0
    def create(self, request, workspace_id, tab_id, iwidget_id):

        iwidget = parse_json_request(request)

        tab = get_object_or_404(Tab.objects.select_related('workspace'), workspace__pk=workspace_id, pk=tab_id)
        if not request.user.is_superuser and tab.workspace.creator != request.user:
            msg = _('You have not enough permission for updating the iwidget')
            return build_error_response(request, 403, msg)

        iwidget['id'] = iwidget_id
        try:
            UpdateIWidget(iwidget, request.user, tab)
        except Tab.DoesNotExist:
            return build_error_response(request, 422, _("Target tab {id} does not exist").format(id=iwidget['tab']))
        except (CatalogueResource.DoesNotExist, Widget.DoesNotExist) as e:
            msg = _('refered widget %(widget_uri)s does not exist.') % {'widget_uri': iwidget['widget']}
            return build_error_response(request, 422, msg)
        except TypeError as e:
            return build_error_response(request, 400, e)
        except ValueError as e:
            return build_error_response(request, 422, e)
        except IWidget.DoesNotExist:
            raise Http404

        return HttpResponse(status=204)
Ejemplo n.º 20
0
    def create(self, request, workspace_id):

        workspace = get_object_or_404(Workspace, pk=workspace_id)
        data = parse_json_request(request)

        if 'name' not in data:
            return build_error_response(
                request, 400, _('Malformed tab JSON: expecting tab name.'))

        tab_name = data['name']
        if not (request.user.is_superuser
                or workspace.creator == request.user):
            return build_error_response(
                request, 403,
                _('You are not allowed to create new tabs for this workspace'))

        try:
            tab = createTab(tab_name, workspace)
        except IntegrityError:
            msg = _(
                'A tab with the given name already exists for the workspace')
            return build_error_response(request, 409, msg)

        # Returning created Ids
        ids = {'id': tab.id, 'name': tab.name}

        return HttpResponse(json.dumps(ids),
                            status=201,
                            content_type='application/json; charset=UTF-8')
Ejemplo n.º 21
0
def proxy_request(request, protocol, domain, path):

    # TODO improve proxy security

    try:
        if request.get_host() != urlparse.urlparse(request.META["HTTP_REFERER"])[1]:
            raise Exception()

        if settings.SESSION_COOKIE_NAME not in request.COOKIES:
            raise Exception()
    except:
        return build_error_response(request, 403, _(u"Invalid request"))

    url = protocol + '://' + domain + path
    if len(request.GET) > 0:
        url += '?' + request.GET.urlencode()

    try:
        response = WIRECLOUD_PROXY.do_request(request, url, request.method.upper())
    except Exception as e:
        msg = _("Error processing proxy request: %s") % unicode(e)
        return build_error_response(request, 500, msg)

    # Process cookies
    for key in response.cookies:
        cookie = response.cookies[key]

        if cookie['path'] == '':
            cookie['path'] = reverse('wirecloud|proxy', kwargs={'protocol': protocol, 'domain': domain, 'path': path})
        else:
            cookie['path'] = reverse('wirecloud|proxy', kwargs={'protocol': protocol, 'domain': domain, 'path': cookie['path']})

    return response
Ejemplo n.º 22
0
    def read(self, request):

        querytext = request.GET.get('q', '')
        indexname = request.GET.get('namespace', '').strip()

        if indexname == '':
            message = _(
                'Missing namespace GET parameter providing a search namespace')
            return build_error_response(request, 400, message)

        if not is_available(indexname):
            message = _('Invalid search namespace: %s' % indexname)
            return build_error_response(request, 422, message)

        try:
            pagenum = int(request.GET.get('pagenum', '1'))
        except ValueError:
            message = _('Invalid pagenum value: %s' % request.GET['pagenum'])
            return build_error_response(request, 422, message)

        try:
            maxresults = int(request.GET.get('maxresults', '30'))
        except ValueError:
            message = _('Invalid maxresults value: %s' %
                        request.GET['maxresults'])
            return build_error_response(request, 422, message)

        result = get_search_engine(indexname).search(querytext,
                                                     request,
                                                     pagenum=pagenum,
                                                     maxresults=maxresults)

        return HttpResponse(json.dumps(result, sort_keys=True),
                            status=200,
                            content_type='application/json; charset=utf-8')
Ejemplo n.º 23
0
    def create(self, request):

        try:
            if 'file' in request.FILES:

                request_file = request.FILES['file']
                resource = add_packaged_resource(request_file, request.user)

            elif 'template_uri' in request.POST:

                template_uri = request.POST['template_uri']
                downloaded_file = download_http_content(template_uri, user=request.user)
                resource = add_packaged_resource(BytesIO(downloaded_file), request.user)

            else:

                return build_error_response(request, 400, _("Missing parameter: template_uri or file"))

        except TemplateParseException as e:

            return build_error_response(request, 400, e.msg)

        except IntegrityError:

            return build_error_response(request, 409, _('Resource already exists'))

        resource.users.add(request.user)
        return HttpResponse(resource.json_description, content_type='application/json; charset=UTF-8')
Ejemplo n.º 24
0
    def read(self, request):

        querytext = request.GET.get('q', '')

        filters = {
            'pagenum': int(request.GET.get('pagenum', '1')),
            'maxresults': int(request.GET.get('maxresults', '30')),
            'orderby': request.GET.get('orderby', '-creation_date'),
            'scope': request.GET.get('scope', None),
            'staff': request.GET.get('staff', 'false').lower() == 'true',
        }

        if not filters['orderby'].replace('-', '', 1) in ['creation_date', 'name', 'vendor']:
            return build_error_response(request, 400, _('Orderby value not supported: %s') % filters['orderby'])

        if filters['scope']:
            filters['scope'] = set(filters['scope'].split(','))
            for scope in filters['scope']:
                if scope not in ['mashup', 'operator', 'widget']:
                    return build_error_response(request, 400, _('Scope value not supported: %s') % scope)

        if filters['staff'] and not request.user.is_staff:
            return build_error_response(request, 403, _('Forbidden'))

        response_json = search(querytext, request, **filters)

        return HttpResponse(json.dumps(response_json, sort_keys=True), content_type='application/json')
Ejemplo n.º 25
0
    def create(self, request, workspace_id, tab_id, iwidget_id):

        workspace = get_object_or_404(Workspace, pk=workspace_id)
        if not request.user.is_superuser and workspace.creator != request.user:
            msg = _('You have not enough permission for updating the preferences of the iwidget')
            return build_error_response(request, 403, msg)

        iwidget = get_object_or_404(IWidget.objects.select_related('widget__resource'), pk=iwidget_id)
        if iwidget.tab_id != int(tab_id):
            raise Http404

        iwidget_info = iwidget.widget.resource.get_processed_info(translate=True, process_variables=True)

        new_values = parse_json_request(request)

        for var_name in new_values:
            try:
                vardef = iwidget_info['variables']['preferences'][var_name]
            except KeyError:
                msg = _('Invalid preference: "%s"') % var_name
                return build_error_response(request, 422, msg)

            if vardef['readonly'] is True:
                msg = _('"%s" preference is read only.') % var_name
                return build_error_response(request, 403, msg)

            iwidget.set_variable_value(var_name, new_values[var_name])

        iwidget.save()
        return HttpResponse(status=204)
Ejemplo n.º 26
0
    def read(self, request):

        querytext = request.GET.get('q', '')

        filters = {
            'pagenum': int(request.GET.get('pagenum', '1')),
            'maxresults': int(request.GET.get('maxresults', '30')),
            'orderby': request.GET.get('orderby', '-creation_date'),
            'scope': request.GET.get('scope', None),
            'staff': request.GET.get('staff', 'false').lower() == 'true',
        }

        if not filters['orderby'].replace(
                '-', '', 1) in ['creation_date', 'name', 'vendor']:
            return build_error_response(
                request, 400,
                _('Orderby value not supported: %s') % filters['orderby'])

        if filters['scope']:
            filters['scope'] = set(filters['scope'].split(','))
            for scope in filters['scope']:
                if scope not in ['mashup', 'operator', 'widget']:
                    return build_error_response(
                        request, 400,
                        _('Scope value not supported: %s') % scope)

        if filters['staff'] and not request.user.is_staff:
            return build_error_response(request, 403, _('Forbidden'))

        response_json = search(querytext, request, **filters)

        return HttpResponse(json.dumps(response_json),
                            content_type='application/json')
Ejemplo n.º 27
0
    def create(self, request):

        try:
            received_data = json.loads(request.body)
        except ValueError as e:
            msg = _("malformed json data: %s") % e
            return build_error_response(request, 400, msg)

        if 'options' not in received_data:
            return build_error_response(request, 400, _("Missing marketplace options"))

        try:
            validate_url_param('options.url', received_data['options']['url'])
        except (TypeError, ValueError) as e:
            return build_error_response(request, 422, text_type(e))

        if 'user' not in received_data['options'] or received_data['options']['user'] == request.user.username:
            user_entry = request.user
        elif received_data['options'].get('user', None) is not None:
            user_entry = User.objects.get(username=received_data['options']['user'])
        else:
            user_entry = None

        if (user_entry is None or user_entry != request.user) and not request.user.is_superuser:
            return build_error_response(request, 403, _("You don't have permissions for adding public marketplaces"))

        if 'user' in received_data['options']:
            del received_data['options']['user']

        try:
            Market.objects.create(user=user_entry, name=received_data['name'], options=json.dumps(received_data['options']))
        except IntegrityError:
            return build_error_response(request, 409, 'Market name already in use')

        return HttpResponse(status=201)
Ejemplo n.º 28
0
    def read(self, request):

        querytext = request.GET.get('q', '')
        indexname = request.GET.get('namespace', '').strip()

        if indexname == '':
            message = _('Missing namespace GET parameter providing a search namespace')
            return build_error_response(request, 400, message)

        if not is_available(indexname):
            message = _('Invalid search namespace: %s' % indexname)
            return build_error_response(request, 422, message)

        try:
            pagenum = int(request.GET.get('pagenum', '1'))
        except ValueError:
            message = _('Invalid pagenum value: %s' % request.GET['pagenum'])
            return build_error_response(request, 422, message)

        try:
            maxresults = int(request.GET.get('maxresults', '30'))
        except ValueError:
            message = _('Invalid maxresults value: %s' % request.GET['maxresults'])
            return build_error_response(request, 422, message)

        orderby = tuple(entry.strip() for entry in request.GET.get('orderby', '').split(','))
        if orderby == ("",):
            orderby = None

        result = get_search_engine(indexname)(request, querytext, pagenum=pagenum, maxresults=maxresults, orderby=orderby)

        return HttpResponse(json.dumps(result, sort_keys=True), status=200, content_type='application/json; charset=utf-8')
Ejemplo n.º 29
0
    def process(self, request):

        try:
            data = json.loads(request.body)
        except ValueError as e:
            msg = _("malformed json data: %s") % unicode(e)
            return build_error_response(request, 400, msg)

        (resource_vendor, resource_name, resource_version) = data['resource'].split('/')
        resource = get_object_or_404(CatalogueResource, vendor=resource_vendor, short_name=resource_name, version=resource_version)

        if not resource.fromWGT:
            msg = _('Only packaged resources can be published')
            return build_error_response(request, 400, msg)

        base_dir = catalogue.wgt_deployer.get_base_dir(resource_vendor, resource_name, resource_version)
        wgt_file = WgtFile(os.path.join(base_dir, resource.template_uri))

        market_managers = get_market_managers(request.user)
        errors = {}
        for market_endpoint in data['marketplaces']:

            try:
                market_managers[market_endpoint['market']].publish(market_endpoint, wgt_file, request.user, request=request)
            except Exception as e:
                errors[market_endpoint['market']] = unicode(e)

        if len(errors) == 0:
            return HttpResponse(status=204)
        elif len(errors) == len(data['marketplaces']):
            return HttpResponse(json.dumps(errors), status=502, content_type='application/json; charset=UTF-8')
        else:
            return HttpResponse(json.dumps(errors), status=200, content_type='application/json; charset=UTF-8')
Ejemplo n.º 30
0
    def create(self, request, workspace_id, tab_id, iwidget_id):

        workspace = Workspace.objects.get(id=workspace_id)
        if not request.user.is_superuser and workspace.creator != request.user:
            msg = _('You have not enough permission for updating the persistent variables of this widget')
            return build_error_response(request, 403, msg)

        try:
            new_values = json.loads(request.body)
        except ValueError as e:
            msg = _("malformed json data: %s") % unicode(e)
            return build_error_response(request, 400, msg)

        try:
            for var_name in new_values:
                variable = Variable.objects.select_related('vardef').get(
                    vardef__name=var_name,
                    vardef__aspect='PROP',
                    iwidget__id=iwidget_id
                )
                variable.set_variable_value(new_values[var_name])
                variable.save()
        except Variable.DoesNotExist:
            msg = _('Invalid persistent variable: "%s"') % var_name
            return build_error_response(request, 422, msg)

        return HttpResponse(status=204)
Ejemplo n.º 31
0
    def create(self, request, workspace_id, tab_id, iwidget_id):

        workspace = get_object_or_404(Workspace, pk=workspace_id)
        if not request.user.is_superuser and workspace.creator != request.user:
            msg = _(
                'You have not enough permission for updating the preferences of the iwidget'
            )
            return build_error_response(request, 403, msg)

        iwidget = get_object_or_404(
            IWidget.objects.select_related('widget__resource'), pk=iwidget_id)
        if iwidget.tab_id != int(tab_id):
            raise Http404

        iwidget_info = iwidget.widget.resource.get_processed_info(
            translate=True, process_variables=True)

        new_values = parse_json_request(request)

        for var_name in new_values:
            try:
                vardef = iwidget_info['variables']['preferences'][var_name]
            except KeyError:
                msg = _('Invalid preference: "%s"') % var_name
                return build_error_response(request, 422, msg)

            if vardef['readonly'] is True:
                msg = _('"%s" preference is read only.') % var_name
                return build_error_response(request, 403, msg)

            iwidget.set_variable_value(var_name, new_values[var_name])

        iwidget.save()
        return HttpResponse(status=204)
Ejemplo n.º 32
0
    def process(self, request):

        data = parse_json_request(request)

        (resource_vendor, resource_name, resource_version) = data['resource'].split('/')
        resource = get_object_or_404(CatalogueResource, vendor=resource_vendor, short_name=resource_name, version=resource_version)

        if not resource.is_available_for(request.user):
            return build_error_response(request, 403, _('You are not allowed to delete this market'))

        base_dir = catalogue.wgt_deployer.get_base_dir(resource_vendor, resource_name, resource_version)
        wgt_file = WgtFile(os.path.join(base_dir, resource.template_uri))

        market_managers = get_market_managers(request.user)
        errors = {}
        for market_endpoint in data['marketplaces']:

            try:
                market_managers[market_endpoint['market']].publish(market_endpoint, wgt_file, request.user, request=request)
            except Exception as e:
                errors[market_endpoint['market']] = text_type(e)

        if len(errors) == 0:
            return HttpResponse(status=204)
        elif len(errors) == len(data['marketplaces']):
            return build_error_response(request, 502, _('Something went wrong (see details for more info)'), details=errors)
        else:
            return build_error_response(request, 200, _('Something went wrong (see details for more info)'), details=errors)
Ejemplo n.º 33
0
def add_tenant(request):

    data = parse_json_request(request)

    id_4CaaSt = data['4CaaStID']

    if id_4CaaSt is None:
        return build_error_response(request, 400, _('Missing 4CaaStID'))

    if not isinstance(id_4CaaSt, string_types) or id_4CaaSt.strip() == '':
        return build_error_response(request, 400, _('Invalid 4CaaStID'))

    username = parse_username(id_4CaaSt)

    status = 201
    try:
        user = User.objects.create_user(username, '*****@*****.**', username)
    except:
        status = 209
        user = User.objects.get(username=username)
        try:
            if user.tenantprofile_4CaaSt.id_4CaaSt != id_4CaaSt:
                msg = "A user with the same name and with different tenant id already exists."
                return build_error_response(request, 400, msg)
            else:
                return HttpResponse(status)
        except TenantProfile.DoesNotExist:
            pass

    TenantProfile.objects.create(user=user, id_4CaaSt=id_4CaaSt)

    return HttpResponse(status)
Ejemplo n.º 34
0
    def create(self, request):

        try:
            if 'file' in request.FILES:

                request_file = request.FILES['file']
                resource = add_packaged_resource(request_file, request.user)

            elif 'template_uri' in request.POST:

                template_uri = request.POST['template_uri']
                downloaded_file = download_http_content(template_uri,
                                                        user=request.user)
                resource = add_packaged_resource(BytesIO(downloaded_file),
                                                 request.user)

            else:

                return build_error_response(
                    request, 400, _("Missing parameter: template_uri or file"))

        except TemplateParseException as e:

            return build_error_response(request, 400, e.msg)

        except IntegrityError:

            return build_error_response(request, 409,
                                        _('Resource already exists'))

        resource.users.add(request.user)

        return HttpResponse(resource.json_description,
                            content_type='application/json; charset=UTF-8')
Ejemplo n.º 35
0
    def process(self, request):

        if not request.user.is_superuser:
            return build_error_response(request, 403, _("You don't have permission to switch current session user"))

        try:
            user_info = json.loads(request.body)
        except ValueError as e:
            msg = _("malformed json data: %s") % unicode(e)
            return build_error_response(request, 400, msg)

        if "username" not in user_info:
            return build_error_response(request, 422, "Missing target user info")

        user_id = get_object_or_404(User, username=user_info['username']).id
        target_user = None
        for backend in auth.get_backends():
            try:
                target_user = backend.get_user(user_id)
            except:
                continue
            if target_user is None:
                continue
            # Annotate the user object with the path of the backend.
            target_user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
            break

        if target_user is None:
            raise Http404

        auth.login(request, target_user)

        return HttpResponse(status=204)
Ejemplo n.º 36
0
def add_tenant(request):

    data = parse_json_request(request)

    id_4CaaSt = data['4CaaStID']

    if id_4CaaSt is None:
        return build_error_response(request, 400, _('Missing 4CaaStID'))

    if not isinstance(id_4CaaSt, string_types) or id_4CaaSt.strip() == '':
        return build_error_response(request, 400, _('Invalid 4CaaStID'))

    username = parse_username(id_4CaaSt)

    status = 201
    try:
        user = User.objects.create_user(username, '*****@*****.**', username)
    except:
        status = 209
        user = User.objects.get(username=username)
        try:
            if user.tenantprofile_4CaaSt.id_4CaaSt != id_4CaaSt:
                msg = "A user with the same name and with different tenant id already exists."
                return build_error_response(request, 400, msg)
            else:
                return HttpResponse(status)
        except TenantProfile.DoesNotExist:
            pass

    TenantProfile.objects.create(user=user, id_4CaaSt=id_4CaaSt)

    return HttpResponse(status)
Ejemplo n.º 37
0
    def delete(self, request, workspace_id, tab_id):

        # Get tab, if it does not exist, an http 404 error is returned
        tab = get_object_or_404(Tab.objects.select_related('workspace'), workspace__pk=workspace_id, pk=tab_id)
        if not request.user.is_superuser and not tab.workspace.users.filter(id=request.user.id).exists():
            return build_error_response(request, 403, _('You are not allowed to remove this tab'))

        tabs = Tab.objects.filter(workspace__pk=workspace_id).order_by('position')[::1]
        if len(tabs) == 1:
            msg = _("Tab cannot be deleted as workspaces need at least one tab")
            return build_error_response(request, 403, msg)

        if tab.iwidget_set.filter(readOnly=True).exists():
            msg = _("Tab cannot be deleted as it contains widgets that cannot be deleted")
            return build_error_response(request, 403, msg)

        # decrease the position of the following tabs
        for t in range(tab.position + 1, len(tabs)):
            tabs[t].position = tabs[t].position - 1
            tabs[t].save()

        # Remove the tab
        tabs.remove(tab)
        deleteTab(tab, request.user)

        if tab.visible:
            # set a new visible tab (first tab by default)
            activeTab = tabs[0]
            setVisibleTab(request.user, workspace_id, activeTab)

        return HttpResponse(status=204)
Ejemplo n.º 38
0
    def create(self, request, workspace_id, tab_id, iwidget_id):

        workspace = get_object_or_404(Workspace, pk=workspace_id)

        iwidget = get_object_or_404(IWidget, pk=iwidget_id)
        if iwidget.tab_id != int(tab_id):
            raise Http404

        iwidget_info = iwidget.widget.resource.get_processed_info(translate=True, process_variables=True)

        new_values = parse_json_request(request)

        for var_name in new_values:
            if var_name not in iwidget_info['variables']['properties']:
                msg = _('Invalid persistent variable: "%s"') % var_name
                return build_error_response(request, 422, msg)

            # Check if its multiuser
            if not iwidget_info['variables']['properties'][var_name].get("multiuser", False):
                # No multiuser -> Check permissions
                if workspace.creator != request.user:
                    msg = _('You have not enough permission for updating the persistent variables of this widget')
                    return build_error_response(request, 403, msg)
            else:
                # Multiuser -> Check permissions
                if not workspace.is_available_for(request.user):
                    msg = _('You have not enough permission for updating the persistent variables of this widget')
                    return build_error_response(request, 403, msg)

            iwidget.set_variable_value(var_name, new_values[var_name], request.user)

        iwidget.save()
        return HttpResponse(status=204)
Ejemplo n.º 39
0
    def create(self, request, workspace_id):

        ts = parse_json_request(request)
        fields = []

        workspace = get_object_or_404(Workspace, pk=workspace_id)
        if not (request.user.is_superuser
                or workspace.users.filter(pk=request.user.pk).exists()):
            return build_error_response(
                request, 403,
                _('You are not allowed to update this workspace'))

        if 'name' in ts:
            workspace.name = ts['name']
            fields.append('name')

        if 'title' in ts:
            workspace.title = ts['title']
            fields.append('title')

        if 'description' in ts:
            workspace.description = ts['description']
            fields.append('description')

        if 'longdescription' in ts:
            workspace.longdescription = ts['longdescription']
            fields.append('longdescription')

        try:
            workspace.save(update_fields=fields)
        except IntegrityError:
            msg = _('A workspace with the given name already exists')
            return build_error_response(request, 409, msg)

        return HttpResponse(status=204)
Ejemplo n.º 40
0
def _parse_ac_request(request):

    fileURL = None
    file_contents = None
    content_type = get_content_type(request)[0]

    try:
        data = json.loads(request.body)
    except Exception as e:
        msg = _("malformed json data: %s") % unicode(e)
        return build_error_response(request, 400, msg)

    if 'url' not in data:
        return build_error_response(request, 400, _('Missing widget URL'))

    fileURL = data.get('url')
    id_4CaaSt = data.get('4CaaStID')

    if id_4CaaSt is None:
        return build_error_response(request, 400, _('Missing 4CaaStID'))

    if not isinstance(id_4CaaSt, string_types) or id_4CaaSt.strip() == '':
        return build_error_response(request, 400, _('Invalid 4CaaStID'))

    try:
        downloaded_file = download_http_content(fileURL)
    except:
        return build_error_response(request, 409, _('Mashable application component could not be downloaded'))

    downloaded_file = StringIO(downloaded_file)
    file_contents = WgtFile(downloaded_file)

    # Create a custom version of the resource
    template = TemplateParser(file_contents.get_template())
    template_info = template.get_resource_info()
    template_info['name'] += '@' + id_4CaaSt

    for pref_name, pref_value in six.iteritems(data.get('preferences', {})):
        for widget_pref_index, widget_pref in enumerate(template_info['preferences']):
            if widget_pref['name'] == pref_name:
                template_info['preferences'][widget_pref_index]['readonly'] = True
                template_info['preferences'][widget_pref_index]['value'] = pref_value
                break

    # Write a new Wgt file
    new_file = StringIO()
    zin = zipfile.ZipFile(downloaded_file, 'r')
    zout = zipfile.ZipFile(new_file, 'w')
    zout.writestr('config.xml', write_rdf_description(template_info))
    for item in zin.infolist():
        if item.filename == 'config.xml':
            continue
        zout.writestr(item, zin.read(item.filename))
    zin.close()
    zout.close()

    file_contents = WgtFile(new_file)

    return id_4CaaSt, file_contents, fileURL
Ejemplo n.º 41
0
def proxy_request(request, protocol, domain, path):

    # TODO improve proxy security
    request_method = request.method.upper()
    if protocol not in ('http', 'https'):
        return build_error_response(request, 422, _("Invalid protocol: %s") % protocol)

    try:
        if settings.SESSION_COOKIE_NAME not in request.COOKIES:
            raise Exception()

        parsed_referer = urlparse(request.META["HTTP_REFERER"])
        if request.get_host() != parsed_referer[1]:
            raise Exception()

        referer_view_info = resolve(parsed_referer.path)
        if referer_view_info.url_name == 'wirecloud.workspace_view':

            workspace = Workspace.objects.get(creator__username=unquote(referer_view_info.kwargs['owner']), name=unquote(referer_view_info.kwargs['name']))
            if not workspace.is_available_for(request.user):
                raise Exception()

        elif referer_view_info.url_name == 'wirecloud.showcase_media' or referer_view_info.url_name == 'wirecloud|proxy':

            if request_method not in ('GET', 'POST'):
                raise Exception()

            workspace = None

        else:
            raise Exception()

    except:
        return build_error_response(request, 403, _("Invalid request"))

    url = protocol + '://' + domain + path
    if len(request.GET) > 0:
        url += '?' + request.GET.urlencode()

    try:
        response = WIRECLOUD_PROXY.do_request(request, url, request_method, workspace)
    except Exception as e:
        log_error(request, sys.exc_info())
        msg = _("Error processing proxy request: %s") % e
        return build_error_response(request, 500, msg)

    # Process cookies
    for key in response.cookies:
        cookie = response.cookies[key]

        if cookie['path'] == '':
            cookie['path'] = reverse('wirecloud|proxy', kwargs={'protocol': protocol, 'domain': domain, 'path': path})
        else:
            cookie['path'] = reverse('wirecloud|proxy', kwargs={'protocol': protocol, 'domain': domain, 'path': cookie['path']})

    return response
Ejemplo n.º 42
0
    def delete(self, request, market, user=None):

        if user is None and (not request.user.is_superuser or market == 'local'):
            return build_error_response(request, 403, _('You are not allowed to delete this market'))

        if user != request.user.username and not request.user.is_superuser:
            return build_error_response(request, 403, _('You are not allowed to delete this market'))

        get_object_or_404(Market, user__username=user, name=market).delete()

        return HttpResponse(status=204)
Ejemplo n.º 43
0
def proxy_request(request, protocol, domain, path):

    # TODO improve proxy security
    request_method = request.method.upper()
    if protocol not in ('http', 'https'):
        return build_error_response(request, 422,
                                    _("Invalid protocol: %s") % protocol)

    try:
        if settings.SESSION_COOKIE_NAME not in request.COOKIES:
            raise Exception()

        context = parse_context_from_referer(request, request_method)

    except:
        return build_error_response(request, 403, _("Invalid request"))

    url = protocol + '://' + domain + path
    if len(request.GET) > 0:
        url += '?' + request.GET.urlencode()

    try:
        # Extract headers from META
        parse_request_headers(request, context)

        response = WIRECLOUD_PROXY.do_request(request, url, request_method,
                                              context)
    except ValidationError as e:
        return e.get_response(request)
    except Exception as e:
        log_error(request, sys.exc_info())
        msg = _("Error processing proxy request: %s") % e
        return build_error_response(request, 500, msg)

    # Process cookies
    for key in response.cookies:
        cookie = response.cookies[key]

        if cookie['path'] == '':
            cookie['path'] = reverse('wirecloud|proxy',
                                     kwargs={
                                         'protocol': protocol,
                                         'domain': domain,
                                         'path': path
                                     })
        else:
            cookie['path'] = reverse('wirecloud|proxy',
                                     kwargs={
                                         'protocol': protocol,
                                         'domain': domain,
                                         'path': cookie['path']
                                     })

    return response
Ejemplo n.º 44
0
    def create(self, request, workspace_id, tab_id, iwidget_id):

        workspace = Workspace.objects.get(id=workspace_id)
        if not request.user.is_superuser and workspace.creator != request.user:
            msg = _('You have not enough permission for updating the preferences of the iwidget')
            return build_error_response(request, 403, msg)

        try:
            new_values = json.loads(request.raw_post_data)
        except ValueError, e:
            msg = _("malformed json data: %s") % unicode(e)
            return build_error_response(request, 400, msg)
Ejemplo n.º 45
0
    def read(self, request, market_user, market_name):

        adaptor = get_market_adaptor(market_user, market_name)

        try:
            result = adaptor.get_all_stores()
        except HTTPError as e:
            details = "%s" % e
            return build_error_response(request, 502, "Unexpected response", details=details)
        except (ConnectionError, ConnectTimeout):
            return build_error_response(request, 504, "Connection Error")

        return HttpResponse(json.dumps(result), content_type='application/json; chaset=UTF-8')
Ejemplo n.º 46
0
    def create(self, request, workspace_id, tab_id):

        tab = get_object_or_404(Tab.objects.select_related('workspace'),
                                workspace__pk=workspace_id,
                                pk=tab_id)
        if tab.workspace.creator != request.user:
            return build_error_response(
                request, 403,
                _('You are not allowed to update this workspace'))

        user_workspace = UserWorkspace.objects.get(user__id=request.user.id,
                                                   workspace__id=workspace_id)
        if user_workspace.manager != '':
            return build_error_response(
                request, 403,
                _('You are not allowed to update this workspace'))

        data = parse_json_request(request)

        if 'visible' in data:
            visible = data['visible']
            if isinstance(visible, string_types):
                visible = visible.strip().lower()
                if visible not in ('true', 'false'):
                    return build_error_response(request, 422,
                                                _('Invalid visible value'))
                visible = visible == 'true'
            elif not isinstance(visible, bool):
                return build_error_response(request, 422,
                                            _('Invalid visible value'))

            if visible:
                # Only one visible tab
                setVisibleTab(request.user, workspace_id, tab)
            else:
                tab.visible = False

        if 'name' in data:
            tab.name = data['name']

        if 'title' in data:
            tab.title = data['title']

        try:
            tab.save()
        except IntegrityError:
            msg = _(
                'A tab with the given name already exists for the workspace')
            return build_error_response(request, 409, msg)

        return HttpResponse(status=204)
Ejemplo n.º 47
0
    def read(self, request, market_user, market_name, store='', search_string='widget'):

        adaptor = get_market_adaptor(market_user, market_name)
        user_data = get_market_user_data(request.user, market_user, market_name)

        try:
            result = adaptor.full_text_search(store, search_string, user_data)
        except HTTPError as e:
            details = "%s" % e
            return build_error_response(request, 502, "Unexpected response", details=details)
        except (ConnectionError, ConnectTimeout):
            return build_error_response(request, 504, "Connection Error")

        return HttpResponse(json.dumps(result), content_type='application/json; chaset=UTF-8')
Ejemplo n.º 48
0
    def delete(self, request, market, user=None):

        if user is None and (not request.user.is_superuser
                             or market == 'local'):
            return build_error_response(
                request, 403, _('You are not allowed to delete this market'))

        if user != request.user.username and not request.user.is_superuser:
            return build_error_response(
                request, 403, _('You are not allowed to delete this market'))

        get_object_or_404(Market, user__username=user, name=market).delete()

        return HttpResponse(status=204)
Ejemplo n.º 49
0
    def read(self, request, market_user, market_name, store, offering_id):

        adaptor = get_market_adaptor(market_user, market_name)
        user_data = get_market_user_data(request.user, market_user, market_name)

        try:
            offering_info = adaptor.get_offering_info(store, offering_id, user_data)[0]
        except HTTPError as e:
            details = "%s" % e
            return build_error_response(request, 502, "Unexpected response", details=details)
        except (ConnectionError, ConnectTimeout):
            return build_error_response(request, 504, "Connection Error")

        return HttpResponse(json.dumps(offering_info), content_type='application/json; charset=UTF-8')
Ejemplo n.º 50
0
    def read(self, request):

        querytext = request.GET.get('q', '')

        filters = {
            'orderby': request.GET.get('orderby', '-creation_date'),
            'scope': request.GET.get('scope', None),
            'staff': request.GET.get('staff', 'false').lower() == 'true',
        }

        try:
            filters['pagenum'] = int(request.GET.get('pagenum', '1'))
        except ValueError:
            message = _('Invalid pagenum value: %s' % request.GET['pagenum'])
            return build_error_response(request, 422, message)

        try:
            filters['maxresults'] = int(request.GET.get('maxresults', '30'))
        except ValueError:
            message = _('Invalid maxresults value: %s' %
                        request.GET['maxresults'])
            return build_error_response(request, 422, message)

        if not filters['orderby'].replace(
                '-', '', 1) in ['creation_date', 'name', 'vendor']:
            return build_error_response(
                request, 400,
                _('Orderby value not supported: %s') % filters['orderby'])

        # This API only supports ordering by one field, but the searcher supports ordering by multiple fields
        filters['orderby'] = [filters['orderby']]

        if filters['scope']:
            filters['scope'] = filters['scope'].split(',')
            for scope in filters['scope']:
                if scope not in ['mashup', 'operator', 'widget']:
                    return build_error_response(
                        request, 400,
                        _('Scope value not supported: %s') % scope)

        if filters['staff'] and not request.user.is_staff:
            return build_error_response(request, 403, _('Forbidden'))

        response_json = get_search_engine("resource")(querytext, request,
                                                      **filters)

        return HttpResponse(json.dumps(response_json, sort_keys=True),
                            content_type='application/json')
Ejemplo n.º 51
0
    def create(self, request, workspace_id):

        ts = parse_json_request(request)
        fields = []

        workspace = get_object_or_404(Workspace, pk=workspace_id)
        if not (request.user.is_superuser
                or workspace.users.filter(pk=request.user.pk).exists()):
            return build_error_response(
                request, 403,
                _('You are not allowed to update this workspace'))

        if 'name' in ts:
            workspace.name = ts['name']
            fields.append('name')

        if 'description' in ts:
            workspace.description = ts['description']
            fields.append('description')

        if 'longdescription' in ts:
            workspace.longdescription = ts['longdescription']
            fields.append('longdescription')

        workspace.save(update_fields=fields)

        return HttpResponse(status=204)
Ejemplo n.º 52
0
    def read(self, request, workspace_id):

        workspace = get_object_or_404(Workspace, id=workspace_id)
        if not workspace.is_available_for(request.user):
            return build_error_response(request, 403, _("You don't have access to this workspace"))

        resources = set()
        for tab in workspace.tab_set.all():
            for iwidget in tab.iwidget_set.select_related('widget__resource').all():
                resources.add(iwidget.widget.resource)

        for operator_id, operator in six.iteritems(workspace.wiringStatus['operators']):
            vendor, name, version = operator['name'].split('/')
            try:
                resources.add(CatalogueResource.objects.get(vendor=vendor, short_name=name, version=version))
            except CatalogueResource.DoesNotExist:
                pass

        result = {}
        process_urls = process_urls=request.GET.get('process_urls', 'true') == 'true'
        for resource in resources:
            options = resource.get_processed_info(request, process_urls=process_urls)
            result[resource.local_uri_part] = options

        return HttpResponse(json.dumps(result), content_type='application/json; chatset=UTF-8')
Ejemplo n.º 53
0
    def update(self, request, workspace_id):

        workspace = get_object_or_404(Workspace, id=workspace_id)

        new_wiring_status = parse_json_request(request)
        old_wiring_status = workspace.wiringStatus

        if workspace.creator == request.user or request.user.is_superuser:
            result = self.checkWiring(request,
                                      new_wiring_status,
                                      old_wiring_status,
                                      can_update_secure=False)
        elif workspace.is_available_for(request.user):
            result = self.checkMultiuserWiring(request,
                                               new_wiring_status,
                                               old_wiring_status,
                                               workspace.creator,
                                               can_update_secure=False)
        else:
            return build_error_response(
                request, 403,
                _('You are not allowed to update this workspace'))

        if result is not True:
            return result

        workspace.wiringStatus = new_wiring_status
        workspace.save()

        return HttpResponse(status=204)
Ejemplo n.º 54
0
def provide_authorization_code(request):

    params = request.GET.dict()

    if 'redirect_uri' not in params:
        return build_error_response(request, 400,
                                    'Missing redirect_uri parameter')

    if 'response_type' not in params or 'client_id' not in params:
        return provider._make_redirect_error_response(params['redirect_uri'],
                                                      'invalid_request')

    try:
        client = provider.get_client(params['client_id'])
    except:
        client = None
    error_response = provider.validate_authorization_code_request(
        request, request.user, client=client, **params)
    if error_response is not None:
        return error_response

    if request.method == 'GET':
        return render(request, 'wirecloud/oauth2provider/auth.html',
                      {'app': client})
    elif request.POST.get('action') == 'auth':
        return provider.get_authorization_code(request,
                                               request.user,
                                               client=client,
                                               **params)
    else:
        return provider._make_redirect_error_response(params['redirect_uri'],
                                                      'access_denied')
Ejemplo n.º 55
0
    def create(self, request, workspace_id):

        ts = parse_json_request(request)

        workspace = get_object_or_404(Workspace, pk=workspace_id)
        if not (request.user.is_superuser
                or workspace.users.filter(pk=request.user.pk).exists()):
            return build_error_response(
                request, 403,
                _('You are not allowed to update this workspace'))

        if 'active' in ts:

            active = ts.get('active', False)
            if isinstance(active, string_types):
                active = ts['active'].lower() == 'true'

            if active:
                # Only one active workspace
                setActiveWorkspace(request.user, workspace)
            else:
                currentUserWorkspace = UserWorkspace.objects.get(
                    workspace=workspace, user=request.user)
                currentUserWorkspace.active = False
                currentUserWorkspace.save()

        if 'name' in ts:
            workspace.name = ts['name']

        workspace.save()

        return HttpResponse(status=204)
Ejemplo n.º 56
0
    def create(self, request, workspace_id):

        # Check Workspace existance and owned by this user
        workspace = get_object_or_404(Workspace, pk=workspace_id)
        if not (request.user.is_superuser or workspace.users.filter(pk=request.user.pk).exists()):
            return build_error_response(request, 403, _('You are not allowed to update this workspace'))

        preferences_json = parse_json_request(request)

        if 'sharelist' in preferences_json:
            workspace.users.clear()
            workspace.groups.clear()
            sharelist = json.loads(preferences_json['sharelist']['value'])
            for item in sharelist:
                try:
                    user = User.objects.get(username=item['name'])
                except User.DoesNotExist:
                    continue

                workspace.userworkspace_set.create(user=user)
                try:
                    workspace.groups.add(user.organization.group)
                except Organization.DoesNotExist:
                    pass
            del preferences_json['sharelist']

        if 'public' in preferences_json:
            workspace.public = preferences_json['public']['value'].strip().lower() == 'true'
            workspace.save()
            del preferences_json['public']

        update_workspace_preferences(workspace, preferences_json)

        return HttpResponse(status=204)
Ejemplo n.º 57
0
def deploy_tenant_ac(request):

    result = _parse_ac_request(request)
    if isinstance(result, HttpResponse):
        return result

    id_4CaaSt, wgt_file, fileURL = result

    # Process 4CaaSt Id
    username = parse_username(id_4CaaSt)

    user = get_object_or_404(User, username=username)

    # Install uploaded MAC resource
    try:

        resource = install_resource_to_user(user, file_contents=wgt_file)

    except TemplateParseException as e:

        return build_error_response(request, 400, e.msg)

    # Create a workspace if the resource is a mashup
    if resource.resource_type() == 'mashup' and not Workspace.objects.filter(
            creator=user, name=resource.short_name).exists():
        buildWorkspaceFromTemplate(resource.get_template(), user, True)

    return HttpResponse(status=204)
Ejemplo n.º 58
0
def bad_request(request, exception=None):

    return build_error_response(request,
                                400,
                                'Bad Request',
                                extra_formatters,
                                context={'request_path': request.path})
Ejemplo n.º 59
0
def permission_denied(request, exception=None):

    return build_error_response(request,
                                403,
                                'Forbidden',
                                extra_formatters,
                                context={'request_path': request.path})
Ejemplo n.º 60
0
def page_not_found(request):

    return build_error_response(request,
                                404,
                                'Page Not Found',
                                extra_formatters,
                                context={'request_path': request.path})