Пример #1
0
def edit_instance(request):
    instance_id = request.POST['instanceid']
    name = request.POST['name']
    
    errors = ""
    response_dict = {}
    
    # test if the name is "Local"
    if name.upper() == "LOCAL":
        errors += "By default, the instance named Local is the instance currently running."
    else:   
        # test if an instance with the same name exists
        instance = Instance.objects(name=name)
        if len(instance) != 0 and str(instance[0].id) != instance_id:
            errors += "An instance with the same name already exists.<br/>"
    
    # If some errors display them, otherwise insert the instance
    if errors == "":
        instance = Instance.objects.get(pk=instance_id)
        instance.name = name
        instance.save()
    else:
        response_dict = {'errors': errors}
    
    return HttpResponse(json.dumps(response_dict), content_type='application/javascript')
Пример #2
0
def explore_perform_search(request):
    try:
        template = loader.get_template('explore/explore_perform_search.html')
        instances = Instance.objects()
        if 'HTTPS' in request.META['SERVER_PROTOCOL']:
            protocol = "https"
        else:
            protocol = "http"
        local = Instance(name="Local", protocol=protocol, address=request.META['REMOTE_ADDR'], port=request.META['SERVER_PORT'])
        listInstances = [local]
        for instance in instances:
            listInstances.append(instance)

        template_hash = Template.objects.get(pk=request.session['exploreCurrentTemplateID']).hash

        queries = SavedQuery.objects(user=str(request.user.id), template=str(request.session['exploreCurrentTemplateID']))
        context = RequestContext(request, {
            'instances': listInstances,
            'template_hash': template_hash,
            'queries':queries,
            'template_id': request.session['exploreCurrentTemplateID']
        })
        if 'exploreCurrentTemplateID' not in request.session:
            return redirect('/explore/select-template')
        else:
            return HttpResponse(template.render(context))
    except:
        return redirect("/explore")
Пример #3
0
def edit_instance(request):
    instance_id = request.POST['instanceid']
    name = request.POST['name']

    errors = ""
    response_dict = {}

    # test if the name is "Local"
    if name.upper() == "LOCAL":
        errors += "By default, the instance named Local is the instance currently running."
    else:
        # test if an instance with the same name exists
        instance = Instance.objects(name=name)
        if len(instance) != 0 and str(instance[0].id) != instance_id:
            errors += "An instance with the same name already exists.<br/>"

    # If some errors display them, otherwise insert the instance
    if errors == "":
        instance = Instance.objects.get(pk=instance_id)
        instance.name = name
        instance.save()
    else:
        response_dict = {'errors': errors}

    return HttpResponse(json.dumps(response_dict),
                        content_type='application/javascript')
Пример #4
0
def explore_perform_search(request):
    try:
        if request.user.is_authenticated():
            template = loader.get_template('explore_perform_search.html')
            instances = Instance.objects()   
            if 'HTTPS' in request.META['SERVER_PROTOCOL']:
                protocol = "https"
            else:
                protocol = "http"
            local = Instance(name="Local", protocol=protocol, address=request.META['REMOTE_ADDR'], port=request.META['SERVER_PORT'])
            listInstances = [local]
            for instance in instances:
                listInstances.append(instance) 
                
            template_hash = Template.objects.get(pk=request.session['exploreCurrentTemplateID']).hash
            
            queries = SavedQuery.objects(user=str(request.user.id), template=str(request.session['exploreCurrentTemplateID']))
            context = RequestContext(request, {
                'instances': listInstances,
                'template_hash': template_hash,
                'queries':queries,
            })
            request.session['currentYear'] = currentYear()
            if 'exploreCurrentTemplateID' not in request.session:
                return redirect('/explore/select-template')
            else:
                return HttpResponse(template.render(context))
        else:
            if 'loggedOut' in request.session:
                del request.session['loggedOut']
            request.session['next'] = '/explore/perform-search'
            return redirect('/login')
    except:
        return redirect("/explore")
Пример #5
0
 def test_create_instance(self):
     self.assertEquals(0, len(Instance.objects()))
     data = {
         'name': 'test',
         'protocol': 'http',
         'ip_address': '127.0.0.1',
         'port': 8082,
         'username': '******',
         'password': '******',
         'client_id': 'client_id',
         'client_secret': 'client_secret',
         'timeout': 12,
         'action': 'Ping'
     }
     response = '{"access_token": "token", "token_type": "Bearer", "expires_in": 31536000, "refresh_token": "refresh_token", "scope": "read write"}'
     create_instance(content=response, request=data)
     self.assertEquals(1, len(Instance.objects()))
Пример #6
0
def add_repository(request):
    if request.method == 'POST':


        form = RepositoryForm(request.POST)

        if form.is_valid():
            if request.POST["action"] == "Register":
                errors = ""

                # test if the name is "Local"
                if (request.POST["name"].upper() == "LOCAL"):
                    errors += "By default, the instance named Local is the instance currently running."
                else:
                    # test if an instance with the same name exists
                    instance = Instance.objects(name=request.POST["name"])
                    if len(instance) != 0:
                        errors += "An instance with the same name already exists.<br/>"

                # test if new instance is not the same as the local instance
                if request.POST["ip_address"] == request.META['REMOTE_ADDR'] and request.POST["port"] == request.META['SERVER_PORT']:
                    errors += "The address and port you entered refer to the instance currently running."
                else:
                    # test if an instance with the same address/port exists
                    instance = Instance.objects(address=request.POST["ip_address"], port=request.POST["port"])
                    if len(instance) != 0:
                        errors += "An instance with the address/port already exists.<br/>"

                # If some errors display them, otherwise insert the instance
                if(errors == ""):
                    try:
                        url = request.POST["protocol"] + "://" + request.POST["ip_address"] + ":" + request.POST["port"] + "/o/token/"
#                             data="grant_type=password&username="******"username"] + "&password="******"password"]
                        headers = {'content-type': 'application/x-www-form-urlencoded'}
                        data={
                            'grant_type': 'password',
                            'username': request.POST["username"],
                            'password': request.POST["password"],
                            'client_id': request.POST["client_id"],
                            'client_secret': request.POST["client_secret"]
                        }
                        r = requests.post(url=url, data=data, headers=headers, timeout=int(request.POST["timeout"]))
                        if r.status_code == 200:
                            now = datetime.now()
                            delta = timedelta(seconds=int(eval(r.content)["expires_in"]))
                            expires = now + delta
                            Instance(name=request.POST["name"], protocol=request.POST["protocol"], address=request.POST["ip_address"], port=request.POST["port"], access_token=eval(r.content)["access_token"], refresh_token=eval(r.content)["refresh_token"], expires=expires).save()
                            messages.add_message(request, messages.INFO, 'Repository registered with success.')
                            return redirect('/admin/repositories')
                        else:
                            message = "Unable to get access to the remote instance using these parameters."
                            return render(request, 'admin/add_repository.html', {'form':form, 'action_result':message})
                    except Exception, e:
                        message = "Unable to get access to the remote instance using these parameters."
                        return render(request, 'admin/add_repository.html', {'form':form, 'action_result':message})

                else:
                    return render(request, 'admin/add_repository.html', {'form':form, 'action_result':errors})

            elif request.POST["action"] == "Ping":
                try:
                    url = request.POST["protocol"] + "://" + request.POST["ip_address"] + ":" + request.POST["port"] + "/rest/ping"
                    r = requests.get(url, auth=(request.POST["username"], request.POST["password"]), timeout=int(request.POST["timeout"]))
                    if r.status_code == 200:
                        message = "Remote API reached with success."
                    else:
                        if 'detail' in eval(r.content):
                            message = "Error: " + eval(r.content)['detail']
                        else:
                            message = "Error: Unable to reach the remote API."
                except Exception, e:
                    message = "Error: Unable to reach the remote API."

                return render(request, 'admin/add_repository.html', {'form':form, 'action_result':message})
Пример #7
0
def add_repository(request):
    if request.method == 'POST':

        form = RepositoryForm(request.POST)

        if form.is_valid():
            if request.POST["action"] == "Register":
                errors = ""

                # test if the name is "Local"
                if (request.POST["name"].upper() == "LOCAL"):
                    errors += "By default, the instance named Local is the instance currently running."
                else:
                    # test if an instance with the same name exists
                    instance = Instance.objects(name=request.POST["name"])
                    if len(instance) != 0:
                        errors += "An instance with the same name already exists.<br/>"

                # test if new instance is not the same as the local instance
                if request.POST["ip_address"] == request.META[
                        'REMOTE_ADDR'] and request.POST[
                            "port"] == request.META['SERVER_PORT']:
                    errors += "The address and port you entered refer to the instance currently running."
                else:
                    # test if an instance with the same address/port exists
                    instance = Instance.objects(
                        address=request.POST["ip_address"],
                        port=request.POST["port"])
                    if len(instance) != 0:
                        errors += "An instance with the address/port already exists.<br/>"

                # If some errors display them, otherwise insert the instance
                if (errors == ""):
                    try:
                        url = request.POST["protocol"] + "://" + request.POST[
                            "ip_address"] + ":" + request.POST[
                                "port"] + "/o/token/"
                        #                             data="grant_type=password&username="******"username"] + "&password="******"password"]
                        headers = {
                            'content-type': 'application/x-www-form-urlencoded'
                        }
                        data = {
                            'grant_type': 'password',
                            'username': request.POST["username"],
                            'password': request.POST["password"],
                            'client_id': request.POST["client_id"],
                            'client_secret': request.POST["client_secret"]
                        }
                        r = requests.post(url=url,
                                          data=data,
                                          headers=headers,
                                          timeout=int(request.POST["timeout"]))
                        if r.status_code == 200:
                            now = datetime.now()
                            delta = timedelta(
                                seconds=int(eval(r.content)["expires_in"]))
                            expires = now + delta
                            Instance(
                                name=request.POST["name"],
                                protocol=request.POST["protocol"],
                                address=request.POST["ip_address"],
                                port=request.POST["port"],
                                access_token=eval(r.content)["access_token"],
                                refresh_token=eval(r.content)["refresh_token"],
                                expires=expires).save()
                            messages.add_message(
                                request, messages.INFO,
                                'Repository registered with success.')
                            return redirect('/admin/repositories')
                        else:
                            message = "Unable to get access to the remote instance using these parameters."
                            return render(request, 'admin/add_repository.html',
                                          {
                                              'form': form,
                                              'action_result': message
                                          })
                    except Exception, e:
                        message = "Unable to get access to the remote instance using these parameters."
                        return render(request, 'admin/add_repository.html', {
                            'form': form,
                            'action_result': message
                        })

                else:
                    return render(request, 'admin/add_repository.html', {
                        'form': form,
                        'action_result': errors
                    })

            elif request.POST["action"] == "Ping":
                try:
                    url = request.POST["protocol"] + "://" + request.POST[
                        "ip_address"] + ":" + request.POST[
                            "port"] + "/rest/ping"
                    r = requests.get(url,
                                     auth=(request.POST["username"],
                                           request.POST["password"]),
                                     timeout=int(request.POST["timeout"]))
                    if r.status_code == 200:
                        message = "Remote API reached with success."
                    else:
                        if 'detail' in eval(r.content):
                            message = "Error: " + eval(r.content)['detail']
                        else:
                            message = "Error: Unable to reach the remote API."
                except Exception, e:
                    message = "Error: Unable to reach the remote API."

                return render(request, 'admin/add_repository.html', {
                    'form': form,
                    'action_result': message
                })