several changes on auth flow 49/6349/2
authorlombardofr <lombardo@everyup.it>
Tue, 17 Jul 2018 15:27:36 +0000 (17:27 +0200)
committergarciadeblas <gerardo.garciadeblas@telefonica.com>
Thu, 19 Jul 2018 12:12:47 +0000 (13:12 +0100)
Change-Id: I49ddbb074a9bc018b9e5becafbe5956fa5860333
Signed-off-by: lombardofr <lombardo@everyup.it>
66 files changed:
.bowerrc
authosm/backend.py
authosm/exceptions.py [new file with mode: 0644]
authosm/models.py
authosm/utils.py [new file with mode: 0644]
authosm/views.py
bower.json
instancehandler/template/instance_list.html
instancehandler/template/instance_list_ns.html
instancehandler/template/instance_list_vnf.html
instancehandler/template/instance_operations_list.html
instancehandler/template/instance_topology_view.html [new file with mode: 0644]
instancehandler/template/modal/instance_create.html
instancehandler/urls.py
instancehandler/views.py
lib/osm/osmclient/clientv2.py
projecthandler/middleware.py [new file with mode: 0644]
projecthandler/template/project/descriptor/descriptor_view_base.html
projecthandler/template/project/osm/descriptor/descriptor_new.html
projecthandler/template/project/osm/descriptor/descriptor_view.html
projecthandler/template/project/osm/descriptor/descriptorlist.html
projecthandler/template/project/osm/osm_project_descriptors.html
projecthandler/template/project/osm/osm_project_details.html
projecthandler/template/project/osm/osm_project_left_sidebar.html
projecthandler/template/project/project_delete.html
projecthandler/template/project/project_details.html
projecthandler/template/project/project_graph_base.html
projecthandler/template/project/projectlist.html
projecthandler/template/project/repository/repo_base_left_sidebar.html [deleted file]
projecthandler/template/project/repository/repo_create_modal.html [deleted file]
projecthandler/template/project/repository/repo_list.html [deleted file]
projecthandler/urls/project.py
projecthandler/views.py
sdnctrlhandler/template/sdn_create.html
sdnctrlhandler/template/sdn_list.html
sdnctrlhandler/views.py
sf_t3d/settings.py
sf_t3d/urls.py
sf_t3d/views.py
sf_user/__init__.py [deleted file]
sf_user/admin.py [deleted file]
sf_user/apps.py [deleted file]
sf_user/management/__init__.py [deleted file]
sf_user/management/commands/__init__.py [deleted file]
sf_user/management/commands/clean_guest_data.py [deleted file]
sf_user/management/commands/clearsessions.py [deleted file]
sf_user/models.py [deleted file]
sf_user/sessions.py [deleted file]
sf_user/tests.py [deleted file]
sf_user/views.py [deleted file]
static/src/instancehandler/instance_list.js
static/src/instancehandler/instance_topology_view.js [new file with mode: 0644]
static/src/osm_gui_properties.js [new file with mode: 0644]
static/src/projecthandler/composer.js [new file with mode: 0644]
static/src/projecthandler/descriptorslist.js
static/src/projecthandler/osm/project_graph.js
static/src/sdnctrlhandler/sdn_list.js
static/src/utils.js
static/topology3D/js/graph_editor.js
static/topology3D/js/model_graph_editor.js
template/topology_toolbar.html
template/topology_toolbar_instance.html [new file with mode: 0644]
vimhandler/template/vim_create.html
vimhandler/template/vim_list.html
vimhandler/template/vim_show.html
vimhandler/views.py

index c7fde75..05723b0 100644 (file)
--- a/.bowerrc
+++ b/.bowerrc
@@ -1,3 +1,4 @@
 {
-"directory": "static/bower_components"
+ "directory": "static/bower_components",
+  "registry": "https://registry.bower.io"
 }
index 4bf9e72..6c23e91 100644 (file)
 #   See the License for the specific language governing permissions and
 #   limitations under the License.
 #
+from django.core.exceptions import PermissionDenied
+
 from .models import OsmUser
 from lib.osm.osmclient.clientv2 import Client
+from .exceptions import OSMAuthException
 
 class OsmBackend(object):
 
@@ -26,27 +29,31 @@ class OsmBackend(object):
         if all(k in kwargs for k in ('username', 'password', 'project_id')):
             username = kwargs['username']
             password = kwargs['password']
-            project_id = kwargs['project_id']
 
             client = Client()
             result = client.auth(kwargs)
-            print "######"
-            print result
 
-            if 'error' in result and result['error'] == True:
-                return None
+            if 'error' in result and result['error'] is True:
+                raise OSMAuthException(result['data'])
             else:
 
                 try:
                     user = OsmUser.objects.get(username=username)
+                    user.psw = password
+                    user.token=result['data']['id']
+                    user.project_id=result['data']['project_id']
+                    user.token_expires=result['data']['expires']
+                    user.session = result['data']
+                    user.save()
 
                 except OsmUser.DoesNotExist:
-                    # Create a new user. There's no need to set a password
-                    # we will keep just some preferences
-                    user = OsmUser(username=username)
-
+                    user = OsmUser(username=username, psw=password, token=result['data']['id'],
+                                                       project_id=result['data']['project_id'],
+                                                       token_expires=result['data']['expires'])
+                    user.session = result['data']
                     user.save()
-                user.session = result['data']
+
+
                 return user
 
         return None
diff --git a/authosm/exceptions.py b/authosm/exceptions.py
new file mode 100644 (file)
index 0000000..c0b061d
--- /dev/null
@@ -0,0 +1,19 @@
+#
+#   Copyright 2018 EveryUP Srl
+#
+#   Licensed under the Apache License, Version 2.0 (the "License");
+#   you may not use this file except in compliance with the License.
+#   You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#   Unless required by applicable law or agreed to in writing, software
+#   distributed under the License is distributed on an  BASIS,
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#   See the License for the specific language governing permissions and
+#   limitations under the License.
+#
+
+
+class OSMAuthException(Exception):
+    pass
index c48f738..36a7b1b 100644 (file)
@@ -18,8 +18,10 @@ from django.db import models
 from django.utils.translation import ugettext_lazy as _
 from django.contrib.auth.models import User, AbstractBaseUser, BaseUserManager, PermissionsMixin
 from django.utils import timezone
-from lib.osm.osmclient.client import Client
-import uuid
+
+from authosm.exceptions import OSMAuthException
+from lib.osm.osmclient.clientv2 import Client
+import utils
 
 
 class OsmUserManager(BaseUserManager):
@@ -58,24 +60,54 @@ class AbstractOsmUser(AbstractBaseUser, PermissionsMixin):
         * is_superuser
 
     """
-    username = models.CharField(_('username'), max_length=255, unique=True, db_index=True)
-    current_project = models.CharField(_('project_id'), max_length=255)
-    token_project = models.CharField(_('token'), max_length=36)
+    username = models.CharField(_('username'), primary_key=True, max_length=255, unique=True, db_index=True)
+
     is_admin = models.BooleanField(_('admin status'), default=False)
     is_basic_user = models.BooleanField(_('basic_user status'), default=False)
+    current_project = models.CharField(_('project_id'), max_length=255)
+
+    psw = models.CharField(_('psw'), max_length=36)
+    token = models.CharField(_('token'), max_length=36)
+    project_id = models.CharField(_('project_id'), max_length=36)
+    token_expires = models.FloatField(_('token_expires'), max_length=36)
 
     objects = OsmUserManager()
 
     USERNAME_FIELD = 'username'
     REQUIRED_FIELDS = []
 
+    @property
+    def is_authenticated(self):
+        """Checks for a valid authentication."""
+        if self.token is not None and utils.is_token_valid({'expires': self.token_expires}):
+            return True
+        else:
+            return False
+
+    def get_token(self):
+        if self.is_authenticated:
+            return {'id': self.token, 'expires': self.token_expires, 'project_id': self.project_id}
+        return None
+
+    def switch_project(self, project_id):
+        client = Client()
+        result = client.switch_project({'project_id': project_id, 'username': self.username, 'password': self.psw})
+        if 'error' in result and result['error'] is True:
+            raise OSMAuthException(result['data'])
+        else:
+            self.token = result['data']['id']
+            self.project_id = result['data']['project_id']
+            self.token_expires = result['data']['expires']
+            self.save()
+            return True
+        return False
+
     class Meta:
         verbose_name = _('custom user')
         verbose_name_plural = _('custom users')
         abstract = True
 
 
-
 class OsmUser(AbstractOsmUser):
     """
         Concrete class of AbstractCustomUser.
@@ -87,6 +119,3 @@ class OsmUser(AbstractOsmUser):
     class Meta(AbstractOsmUser.Meta):
         swappable = 'AUTH_USER_MODEL'
 
-    def get_projects(self):
-        client = Client()
-        return []
diff --git a/authosm/utils.py b/authosm/utils.py
new file mode 100644 (file)
index 0000000..c1a5d50
--- /dev/null
@@ -0,0 +1,33 @@
+#
+#   Copyright 2018 EveryUP Srl
+#
+#   Licensed under the Apache License, Version 2.0 (the "License");
+#   you may not use this file except in compliance with the License.
+#   You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#   Unless required by applicable law or agreed to in writing, software
+#   distributed under the License is distributed on an  BASIS,
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#   See the License for the specific language governing permissions and
+#   limitations under the License.
+#
+
+import time
+import authosm.models
+
+
+def get_user(request):
+    user = authosm.models.OsmUser.objects.get(username=request.session['_auth_user_id'])
+    return user
+
+
+def is_token_valid(token):
+
+    expiration = token['expires'] if 'expires' in token \
+                                     and isinstance(token['expires'], (int, long, float, complex)) else None
+    if expiration is None:
+        return False
+
+    return expiration > time.time()
index 5ce8765..65b1ed6 100644 (file)
@@ -30,14 +30,20 @@ def user_login(request):
         print request.POST.get('password')
         next_page = request.POST.get('next')
         next_page = urllib.unquote(next_page).decode('iso-8859-2')
-        user = authenticate(username=request.POST.get('username'),
-                            password=request.POST.get('password'),
-                            project_id=request.POST.get('project_id'))
+        try:
+            user = authenticate(username=request.POST.get('username'),
+                                password=request.POST.get('password'),
+                                project_id=request.POST.get('project_id'))
+        except Exception as e:
+            print e
+            res = HttpResponseRedirect('/auth')
+            res.set_cookie('logout_reason', '', max_age=10)
+            return res
+
         if user and user.is_active:
-            if user.is_authenticated():
+            if user.is_authenticated:
                 login(request, user)
                 request.session['token'] = user.session
-                print request.session['token']
                 if next_page == "" or next_page is None:
                     return HttpResponseRedirect('/home')
                 else:
index d651b65..20c60cb 100644 (file)
@@ -21,7 +21,7 @@
   "dependencies": {
     "admin-lte": "^2.4.3",
     "codemirror": "^5.36.0",
-    "d3": "^5.1.0",
+    "d3": "^4",
     "bootbox.js": "bootbox#^4.4.0",
     "components-font-awesome": "^5.0.6"
   }
index 9baae4c..5888519 100644 (file)
@@ -25,7 +25,7 @@
 
 {% block breadcrumb_body %}
     {{ block.super }}
-    <li><a href="{% url 'projects:instances:list' project_id=project_id type=type %}">{{ type|upper }} Instances</a></li>
+    <li><a href="{% url 'projects:instances:list'  type=type %}">{{ type|upper }} Instances</a></li>
 {% endblock %}
 
 {% block content_body %}
index dd84d47..2da870d 100644 (file)
@@ -7,7 +7,7 @@
 
             <button type="button" class="btn btn-default" data-container="body"
                     data-toggle="tooltip" data-placement="top" title="Instantiate NS"
-                    onclick="javascript:openModalCreateNS({ 'project_id':'{{ project_id }}','vim_list_url': '{% url "projects:vims:list" project_id=project_id %}', 'nsd_list_url': '{% url "projects:list_descriptors" project_id=project_id descriptor_type='nsd' %}'})">
+                    onclick="javascript:openModalCreateNS({ 'project_id':'{{ project_id }}','vim_list_url': '{% url "projects:vims:list"  %}', 'nsd_list_url': '{% url "projects:list_descriptors" descriptor_type='nsd' %}'})">
                 <i class="fa fa-paper-plane"></i> <span> New NS</span></button>
 
         </div>
                     <td>
                         <div class="btn-group">
                             <button type="button" class="btn btn-default"
-                                    onclick="javascript:showInstanceDetails('{% url 'projects:instances:show' instance_id=i|get:'_id' project_id=project_id type=type %}')"
+                                    onclick="javascript:showInstanceDetails('{% url 'projects:instances:show' instance_id=i|get:'_id'  type=type %}')"
                                     data-toggle="tooltip" data-placement="top" data-container="body" title="Show Info">
-                                <i
-                                        class="fa fa-info"></i>
+                                <i class="fa fa-info"></i>
                             </button>
+                            <!--
+                            <button type="button" class="btn btn-default"
+                                    onclick="javascript:showInstanceTopology('{% url 'projects:instances:show_topology' instance_id=i|get:'_id'  type=type %}')"
+                                    data-toggle="tooltip" data-placement="top" data-container="body" title="Show Topology">
+                                <i class="fa fa-sitemap"></i>
+                            </button>
+                            -->
 
                             <button type="button" class="btn btn-default"
-                                    onclick="javascript:deleteNs('{% url 'projects:instances:delete' instance_id=i|get:'_id' project_id=project_id type=type %}')"
+                                    onclick="javascript:deleteNs('{% url 'projects:instances:delete' instance_id=i|get:'_id'  type=type %}')"
                                     data-toggle="tooltip" data-placement="top" data-container="body" title="Delete"><i
                                     class="far fa-trash-alt"></i></button>
 
                                 <span class="fa fa-caret-down"></span></button>
                             <ul class="dropdown-menu">
                                 <li><a href="#"
-                                       onclick="javascript:performAction('{% url 'projects:instances:action' instance_id=i|get:'_id' project_id=project_id type=type %}')">
+                                       onclick="javascript:performAction('{% url 'projects:instances:action' instance_id=i|get:'_id'  type=type %}')">
                                     <i class="fa fa-magic"></i> Exec NS Primitive</a></li>
                                 <li>
-                                    <a href="{% url 'projects:instances:ns_operations' project_id=project_id type=type instance_id=i|get:'_id' %}">
+                                    <a href="{% url 'projects:instances:ns_operations'  type=type instance_id=i|get:'_id' %}">
                                         <i class="fa fa-list"></i> Active operations</a></li>
                                 <li class="divider"></li>
                                 <li><a href="#"
-                                       onclick="javascript:newAlarmNs('{% url 'projects:instances:ns_create_alarm' instance_id=i|get:'_id' project_id=project_id type=type %}')">
+                                       onclick="javascript:newAlarmNs('{% url 'projects:instances:ns_create_alarm' instance_id=i|get:'_id'  type=type %}')">
                                     <i class="far fa-bell"></i> New Alarm</a></li>
                                 <li><a href="#"
-                                       onclick="javascript:exportMetricNs('{% url 'projects:instances:ns_export_metric' instance_id=i|get:'_id' project_id=project_id type=type %}')">
+                                       onclick="javascript:exportMetricNs('{% url 'projects:instances:ns_export_metric' instance_id=i|get:'_id'  type=type %}')">
                                     <i class="far fa-chart-bar"></i> Export metric</a></li>
                                 <li class="divider"></li>
                                 <li>
-                                    <a href="javascript:deleteNs('{% url 'projects:instances:delete' instance_id=i|get:'_id' project_id=project_id type=type %}', true)">
+                                    <a href="javascript:deleteNs('{% url 'projects:instances:delete' instance_id=i|get:'_id'  type=type %}', true)">
                                         <i class="far fa-trash-alt" style="color:red" ></i> Force delete</a></li>
                             </ul>
 
index 4aa084e..410fcb0 100644 (file)
@@ -29,7 +29,7 @@
                 <tr>
 
                     <td>{{ i|get:"_id" }}</td>
-                    <td><a href="javascript:openDescriptorView('{{project_id}}', 'vnfd', '{{ i|get:"vnfd-id" }}')"> {{ i|get:"vnfd-ref" }}</a></td>
+                    <td><a href="javascript:openDescriptorView('vnfd', '{{ i|get:"vnfd-id" }}')"> {{ i|get:"vnfd-ref" }}</a></td>
                     <td>{{ i|get:"member-vnf-index-ref" }}</td>
                     <td class="ellipsis" data-text="{{ i|get:"nsr-id-ref" }}">{{ i|get:"nsr-id-ref" }}</td>
                     <td >{{ i|get:"created-time"|get_date }}</td>
@@ -37,7 +37,7 @@
                     <td>
                         <div class="btn-group">
                             <button type="button" class="btn btn-default"
-                                    onclick="javascript:showInstanceDetails('{% url 'projects:instances:show' instance_id=i|get:'_id' project_id=project_id type=type %}')"
+                                    onclick="javascript:showInstanceDetails('{% url 'projects:instances:show' instance_id=i|get:'_id'  type=type %}')"
                                     data-toggle="tooltip" data-placement="top" data-container="body" title="Show Info">
                                 <i class="fa fa-info"></i>
                             </button>
index 4115e0d..e72b56c 100644 (file)
@@ -25,7 +25,7 @@
 
 {% block breadcrumb_body %}
     {{ block.super }}
-    <li><a href="{% url 'projects:instances:list' project_id=project_id type=type %}">Instances</a></li>
+    <li><a href="{% url 'projects:instances:list'  type=type %}">Instances</a></li>
 {% endblock %}
 
 {% block content_body %}
@@ -74,7 +74,7 @@
                                 <td>
                                     <div class="btn-group">
                                         <button type="button" class="btn btn-default"
-                                                onclick="javascript:showOperationDetails('{% url 'projects:instances:ns_operation' op_id=i|get:'_id' instance_id=i|get:'nsInstanceId' project_id=project_id type=type %}')"
+                                                onclick="javascript:showOperationDetails('{% url 'projects:instances:ns_operation' op_id=i|get:'_id' instance_id=i|get:'nsInstanceId'  type=type %}')"
                                                 data-toggle="tooltip" data-placement="top" data-container="body" title="More Info"><i
                                                 class="fa fa-info"></i>
                                         </button>
diff --git a/instancehandler/template/instance_topology_view.html b/instancehandler/template/instance_topology_view.html
new file mode 100644 (file)
index 0000000..627770d
--- /dev/null
@@ -0,0 +1,79 @@
+{% extends "base.html" %}
+{% load get %}
+{% load staticfiles %}
+
+
+
+{% block head_block %}
+    {{ block.super }}
+    <link rel="stylesheet" href="/static/bower_components/select2/dist/css/select2.min.css">
+    <link rel="stylesheet" href="/static/css/lwuitable.css">
+
+    <!-- Topology3D core CSS -->
+    <link rel="stylesheet" href="/static/topology3D/css/graph_editor_d3js.css">
+    <link rel="stylesheet" href="/static/topology3D/css/d3-context-menu.css">
+
+{% endblock %}
+{% block title_header_big %}
+    {{ block.super }}
+{% endblock %}
+{% block left_sidebar %}
+    {% include 'osm/osm_project_left_sidebar.html' %}
+{% endblock %}
+
+
+{% block breadcrumb_body %}
+    {{ block.super }}
+    <li><a href="{% url 'projects:instances:list'  type=type %}">{{ type|upper }} Instances</a></li>
+    <li><a href="#"><i class="fa fa-sitemap"></i> {{ type|upper }} Topology</a></li>
+{% endblock %}
+
+{% block content_body %}
+    {{ block.super }}
+    {% csrf_token %}
+
+    <div class="row" >
+        <div class="col-md-12">
+            {% block topology_toolbar %}
+                {{ block.super }}
+                 {% include 'topology_toolbar_instance.html' %}
+            {% endblock %}
+            <div id="graph_ed_container" style="width: 100%; height:100%; background-color: white; border: 2px #3c8dbc solid;">
+
+            </div>
+        </div>
+    </div>
+
+
+
+{% endblock %}
+
+{% block resource_block %}
+    {{ block.super }}
+    <script>
+        var topology_data = {};//{{topology_data|safe }};
+    </script>
+    <!-- Utility JS -->
+    <script src="/static/bower_components/select2/dist/js/select2.js"></script>
+
+    <!-- d3.js -->
+    <script src="https://d3js.org/d3.v4.js"></script>
+<!--
+    <script src="/static/bower_components/d3/d3.js"></script>-->
+
+    <!-- topology3D -->
+    <script src="/static/topology3D/js/d3-context-menu.js"></script>
+    <script src="/static/topology3D/js/event.js"></script>
+    <script src="/static/topology3D/js/graph_editor.js"></script>
+    <script src="/static/topology3D/js/graph_request.js"></script>
+    <script src="/static/topology3D/js/model_graph_editor.js"></script>
+
+
+    <script src="/static/src/osm_gui_properties.js"></script>
+    <script src="/static/src/instancehandler/instance_topology_view.js"></script>
+
+{% endblock %}
+
+{% block footer %}
+    {% include "footer.html" %}
+{% endblock %}
index f1c24d9..384e782 100644 (file)
@@ -6,7 +6,7 @@
                     <span aria-hidden="true">×</span></button>
                 <h4 class="modal-title">New Instance</h4>
             </div>
-            <form id="formCreateNS" action='{% url "projects:instances:create"  project_id=project_id %}'
+            <form id="formCreateNS" action='{% url "projects:instances:create"   %}'
                   class="form-horizontal"
                   method="post" enctype="multipart/form-data">
                 {% csrf_token %}
index 054c3ba..d097b60 100644 (file)
@@ -21,6 +21,7 @@ urlpatterns = [
     url(r'^(?P<type>[ns|vnf]+)/list/', views.list, name='list'),
     url(r'^create/', views.create, name='create'),
     url(r'^(?P<type>[ns|vnf]+)/(?P<instance_id>[0-9a-z-]+)/delete$', views.delete, name='delete'),
+    url(r'^(?P<type>[ns|vnf]+)/(?P<instance_id>[0-9a-z-]+)/topology', views.show_topology, name='show_topology'),
     url(r'^(?P<type>[ns|vnf]+)/(?P<instance_id>[0-9a-z-]+)/action$', views.action, name='action'),
     url(r'^(?P<type>[ns|vnf]+)/(?P<instance_id>[0-9a-z-]+)/operation$', views.ns_operations, name='ns_operations'),
     url(r'^(?P<type>[ns|vnf]+)/(?P<instance_id>[0-9a-z-]+)/operation/(?P<op_id>[0-9a-z-]+)', views.ns_operation, name='ns_operation'),
index 39837d7..2148b7b 100644 (file)
@@ -21,18 +21,20 @@ import yaml
 import json
 import logging
 from lib.osm.osmclient.clientv2 import Client
+import authosm.utils as osmutils
 
 logging.basicConfig(level=logging.DEBUG)
 log = logging.getLogger('instancehandler/view.py')
 
-
 @login_required
-def list(request, project_id=None, type=None):
+def list(request, type=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     client = Client()
     if type == 'ns':
-        instance_list = client.ns_list(request.session['token'])
+        instance_list = client.ns_list(user.get_token())
     elif type == 'vnf':
-        instance_list = client.vnf_list(request.session['token'])
+        instance_list = client.vnf_list(user.get_token())
 
     result = {'instances': instance_list['data'] if instance_list and instance_list['error'] is False else [],
               'type': type, 'project_id': project_id}
@@ -41,7 +43,7 @@ def list(request, project_id=None, type=None):
 
 
 @login_required
-def create(request, project_id=None):
+def create(request):
     result = {}
     ns_data = {
         "nsName": request.POST.get('nsName', 'WithoutName'),
@@ -73,32 +75,36 @@ def create(request, project_id=None):
 
                 ns_data["vnf"] = ns_config["vnf"]
     print ns_data
+    user = osmutils.get_user(request)
     client = Client()
-    result = client.ns_create(request.session['token'], ns_data)
+    result = client.ns_create(user.get_token(), ns_data)
     return __response_handler(request, result, 'projects:instances:list', to_redirect=True, type='ns',
-                              project_id=project_id)
+                              )
 
 
 @login_required
-def ns_operations(request, project_id=None, instance_id=None, type=None):
+def ns_operations(request, instance_id=None, type=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     client = Client()
-    op_list = client.ns_op_list(request.session['token'], instance_id)
+    op_list = client.ns_op_list(user.get_token(), instance_id)
     return __response_handler(request,
                               {'operations': op_list['data'] if op_list and op_list['error'] is False else [],
                                'type': 'ns', 'project_id': project_id}, 'instance_operations_list.html')
 
 
 @login_required
-def ns_operation(request, op_id, project_id=None, instance_id=None, type=None):
+def ns_operation(request, op_id, instance_id=None, type=None):
+    user = osmutils.get_user(request)
     client = Client()
-    result = client.ns_op(request.session['token'], op_id)
+    result = client.ns_op(user.get_token(), op_id)
     return __response_handler(request, result['data'])
 
 
 @login_required
-def action(request, project_id=None, instance_id=None, type=None):
+def action(request, instance_id=None, type=None):
+    user = osmutils.get_user(request)
     client = Client()
-
     # result = client.ns_action(instance_id, action_payload)
     primitive_param_keys = request.POST.getlist('primitive_params_name')
     primitive_param_value = request.POST.getlist('primitive_params_value')
@@ -108,7 +114,7 @@ def action(request, project_id=None, instance_id=None, type=None):
         "primitive_params": {k: v for k, v in zip(primitive_param_keys, primitive_param_value) if len(k) > 0}
     }
 
-    result = client.ns_action(request.session['token'], instance_id, action_payload)
+    result = client.ns_action(user.get_token(), instance_id, action_payload)
     print result
     if result['error']:
         return __response_handler(request, result['data'], url=None,
@@ -119,32 +125,191 @@ def action(request, project_id=None, instance_id=None, type=None):
 
 
 @login_required
-def delete(request, project_id=None, instance_id=None, type=None):
+def delete(request, instance_id=None, type=None):
     force = bool(request.GET.get('force', False))
     result = {}
+    user = osmutils.get_user(request)
     client = Client()
-    result = client.ns_delete(request.session['token'], instance_id, force)
+    result = client.ns_delete(user.get_token(), instance_id, force)
     print result
     return __response_handler(request, result, 'projects:instances:list', to_redirect=True, type='ns',
-                              project_id=project_id)
+                              )
+
+
+def show_topology(request, instance_id=None, type=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
+    if 'application/json' in raw_content_types:
+        result = {'vertices': [
+            {"info": {"type": "vnf", "property": {"custom_label": ""},
+                      "group": []}, "id": "ping"},
+            {"info": {"type": "vnf", "property": {"custom_label": ""},
+                      "group": []}, "id": "pong"},
+            {"info": {"type": "vdu", "property": {"custom_label": ""},
+                      "group": ['pong']}, "id": "pong/ubuntu"},
+            {"info": {"type": "vdu", "property": {"custom_label": ""},
+                      "group": ['ping']}, "id": "ping/ubuntu"},
+            {"info": {"type": "cp", "property": {"custom_label": ""},
+                      "group": ['ping']}, "id": "ping/cp0"},
+            {"info": {"type": "cp", "property": {"custom_label": ""},
+                      "group": ['ping']}, "id": "ping/cp1"},
+            {"info": {"type": "cp", "property": {"custom_label": ""},
+                      "group": ['pong']}, "id": "pong/cp0"},
+            {"info": {"type": "cp", "property": {"custom_label": ""},
+                      "group": ['pong']}, "id": "pong/cp1"},
+            {"info": {"type": "ns_vl", "property": {"custom_label": ""},
+                      "group": []}, "id": "mgmt_vl"},
+        ],
+            'edges': [
+                # {"source": "ping", "group": [], "target": "ping/cp0", "view": "Data"},
+                {"source": "pong/ubuntu", "group": ['pong'], "target": "pong/cp0", "view": "vnf"},
+                {"source": "ping/ubuntu", "group": ['ping'], "target": "ping/cp0", "view": "vnf"},
+                {"source": "pong/ubuntu", "group": ['pong'], "target": "pong/cp1", "view": "vnf"},
+                {"source": "ping/ubuntu", "group": ['ping'], "target": "ping/cp1", "view": "vnf"},
+                {"source": "pong", "group": [], "target": "mgmt_vl", "view": "ns"},
+                {"source": "ping", "group": [], "target": "mgmt_vl", "view": "ns"},
+            ], 'graph_parameters': [],
+            'model': {
+                "layer": {
+
+                    "ns": {
+                        "nodes": {
+                            "vnf": {
+                                "addable": {
+                                    "callback": "addNode"
+                                },
+                                "removable": {
+                                    "callback": "removeNode"
+                                },
+                                "expands": "vnf"
+                            },
+                            "ns_vl": {
+                                "addable": {
+                                    "callback": "addNode"
+                                },
+                                "removable": {
+                                    "callback": "removeNode"
+                                }
+                            },
+
+                        },
+                        "allowed_edges": {
+                            "ns_vl": {
+                                "destination": {
+                                    "vnf": {
+                                        "callback": "addLink",
+                                        "direct_edge": False,
+                                        "removable": {
+                                            "callback": "removeLink"
+                                        }
+                                    }
+                                }
+                            },
+                            "vnf": {
+                                "destination": {
+                                    "ns_vl": {
+                                        "callback": "addLink",
+                                        "direct_edge": False,
+                                        "removable": {
+                                            "callback": "removeLink"
+                                        }
+                                    },
+
+                                }
+                            }
+
+                        }
+                    },
+                    "vnf": {
+                        "nodes": {
+                            "vdu": {
+                                "addable": {
+                                    "callback": "addNode"
+                                },
+                                "removable": {
+                                    "callback": "removeNode"
+                                }
+                            },
+                            "cp": {
+                                "addable": {
+                                    "callback": "addNode"
+                                },
+                                "removable": {
+                                    "callback": "removeNode"
+                                }
+                            },
+
+                        },
+                        "allowed_edges": {
+                            "vdu": {
+                                "destination": {
+                                    "cp": {
+                                        "callback": "addLink",
+                                        "direct_edge": False,
+                                        "removable": {
+                                            "callback": "removeLink"
+                                        }
+                                    }
+                                }
+                            },
+                            "cp": {
+                                "destination": {
+                                    "vdu": {
+                                        "callback": "addLink",
+                                        "direct_edge": False,
+                                        "removable": {
+                                            "callback": "removeLink"
+                                        }
+                                    }
+                                }
+                            }
+                        }
+                    },
+                    "name": "OSM",
+                    "version": 1,
+                    "nodes": {
+                        "vnf": {
+                            "label": "vnf"
+                        },
+                        "ns_vl": {
+                            "label": "vl"
+                        },
+                        "cp": {
+                            "label": "cp"
+                        },
+                        "vdu": {
+                            "label": "vdu"
+                        }
+                    },
+                    "description": "osm"
+                }
+            }}
+        return __response_handler(request, result)
+    else:
+        result = {'type': type, 'project_id': project_id, 'instance_id': instance_id}
+        return __response_handler(request, result, 'instance_topology_view.html')
 
 
 @login_required
-def show(request, project_id=None, instance_id=None, type=None):
+def show(request, instance_id=None, type=None):
     # result = {}
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     client = Client()
     if type == 'ns':
-        result = client.ns_get(request.session['token'], instance_id)
+        result = client.ns_get(user.get_token(), instance_id)
     elif type == 'vnf':
-        result = client.vnf_get(request.session['token'], instance_id)
+        result = client.vnf_get(user.get_token(), instance_id)
     print result
     return __response_handler(request, result)
 
 
 @login_required
-def export_metric(request, project_id=None, instance_id=None, type=None):
+def export_metric(request, instance_id=None, type=None):
     metric_data = request.POST.dict()
-
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     client = Client()
     keys = ["collection_period",
             "vnf_member_index",
@@ -154,7 +319,7 @@ def export_metric(request, project_id=None, instance_id=None, type=None):
             "collection_unit"]
     metric_data = dict(filter(lambda i: i[0] in keys and len(i[1]) > 0, metric_data.items()))
 
-    result = client.ns_metric_export(request.session['token'], instance_id, metric_data)
+    result = client.ns_metric_export(user.get_token(), instance_id, metric_data)
 
     if result['error']:
         print result
@@ -165,9 +330,11 @@ def export_metric(request, project_id=None, instance_id=None, type=None):
 
 
 @login_required
-def create_alarm(request, project_id=None, instance_id=None, type=None):
+def create_alarm(request, instance_id=None, type=None):
     metric_data = request.POST.dict()
     print metric_data
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     client = Client()
 
     keys = ["threshold_value",
@@ -181,7 +348,7 @@ def create_alarm(request, project_id=None, instance_id=None, type=None):
             "severity"]
     metric_data = dict(filter(lambda i: i[0] in keys and len(i[1]) > 0, metric_data.items()))
 
-    result = client.ns_alarm_create(request.session['token'], instance_id, metric_data)
+    result = client.ns_alarm_create(user.get_token(), instance_id, metric_data)
     if result['error']:
         print result
         return __response_handler(request, result['data'], url=None,
index 9acb590..6555071 100644 (file)
@@ -28,7 +28,23 @@ class Client(object):
         try:
             r = requests.post(token_url, json=args, verify=False, headers=headers)
         except Exception as e:
-            print "saltata"
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code == requests.codes.ok:
+            result['error'] = False
+
+        result['data'] = Util.json_loads_byteified(r.text)
+
+        return result
+
+    def switch_project(self, args):
+        result = {'error': True, 'data': ''}
+        token_url = "{0}/{1}".format(self._base_path, self._token_endpoint)
+        headers = {"Content-Type": "application/yaml", "accept": "application/json"}
+        try:
+            r = requests.post(token_url, json=args, verify=False, headers=headers)
+        except Exception as e:
             log.exception(e)
             result['data'] = str(e)
             return result
diff --git a/projecthandler/middleware.py b/projecthandler/middleware.py
new file mode 100644 (file)
index 0000000..4880ebe
--- /dev/null
@@ -0,0 +1,6 @@
+
+class OsmProjectMiddleware(object):
+    def process_view(self, request, view_func, view_args, view_kwargs):
+        print "OsmProjectMiddleware", view_func, view_args, view_kwargs
+
+        return None
\ No newline at end of file
index 3635d66..e97649d 100644 (file)
 
 
         function goToGraph() {
-            window.location.href = '/projects/{{project_id}}/graph?type={{descriptor_type}}&id={{descriptor_id}}'
+            window.location.href = '/projects/graph?type={{descriptor_type}}&id={{descriptor_id}}'
         }
     </script>
 {% endblock %}
index 799026b..7711b57 100644 (file)
@@ -14,8 +14,8 @@ Onboard new {{ descriptor_type }} package
 
 {% block breadcrumb_body %}
 {{ block.super }}
-<li><a href="{% url 'projects:open_project' project_id=project_id %}">{{project_id}}</a></li>
-<li><a href="{% url 'projects:open_project' project_id=project_id %}descriptors/{{descriptor_type}}">{{ descriptor_type }}  Descriptors</a></li>
+<li><a href="{% url 'projects:open_project'  %}">{{project_id}}</a></li>
+<li><a href="{% url 'projects:open_project'  %}descriptors/{{descriptor_type}}">{{ descriptor_type }}  Descriptors</a></li>
 <li>Create Descriptor</li>
 {% endblock %}
 
@@ -50,9 +50,9 @@ Onboard new {{ descriptor_type }} package
 {{ block.super }}
 
 <script>
-    var descr_list_url = '{% url "projects:list_descriptors"  project_id=project_id descriptor_type=descriptor_type%}';
+    var descr_list_url = '{% url "projects:list_descriptors"   descriptor_type=descriptor_type%}';
     var csrf_token = '{{csrf_token}}';
-    var new_desc_url ="{% url 'projects:new_descriptor' project_id=project_id descriptor_type=descriptor_type %}"
+    var new_desc_url ="{% url 'projects:new_descriptor'  descriptor_type=descriptor_type %}"
 
     function cancel(id) {
         window.location.href = descr_list_url
index fe2d78c..3272f44 100644 (file)
@@ -15,8 +15,8 @@ Edit {{ descriptor_type|upper }} Descriptor
 
 {% block breadcrumb_body %}
 {{ block.super }}
-<li><a href="{% url 'projects:open_project' project_id=project_id %}">{{project_id}}</a></li>
-<li><a href="{% url 'projects:open_project' project_id=project_id %}descriptors/{{descriptor_type}}">{{ descriptor_type }} Descriptors</a></li>
+<li><a href="{% url 'projects:open_project' %}">{{project_id}}</a></li>
+<li><a href="{% url 'projects:open_project' %}descriptors/{{descriptor_type}}">{{ descriptor_type }} Descriptors</a></li>
 <li><a>{{descriptor_id}}</a></li>
 {% endblock %}
 
@@ -97,7 +97,7 @@ Edit {{ descriptor_type|upper }} Descriptor
                 break;
         }
         $.ajax({
-            url: "/projects/{{project_id}}/descriptors/{{descriptor_type}}/{{descriptor_id}}/",
+            url: "/projects/descriptors/{{descriptor_type}}/{{descriptor_id}}/",
             type: 'POST',
             dataType: 'json',
             data: {
index 002cd57..c995844 100644 (file)
@@ -7,10 +7,13 @@
             <h3 class="box-title">
             </h3>
             <div class="box-tools">
-
-                <a href="{% url 'projects:new_descriptor' project_id=project_id descriptor_type=descriptor_type %}"
+                <div class="btn-group">
+                    <!--
+                <a href="{% url 'projects:open_composer'%}"
                    class="btn btn-block btn-primary btn-sm"><i
-                        class="fa fa-upload"></i><span> Onboard {{ descriptor_type|upper }}</span></a>
+                        class="fa fa-paint-brush" disabled></i><span> Composer</span></a>
+                        -->
+                </div>
             </div>
         </div>
         <div class="box-body">
                                 {% if descriptor_type == "nsd" %}
                                     <button type="button" class="btn btn-default" data-container="body"
                                             data-toggle="tooltip" data-placement="top" title="Instantiate NS"
-                                            onclick="javascript:openModalCreateNS({ 'project_id':'{{ project_id }}', 'descriptor_type': '{{ descriptor_type }}', 'descriptor_name':'{{ k|get:"name" }}', 'descriptor_id':'{{ k|get:"_id" }}','vim_list_url': '{% url "projects:vims:list" project_id=project_id %}',  'nsd_list_url': '{% url "projects:list_descriptors" project_id=project_id descriptor_type=descriptor_type %}' })">
+                                            onclick="javascript:openModalCreateNS({ 'project_id':'{{ project_id }}', 'descriptor_type': '{{ descriptor_type }}', 'descriptor_name':'{{ k|get:"name" }}', 'descriptor_id':'{{ k|get:"_id" }}','vim_list_url': '{% url "projects:vims:list"  %}',  'nsd_list_url': '{% url "projects:list_descriptors"  descriptor_type=descriptor_type %}' })">
                                         <i class="fa fa-paper-plane"></i></button>
                                 {% endif %}
                                 <button type="button" class="btn btn-default" data-container="body"
                                         data-toggle="tooltip" data-placement="top" title="Edit"
-                                        onclick="javascript:openDescriptorView('{{ project_id }}', '{{ descriptor_type }}', '{{ k|get:"_id" }}')">
+                                        onclick="javascript:openDescriptorView('{{ descriptor_type }}', '{{ k|get:"_id" }}')">
                                     <i class="fa fa-edit"></i></button>
                                 <button type="button" class="btn btn-default" data-container="body"
                                         data-toggle="tooltip" data-placement="top" title="Show content"
-                                        onclick="javascript:openPackageContentList('{{ project_id }}', '{{ descriptor_type }}', '{{ k|get:"_id" }}')">
+                                        onclick="javascript:openPackageContentList('{{ descriptor_type }}', '{{ k|get:"_id" }}')">
                                     <i class="fa fa-folder-open"></i></button>
                                 <button type="button" class="btn btn-default" data-container="body"
                                         data-toggle="tooltip" data-placement="top" title="Show Graph"
-                                        onclick="location.href='/projects/{{ project_id }}/graph?type={{ descriptor_type }}&id={{ k|get:"_id" }}'"
+                                        onclick="location.href='/projects/graph?type={{ descriptor_type }}&id={{ k|get:"_id" }}'"
                                         disabled><i class="fa fa-sitemap fa-fw"></i></button>
                                 <button type="button" class="btn btn-default" data-container="body"
                                         data-toggle="tooltip" data-placement="top" title="Download package"
-                                        onclick="location.href='{% url 'projects:custom_action' project_id=project_id descriptor_type=descriptor_type descriptor_id=k|get:'_id' action_name='download_pkg' %}'">
+                                        onclick="location.href='{% url 'projects:custom_action'  descriptor_type=descriptor_type descriptor_id=k|get:'_id' action_name='download_pkg' %}'">
                                     <i class="fa fa-download fa-fw"></i></button>
                                 <button type="button" class="btn btn-default" data-container="body"
                                         data-toggle="tooltip" data-placement="top" title="Delete"
-                                        onclick="javascript:deletePackage('{{ project_id }}', '{{ descriptor_type }}', '{{ k|get:"_id" }}')">
+                                        onclick="javascript:deletePackage( '{{ descriptor_type }}', '{{ k|get:"_id" }}')">
                                     <i class="far fa-trash-alt"></i></button>
                             </div>
 
index 99b6111..10df788 100644 (file)
@@ -22,7 +22,7 @@
 
 {% block breadcrumb_body %}
        {{ block.super }}
-    <li><a href="{% url 'projects:open_project' project_id=project_id %}">{{project_id}}</a></li>
+    <li><a href="{% url 'projects:open_project' %}">{{project_id}}</a></li>
     <li><a> {% if descriptor_type  %}
      {{ descriptor_type }}
   {% else%}
@@ -47,8 +47,8 @@
        {{ block.super }}
     <script>
     var csrf_token = '{{csrf_token}}';
-    var descr_list_url = '{% url "projects:list_descriptors"  project_id=project_id descriptor_type=descriptor_type%}';
-    var new_desc_url ="{% url 'projects:new_descriptor' project_id=project_id descriptor_type=descriptor_type %}"
+    var descr_list_url = '{% url "projects:list_descriptors"   descriptor_type=descriptor_type%}';
+    var new_desc_url ="{% url 'projects:new_descriptor'  descriptor_type=descriptor_type %}"
     </script>
     <script src="/static/bower_components/select2/dist/js/select2.js"></script>
     <script src="/static/src/instancehandler/instance_create.js"></script>
index ed3e0fa..b0a1203 100644 (file)
@@ -44,7 +44,7 @@
                     <div class="inner"><h3>{{ project_overview.nsd }}</h3>
                         <p>NS packages</p></div>
                     <div class="icon"><i class="fa fa-archive"></i></div>
-                    <a href='{% url "projects:list_descriptors"  project_id=project_id descriptor_type="nsd" %}' class="small-box-footer">Open list <i
+                    <a href='{% url "projects:list_descriptors"   descriptor_type="nsd" %}' class="small-box-footer">Open list <i
                             class="fa fa-arrow-circle-right"></i></a></div>
             </div>
             <div class="col-md-6 ">
@@ -52,7 +52,7 @@
                     <div class="inner"><h3>{{ project_overview.vnfd }}</h3>
                         <p>VNF packages</p></div>
                     <div class="icon"><i class="fa fa-archive"></i></div>
-                    <a href='{% url "projects:list_descriptors"  project_id=project_id descriptor_type="vnfd" %}' class="small-box-footer">Open list <i
+                    <a href='{% url "projects:list_descriptors"   descriptor_type="vnfd" %}' class="small-box-footer">Open list <i
                             class="fa fa-arrow-circle-right"></i></a></div>
             </div>
         </div>
@@ -62,7 +62,7 @@
                     <div class="inner"><h3>{{ project_overview.ns }}</h3>
                         <p>NS Instances</p></div>
                     <div class="icon"><i class="fa fa-sitemap fa-fw"></i></div>
-                    <a href='{% url "projects:instances:list" project_id=project_id type="ns"  %}' class="small-box-footer">Open list <i
+                    <a href='{% url "projects:instances:list"  type="ns"  %}' class="small-box-footer">Open list <i
                             class="fa fa-arrow-circle-right"></i></a></div>
             </div>
 
@@ -71,7 +71,7 @@
                     <div class="inner"><h3>{{ project_overview.vnf }}</h3>
                         <p>VNF Instances</p></div>
                     <div class="icon"><i class="far fa-hdd fa-fw"></i></div>
-                    <a href='{% url "projects:instances:list" project_id=project_id type="vnf"  %}' class="small-box-footer">Open list <i
+                    <a href='{% url "projects:instances:list"  type="vnf"  %}' class="small-box-footer">Open list <i
                             class="fa fa-arrow-circle-right"></i></a></div>
             </div>
 
index 6399b11..b07c432 100644 (file)
@@ -8,14 +8,14 @@
             <li {% if request.get_full_path == home_url %} class="active" {% endif %} ><a href='{% url "home" %}'><i
                     class="fa fa-home fa-fw"></i> <span>Home</span></a></li>
             <li class="header">PROJECT</li>
-            {% url "projects:open_project"  project_id=project_id as  project_url %}
+            {% url "projects:open_project"  as  project_url %}
             <li {% if request.get_full_path == project_url %} class="active" {% endif %} >
-                <a href='{% url "projects:open_project"  project_id=project_id %}'>
+                <a href='{% url "projects:open_project" %}'>
                     <i class="fa fa-file-text fa-fw"></i> <span>Overview</span>
                 </a>
             </li>
-            {% url "projects:list_descriptors"  project_id=project_id descriptor_type="nsd" as  nsd_list_url %}
-            {% url "projects:list_descriptors"  project_id=project_id descriptor_type='vnfd' as  vnfd_list_url %}
+            {% url "projects:list_descriptors"   descriptor_type="nsd" as  nsd_list_url %}
+            {% url "projects:list_descriptors"   descriptor_type='vnfd' as  vnfd_list_url %}
             <li {% if request.get_full_path == nsd_list_url or  request.get_full_path == vnfd_list_url %}
                 class="active treeview menu-open" {% else %} class="treeview  menu-open" {% endif %} >
                 <a href="#">
@@ -38,8 +38,8 @@
 
                 </ul>
             </li>
-            {% url "projects:instances:list" project_id=project_id type='ns' as  instance_ns_list_url %}
-            {% url "projects:instances:list" project_id=project_id type='vnf' as  instance_vnf_list_url %}
+            {% url "projects:instances:list"  type='ns' as  instance_ns_list_url %}
+            {% url "projects:instances:list"  type='vnf' as  instance_vnf_list_url %}
             <li {% if request.get_full_path == instance_ns_list_url or  request.get_full_path == instance_vnf_list_url %}
                 class="active treeview menu-open" {% else %} class="treeview  menu-open" {% endif %} >
                 <a href="#">
                     </span>
                 </a>
                 <ul class="treeview-menu" style="display: block;">
-                    {% url "projects:instances:list" project_id=project_id type='ns' as  instance_ns_list_url %}
+                    {% url "projects:instances:list"  type='ns' as  instance_ns_list_url %}
                     <li {% if request.get_full_path == instance_ns_list_url %} class="active" {% endif %} >
-                        <a href='{% url "projects:instances:list" project_id=project_id  type="ns" %}'>
+                        <a href='{% url "projects:instances:list"   type="ns" %}'>
                             <i class="fa fa-sitemap fa-fw"></i> <span>NS Instances</span>
                         </a>
 
                     </li>
-                    {% url "projects:instances:list" project_id=project_id type='vnf' as  instance_vnf_list_url %}
+                    {% url "projects:instances:list"  type='vnf' as  instance_vnf_list_url %}
                     <li {% if request.get_full_path == instance_vnf_list_url %} class="active" {% endif %} >
-                        <a href='{% url "projects:instances:list" project_id=project_id  type="vnf" %}'>
+                        <a href='{% url "projects:instances:list"   type="vnf" %}'>
                             <i class="far fa-hdd fa-fw"></i> <span>VNF Instances</span>
                         </a>
                     </li>
                 </ul>
             </li>
 
-            {% url "projects:sdns:list"  project_id=project_id as sdn_list_url %}
+            {% url "projects:sdns:list"   as sdn_list_url %}
             <li {% if request.get_full_path == sdn_list_url %} class="active" {% endif %}>
-                <a href='{% url "projects:sdns:list"  project_id=project_id %}'>
+                <a href='{% url "projects:sdns:list"   %}'>
                     <i class="fas fa-globe fa-fw"></i> <span>SDN Controllers</span>
                 </a>
             </li>
 
-            {% url "projects:vims:list"  project_id=project_id as  vim_list_url %}
+            {% url "projects:vims:list"   as  vim_list_url %}
             <li {% if request.get_full_path == vim_list_url %} class="active" {% endif %}>
-                <a href='{% url "projects:vims:list"  project_id=project_id %}'>
+                <a href='{% url "projects:vims:list"   %}'>
                     <i class="fa fa-server fa-fw"></i> <span>VIM Accounts</span>
                 </a>
             </li>
index 432e1ff..4ae063e 100644 (file)
@@ -14,7 +14,7 @@
 {% block breadcrumb_body %}
        {{ block.super }}
     {% if project_id  %}
-    <li><a href="{% url 'projects:open_project' project_id=project_id %}">{{project_overview_data.name}}</a></li>
+    <li><a href="{% url 'projects:open_project' %}">{{project_overview_data.name}}</a></li>
     <li>Delete Project</li>
     {% endif %}
 {% endblock %}
index e944e0d..aac2983 100644 (file)
@@ -25,7 +25,7 @@
 {% block breadcrumb_body %}
        {{ block.super }}
     <li><a href="{% url 'projects:projects_list' %}">Projects</a></li>
-    <li><a href="{% url 'projects:open_project' project_id=project_id %}">{{project_overview.name}}</a></li>
+    <li><a href="{% url 'projects:open_project' %}">{{project_overview.name}}</a></li>
 {% endblock %}
 
 {% block content_body %}
index 7d344da..282afb4 100644 (file)
@@ -1,58 +1,81 @@
 {% extends "base.html" %}
-
+{% load get %}
 {% load staticfiles %}
 
+
+
 {% block head_block %}
-       {{ block.super }}
-       <link rel="stylesheet" href="{% static "topology3D/css/graph_editor_d3js.css" %}">
-       <link rel="stylesheet" href="{% static "topology3D/css/d3-context-menu.css" %}">
+    {{ block.super }}
+    <link rel="stylesheet" href="/static/bower_components/select2/dist/css/select2.min.css">
+    <link rel="stylesheet" href="/static/css/lwuitable.css">
+
+    <!-- Topology3D core CSS -->
+    <link rel="stylesheet" href="/static/topology3D/css/graph_editor_d3js.css">
+    <link rel="stylesheet" href="/static/topology3D/css/d3-context-menu.css">
+
 {% endblock %}
 {% block title_header_big %}
     {{ block.super }}
 {% endblock %}
 {% block left_sidebar %}
-
+    {% include 'osm/osm_project_left_sidebar.html' %}
 {% endblock %}
 
 
 {% block breadcrumb_body %}
-       {{ block.super }}
-    <li><a href="{% url 'projects:open_project' project_id=project_id %}">{{project_overview_data.name}}</a></li>
+    {{ block.super }}
+    <li><a href="#"><i class="fa fa-sitemap"></i> Composer</a></li>
 {% endblock %}
 
 {% block content_body %}
-       {{ block.super }}
- {% csrf_token %}
-<div class="row" >
-    <div class="col-md-12">
-        {% block topology_toolbar %}
-
-
-        {% endblock %}
-        <div id="graph_ed_container" style="width: 100%; height:100%; background-color: white; border: 2px #3c8dbc solid;">
-
+    {{ block.super }}
+    {% csrf_token %}
+    {% include 'osm/descriptor/modal/create_link_chooser.html' %}
+{% include 'osm/descriptor/modal/choose_node_id.html' %}
+{% include 'osm/modal/modal_keyboard_info.html' %}
+    <div class="row" >
+        <div class="col-md-12">
+            {% block topology_toolbar %}
+                {{ block.super }}
+                 {% include 'topology_toolbar.html' %}
+            {% endblock %}
+            <div id="graph_ed_container" style="width: 100%; height:100%; background-color: white; border: 2px #3c8dbc solid;">
+
+            </div>
         </div>
     </div>
-</div>
+
 
 
 {% endblock %}
 
 {% block resource_block %}
-       {{ block.super }}
+    {{ block.super }}
+    <script>
+        var topology_data = {};//{{topology_data|safe }};
+    </script>
+    <!-- Utility JS -->
+    <script src="/static/bower_components/select2/dist/js/select2.js"></script>
 
     <!-- d3.js -->
-    <script src="{% static "bower_components/d3/d3.min.js" %}" charset="utf-8"></script>
+    <script src="https://d3js.org/d3.v4.js"></script>
+<!--
+    <script src="/static/bower_components/d3/d3.js"></script>-->
 
     <!-- topology3D -->
-    <script src="{% static "topology3D/js/d3-context-menu.js" %}"></script>
-    <script src="{% static "topology3D/js/event.js" %}"></script>
-    <script src="{% static "topology3D/js/graph_editor.js" %}"></script>
-    <script src="{% static "topology3D/js/graph_request.js" %}"></script>
+    <script src="/static/topology3D/js/d3-context-menu.js"></script>
+    <script src="/static/topology3D/js/event.js"></script>
+    <script src="/static/topology3D/js/graph_editor.js"></script>
+    <script src="/static/topology3D/js/graph_request.js"></script>
+    <script src="/static/topology3D/js/model_graph_editor.js"></script>
 
-{% endblock %}
 
+    <script src="/static/src/osm_gui_properties.js"></script>
+    <script src="/static/src/projecthandler/composer.js"></script>
+    <script src="/static/src/projecthandler/osm/controller.js"></script>
 
-{% block header %}
 {% endblock %}
 
+{% block footer %}
+    {% include "footer.html" %}
+{% endblock %}
index 6339679..6e3793d 100644 (file)
                                        <tr>
 
                                                <td>
-                                                       <a href="javascript:openProject('{{ p.name }}')" >{{ p.name }}</a>
+                                                       <a href="/projects/switch/{{ p.name }}" >{{ p.name }}</a>
                                                </td>
 
                                                <td>{{ p|get_sub:"_admin,modified"|get_date}}</td>
                         <td>{{ p|get_sub:"_admin,created"|get_date}}</td>
 
-                                               <td><a href="javascript:deleteProject('{% url 'projects:delete_project'  project_id=p|get:'_id' %}')"> Delete</a></td>
+                                               <td><a href="javascript:deleteProject('{% url 'projects:delete_project' %}')"> Delete</a></td>
 
                                        </tr>
                                {% endfor %}
diff --git a/projecthandler/template/project/repository/repo_base_left_sidebar.html b/projecthandler/template/project/repository/repo_base_left_sidebar.html
deleted file mode 100644 (file)
index 3367eeb..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-{% extends "left_sidebar_base.html" %}
-
-{% block left_sidebar_base %}
-    <li class="header">REPOSITORY</li>
-    {% url "repos:repos_list" as  repo_list_url %}
-    <li {% if request.get_full_path == repo_list_url %} class="active" {% endif %}><a href='{% url "repos:repos_list" %}'><i class="fa fa-git fa-fw"></i><span>Ropository Registered</span></a></li>
-
-    {% block li_list %}
-
-
-    {% endblock %}
-{% endblock %}
diff --git a/projecthandler/template/project/repository/repo_create_modal.html b/projecthandler/template/project/repository/repo_create_modal.html
deleted file mode 100644 (file)
index 6df53b5..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-<div class="modal" id="modal_new_repository" xmlns="http://www.w3.org/1999/html">
-    <div class="modal-dialog">
-        <div class="modal-content">
-            <div class="modal-header">
-                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
-                    <span aria-hidden="true">×</span></button>
-                <h4 class="modal-title" id="modal_new_repo_title">New Repository</h4>
-            </div>
-            <div id="div_chose_id" class="modal-body">
-                <!-- form start -->
-            <form action='{% url "repos:new_repo" %}' class="form-horizontal" role="form" method="post" enctype="multipart/form-data">
-                {% csrf_token %}
-                    <div class="box-body">
-                        <div class="form-group">
-                            <label for="name" class="col-sm-2 control-label">Name</label>
-
-                            <div class="col-sm-10">
-                                <input type="text" class="form-control" id="name" placeholder="Name" name="name" required>
-                            </div>
-                        </div>
-                        <div class="form-group">
-                            <label for="base_url_repo" class="col-sm-2 control-label">Base Url</label>
-
-                                <div class="col-sm-10">
-                                    <input class="form-control required" id="base_url_repo"
-                                           name="base_url_repo" placeholder="Base Url" pattern="((git|ssh|http(s)?)|(git@[\w\.]+))(:(\/\/)?)([\w\.\/\-]*)">
-                                </div>
-                        </div>
-                    </div>
-                    <!-- /.box-body -->
-                    <div class="box-footer">
-                        <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Cancel</button>
-                        <button type="submit" class="btn btn-info pull-right" id="save_new_repo">Register</button>
-                    </div>
-                    <!-- /.box-footer -->
-                </form>
-            </div>
-
-        </div>
-        <!-- /.modal-content -->
-    </div>
-    <!-- /.modal-dialog -->
-</div>
\ No newline at end of file
diff --git a/projecthandler/template/project/repository/repo_list.html b/projecthandler/template/project/repository/repo_list.html
deleted file mode 100644 (file)
index 1f0a8f3..0000000
+++ /dev/null
@@ -1,120 +0,0 @@
-{% extends "base.html" %}
-
-{% load staticfiles %}
-
-{% block head_block %}
-{{ block.super }}
-
-<style type="text/css">
-
-  input:required:invalid, input:focus:invalid {
-
-    background-position: right top;
-    background-repeat: no-repeat;
-  }
-  input:required:valid {
-
-    background-position: right top;
-    background-repeat: no-repeat;
-  }
-
-.form-control.select2-hidden-accessible {
-    top: 30px;
-}
-
-
-</style>
-{% endblock %}
-
-{% block title_header_big %}
-{{ block.super }}
-{% endblock %}
-
-{% block left_sidebar %}
-<!-- Left side column. contains the sidebar -->
-{% include "repository/repo_base_left_sidebar.html" %}
-{% endblock %}
-
-
-{% block breadcrumb_body %}
-{{ block.super }}
-
-{% endblock %}
-
-{% block content_body %}
-{{ block.super }}
-{% csrf_token %}
-    <div class="row">
-
-        <div class="col-md-12">
-
-            <div class="box">
-                <div class="box-header with-border">
-                    <h3 class="box-title">Registered Repository</h3>
-                    <div class="box-tools">
-                        <a href="#" class="btn btn-block btn-primary btn-sm" data-toggle="modal"
-                           data-target="#modal_new_repository"><i
-                                class="fa fa-plus"></i><span> New Repository</span></a>
-                    </div>
-                </div>
-                <div class="box-body">
-                    <table id="deployments_table" class="table table-bordered table-striped">
-                        <thead>
-                        <tr>
-
-                            <th>Name</th>
-                            <th>Url</th>
-                            <th>Last Update</th>
-                            <th>Actions</th>
-                        </tr>
-                        </thead>
-                        <tbody>
-                        {% for repo in repos %}
-                            <tr>
-
-                                <td>
-                                    {{ repo.name }}
-                                </td>
-                                <td>
-                                    {{ repo.base_url }}
-                                </td>
-                                <td>{{ repo.last_update }}</td>
-                                <td>
-                                    <div class="btn-group">
-                                        <button type="button" class="btn btn-default"><i class="fa fa-cog"
-                                                                                         aria-hidden="true"></i>
-                                        </button>
-                                        <button type="button" class="btn btn-default dropdown-toggle"
-                                                data-toggle="dropdown"
-                                                aria-expanded="false">
-                                            <span class="caret"></span>
-                                            <span class="sr-only">Toggle Dropdown</span>
-                                        </button>
-                                        <ul class="dropdown-menu" role="menu">
-                                            <li class='disabled'><a href='#'><i class="fa fa-edit fa-fw"></i>Edit</a>
-                                            </li>
-                                            <li><a href='{% url "repos:delete_repo" repo_id=repo.id %}'>
-                                                <i class="fa fa-trash fa-fw"></i>Delete</a></li>
-                                        </ul>
-                                    </div>
-                                </td>
-
-                            </tr>
-                        {% endfor %}
-                        </tbody>
-                    </table>
-                </div>
-            </div>
-        </div>
-
-    </div>
-{% include 'repository/repo_create_modal.html' %}
-
-{% endblock %}
-
-{% block resource_block %}
-{{ block.super }}
-
-
-
-{% endblock %}
\ No newline at end of file
index 2054656..1e3b24e 100644 (file)
@@ -18,24 +18,26 @@ from django.conf.urls import url, include
 from projecthandler import views
 
 urlpatterns = [
+    url(r'^$', views.open_project, name='open_project'),
     url(r'^list/', views.user_projects, name='projects_list'),
     url(r'^new/', views.create_new_project, name='new_project'),
-    url(r'^(?P<project_id>\w+)/$', views.open_project, name='open_project'),
-    url(r'^(?P<project_id>\w+)/sdn/', include('sdnctrlhandler.urls', namespace='sdns'), name='sdns_base'),
-    url(r'^(?P<project_id>\w+)/vims/', include('vimhandler.urls', namespace='vims'), name='vims_base'),
-    url(r'^(?P<project_id>\w+)/instances/', include('instancehandler.urls', namespace='instances'), name='instances_base'),
-    url(r'^(?P<project_id>\w+)/delete$', views.delete_project, name='delete_project'),
-    url(r'^(?P<project_id>\w+)/descriptors/(?P<descriptor_type>\w+)/list$', views.show_descriptors, name='list_descriptors'),
-    url(r'^(?P<project_id>\w+)/descriptors/(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)(/$)',
+    url(r'^delete$', views.delete_project, name='delete_project'),
+    url(r'^switch/(?P<project_id>\w+)', views.switch_project, name='switch_project'),
+    url(r'^descriptors/(?P<descriptor_type>\w+)/list$', views.show_descriptors, name='list_descriptors'),
+    url(r'^descriptors/(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)(/$)',
         views.edit_descriptor, name='edit_descriptor'),
-    url(r'^(?P<project_id>\w+)/descriptors/(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)/delete$',
+    url(r'^descriptors/(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)/delete$',
         views.delete_descriptor,
         name='delete_descriptor'),
-    url(r'^(?P<project_id>\w+)/descriptors/(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)/action/(?P<action_name>[-\w]+)',
+    url(r'^descriptors/(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)/action/(?P<action_name>[-\w]+)',
         views.custom_action,
         name='custom_action'),
-    url(r'^(?P<project_id>\w+)/descriptors/(?P<descriptor_type>\w+)/new$', views.new_descriptor,
+    url(r'^descriptors/(?P<descriptor_type>\w+)/new$', views.new_descriptor,
         name='new_descriptor'),
-
+    url(r'^composer$', views.open_composer, name='open_composer'),
+    url(r'^availablenodes', views.get_available_nodes, name='get_available_nodes'),
+    url(r'^sdn/', include('sdnctrlhandler.urls', namespace='sdns'), name='sdns_base'),
+    url(r'^vims/', include('vimhandler.urls', namespace='vims'), name='vims_base'),
+    url(r'^instances/', include('instancehandler.urls', namespace='instances'), name='instances_base'),
 
 ]
\ No newline at end of file
index 0d50e10..144aa5b 100644 (file)
@@ -20,11 +20,12 @@ import logging
 import yaml
 from django.contrib.auth.decorators import login_required
 from django.http import HttpResponse, JsonResponse
-from django.middleware.csrf import get_token
 from django.shortcuts import render, redirect
+
+from authosm.exceptions import OSMAuthException
 from lib.util import Util
-from projecthandler.osm_model import OsmProject
 from lib.osm.osmclient.clientv2 import Client
+import authosm.utils as osmutils
 
 
 logging.basicConfig(level=logging.DEBUG)
@@ -39,11 +40,12 @@ def home(request):
 @login_required
 def create_new_project(request):
     if request.method == 'POST':
+        user = osmutils.get_user(request)
         client = Client()
         new_project_dict = request.POST.dict()
         keys = ["name"]
         project_data = dict(filter(lambda i: i[0] in keys and len(i[1]) > 0, new_project_dict.items()))
-        result = client.project_create(request.session['token'], project_data)
+        result = client.project_create(user.get_token(), project_data)
         if isinstance(result, dict) and 'error' in result and result['error']:
             print result
             return __response_handler(request, result['data'], url=None,
@@ -54,23 +56,208 @@ def create_new_project(request):
 
 @login_required
 def user_projects(request):
+    user = osmutils.get_user(request)
     client = Client()
-    result = client.project_list(request.session['token'])
+    result = client.project_list(user.get_token())
     return render(request, 'projectlist.html', {
         'projects': result['data'] if result and result['error'] is False else [],
     })
 
 
+def open_composer(request):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    result = {'project_id': project_id,
+              'vertices': [
+                  {"info": {"type": "vnf", "property": {"custom_label": ""},
+                            "group": []}, "id": "vm"},
+                  {"info": {"type": "vnf", "property": {"custom_label": ""},
+                            "group": []}, "id": "vlan"},
+                  {"info": {"type": "vnf", "property": {"custom_label": ""},
+                            "group": []}, "id": "firewall"},
+                  {"info": {"type": "vnf", "property": {"custom_label": ""},
+                            "group": []}, "id": "ping"},
+
+                  {"info": {"type": "ns_vl", "property": {"custom_label": ""},
+                            "group": []}, "id": "vl1"},
+                  {"info": {"type": "ns_vl", "property": {"custom_label": ""},
+                            "group": []}, "id": "vl2"},
+                  {"info": {"type": "ns_vl", "property": {"custom_label": ""},
+                            "group": []}, "id": "vl3"},
+              ],
+              'edges': [
+                  {"source": "vm", "group": [], "target": "vl3", "view": "ns"},
+                  {"source": "vlan", "group": [], "target": "vl3", "view": "ns"},
+                  {"source": "vlan", "group": [], "target": "vl1", "view": "ns"},
+                  {"source": "firewall", "group": [], "target": "vl1", "view": "ns"},
+                  {"source": "firewall", "group": [], "target": "vl2", "view": "ns"},
+                  {"source": "ping", "group": [], "target": "vl2", "view": "ns"},
+              ],
+              'model': {
+                "layer": {
+
+                    "ns": {
+                        "nodes": {
+                            "vnf": {
+                                "addable": {
+                                    "callback": "addNode"
+                                },
+                                "removable": {
+                                    "callback": "removeNode"
+                                },
+                                "expands": "vnf"
+                            },
+                            "ns_vl": {
+                                "addable": {
+                                    "callback": "addNode"
+                                },
+                                "removable": {
+                                    "callback": "removeNode"
+                                }
+                            },
+
+                        },
+                        "allowed_edges": {
+                            "ns_vl": {
+                                "destination": {
+                                    "vnf": {
+                                        "callback": "addLink",
+                                        "direct_edge": False,
+                                        "removable": {
+                                            "callback": "removeLink"
+                                        }
+                                    }
+                                }
+                            },
+                            "vnf": {
+                                "destination": {
+                                    "ns_vl": {
+                                        "callback": "addLink",
+                                        "direct_edge": False,
+                                        "removable": {
+                                            "callback": "removeLink"
+                                        }
+                                    },
+
+                                }
+                            }
+
+                        }
+                    },
+                    "vnf": {
+                        "nodes": {
+                            "vdu": {
+                                "addable": {
+                                    "callback": "addNode"
+                                },
+                                "removable": {
+                                    "callback": "removeNode"
+                                }
+                            },
+                            "cp": {
+                                "addable": {
+                                    "callback": "addNode"
+                                },
+                                "removable": {
+                                    "callback": "removeNode"
+                                }
+                            },
+
+                        },
+                        "allowed_edges": {
+                            "vdu": {
+                                "destination": {
+                                    "cp": {
+                                        "callback": "addLink",
+                                        "direct_edge": False,
+                                        "removable": {
+                                            "callback": "removeLink"
+                                        }
+                                    }
+                                }
+                            },
+                            "cp": {
+                                "destination": {
+                                    "vdu": {
+                                        "callback": "addLink",
+                                        "direct_edge": False,
+                                        "removable": {
+                                            "callback": "removeLink"
+                                        }
+                                    }
+                                }
+                            }
+                        }
+                    },
+                    "name": "OSM",
+                    "version": 1,
+                    "nodes": {
+                        "vnf": {
+                            "label": "vnf"
+                        },
+                        "ns_vl": {
+                            "label": "vl"
+                        },
+                        "cp": {
+                            "label": "cp"
+                        },
+                        "vdu": {
+                            "label": "vdu"
+                        }
+                    },
+                    "description": "osm",
+                    "callback": {
+                        "addNode": {
+                            "file": "osm_controller.js",
+                            "class": "OsmController"
+                        },
+                        "removeNode": {
+                            "file": "osm_controller.js",
+                            "class": "OsmController"
+                        },
+                        "addLink": {
+                            "file": "osm_controller.js",
+                            "class": "OsmController"
+                        },
+                        "removeLink": {
+                            "file": "osm_controller.js",
+                            "class": "OsmController"
+                        }
+                    }
+
+                }
+            }}
+    return __response_handler(request, result, 'project_graph_base.html')
+
+
+def get_available_nodes(request):
+
+    params = request.GET.dict()
+    nodes = {
+        'ns': [{"types": [{"name": "Generic", "id": "vnf"},
+                          {"name": "ping", "id": "vnf"},
+                          {"name": "pong", "id": "vnf"},
+                          {"name": "hackfest1-vm", "id": "vnf"}], "category_name": "Vnf"},
+               {"types": [{"name": "VL", "id": "ns_vl"}], "category_name": "VirtualLink"}],
+        'vnf': [{"types": [{"name": "VDU", "id": "vdu"}], "category_name": "Vdu"},
+                {"types": [{"name": "CP", "id": "cp"}], "category_name": "CP"}]
+    }
+
+    return __response_handler(request, nodes[params['layer']])
+
+
 @login_required
-def open_project(request, project_id=None):
+def open_project(request):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     try:
-        user = request.user
+
         client = Client()
         ##TODO change with adhoc api call
-        nsd = client.nsd_list(request.session['token'])
-        vnfd = client.vnfd_list(request.session['token'])
-        ns = client.ns_list(request.session['token'])
-        vnf = client.vnf_list(request.session['token'])
+        nsd = client.nsd_list(user.get_token())
+        vnfd = client.vnfd_list(user.get_token())
+        ns = client.ns_list(user.get_token())
+        vnf = client.vnf_list(user.get_token())
         project_overview = {
             'owner': user.username,
             'name': project_id,
@@ -92,9 +279,11 @@ def open_project(request, project_id=None):
 
 
 @login_required
-def delete_project(request, project_id=None):
+def delete_project(request):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     client = Client()
-    result = client.project_delete(request.session['token'], project_id)
+    result = client.project_delete(user.get_token(), project_id)
     if isinstance(result, dict) and 'error' in result and result['error']:
         print result
         return __response_handler(request, result['data'], url=None,
@@ -104,14 +293,23 @@ def delete_project(request, project_id=None):
 
 
 @login_required
-def show_descriptors(request, project_id=None, descriptor_type=None):
+def switch_project(request, project_id):
+    user = osmutils.get_user(request)
+    user.switch_project(project_id)
+    return redirect('projects:open_project')
+
+
+@login_required
+def show_descriptors(request, descriptor_type=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     client = Client()
     print request.GET.dict()
     try:
         if descriptor_type == 'nsd':
-            descriptors = client.nsd_list(request.session['token'])
+            descriptors = client.nsd_list(user.get_token())
         elif descriptor_type == 'vnfd':
-            descriptors = client.vnfd_list(request.session['token'])
+            descriptors = client.vnfd_list(user.get_token())
     except Exception as e:
         log.exception(e)
         descriptors = []
@@ -126,14 +324,15 @@ def show_descriptors(request, project_id=None, descriptor_type=None):
 
 
 @login_required
-def delete_descriptor(request, project_id=None, descriptor_type=None, descriptor_id=None):
-
+def delete_descriptor(request, descriptor_type=None, descriptor_id=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     try:
         client = Client()
         if descriptor_type == 'nsd':
-            result = client.nsd_delete(request.session['token'], descriptor_id)
+            result = client.nsd_delete(user.get_token(), descriptor_id)
         elif descriptor_type == 'vnfd':
-            result = client.vnfd_delete(request.session['token'], descriptor_id)
+            result = client.vnfd_delete(user.get_token(), descriptor_id)
     except Exception as e:
         log.exception(e)
         result = {'error': True, 'data': str(e)}
@@ -142,9 +341,9 @@ def delete_descriptor(request, project_id=None, descriptor_type=None, descriptor
     descriptors = {}
     try:
         if descriptor_type == 'nsd':
-            descriptors = client.nsd_list(request.session['token'])
+            descriptors = client.nsd_list(user.get_token())
         elif descriptor_type == 'vnfd':
-            descriptors = client.vnfd_list(request.session['token'])
+            descriptors = client.vnfd_list(user.get_token())
     except Exception as e:
         log.exception(e)
 
@@ -161,8 +360,9 @@ def delete_descriptor(request, project_id=None, descriptor_type=None, descriptor
 
 
 @login_required
-def new_descriptor(request, project_id=None, descriptor_type=None):
-
+def new_descriptor(request, descriptor_type=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     page = 'osm/descriptor/descriptor_new.html'
     if request.method == 'GET':
         request_id = request.GET.get('id', '')
@@ -181,9 +381,9 @@ def new_descriptor(request, project_id=None, descriptor_type=None):
             try:
                 client = Client()
                 if descriptor_type == 'nsd':
-                    result = client.nsd_onboard(request.session['token'], file_uploaded)
+                    result = client.nsd_onboard(user.get_token(), file_uploaded)
                 elif descriptor_type == 'vnfd':
-                    result = client.vnfd_onboard(request.session['token'], file_uploaded)
+                    result = client.vnfd_onboard(user.get_token(), file_uploaded)
                 else:
                     log.debug('Create descriptor: Unknown data type')
                     result = {'error': True, 'data': 'Create descriptor: Unknown data type'}
@@ -202,7 +402,9 @@ def new_descriptor(request, project_id=None, descriptor_type=None):
 
 
 @login_required
-def edit_descriptor(request, project_id=None, descriptor_id=None, descriptor_type=None):
+def edit_descriptor(request, descriptor_id=None, descriptor_type=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     if request.method == 'POST':
         print "edit_descriptor"
         new_data = request.POST.get('text'),
@@ -216,14 +418,14 @@ def edit_descriptor(request, project_id=None, descriptor_id=None, descriptor_typ
                 elif data_type == 'json':
                     new_data = json.loads(request.POST.get('text'))
                 print new_data
-                result = client.nsd_update(request.session['token'], descriptor_id, new_data)
+                result = client.nsd_update(user.get_token(), descriptor_id, new_data)
             elif descriptor_type == 'vnfd':
                 if data_type == 'yaml':
                     new_data = yaml.load(request.POST.get('text'))
                 elif data_type == 'json':
                     new_data = json.loads(request.POST.get('text'))
                 print new_data
-                result = client.vnfd_update(request.session['token'], descriptor_id, new_data)
+                result = client.vnfd_update(user.get_token(), descriptor_id, new_data)
 
             else:
                 log.debug('Update descriptor: Unknown data type')
@@ -244,10 +446,10 @@ def edit_descriptor(request, project_id=None, descriptor_id=None, descriptor_typ
         try:
             client = Client()
             if descriptor_type == 'nsd':
-                result = client.nsd_get(request.session['token'], descriptor_id)
+                result = client.nsd_get(user.get_token(), descriptor_id)
                 print result
             elif descriptor_type == 'vnfd':
-                result = client.vnfd_get(request.session['token'], descriptor_id)
+                result = client.vnfd_get(user.get_token(), descriptor_id)
 
                 print result
         except Exception as e:
@@ -269,14 +471,14 @@ def edit_descriptor(request, project_id=None, descriptor_id=None, descriptor_typ
 
 
 @login_required
-def get_package_files_list(request, project_id, descriptor_id, descriptor_type):
-    files_list = []
+def get_package_files_list(request, descriptor_id, descriptor_type):
+    user = osmutils.get_user(request)
     try:
         client = Client()
         if descriptor_type == 'nsd':
-            artifacts_res = client.nsd_artifacts(request.session['token'], descriptor_id)
+            artifacts_res = client.nsd_artifacts(user.get_token(), descriptor_id)
         elif descriptor_type == 'vnfd':
-            artifacts_res = client.vnf_packages_artifacts(request.session['token'], descriptor_id)
+            artifacts_res = client.vnf_packages_artifacts(user.get_token(), descriptor_id)
         else:
             return False
 
@@ -289,15 +491,16 @@ def get_package_files_list(request, project_id, descriptor_id, descriptor_type):
     return __response_handler(request, result)
 
 @login_required
-def download_pkg(request, project_id, descriptor_id, descriptor_type):
+def download_pkg(request, descriptor_id, descriptor_type):
+    user = osmutils.get_user(request)
     file_name = "osm_export.tar.gz"
     tar_pkg = None
     try:
         client = Client()
         if descriptor_type == 'nsd':
-            tar_pkg = client.get_nsd_pkg(request.session['token'], descriptor_id)
+            tar_pkg = client.get_nsd_pkg(user.get_token(), descriptor_id)
         elif descriptor_type == 'vnfd':
-            tar_pkg = client.get_vnfd_pkg(request.session['token'], descriptor_id)
+            tar_pkg = client.get_vnfd_pkg(user.get_token(), descriptor_id)
 
     except Exception as e:
         log.exception(e)
@@ -309,10 +512,10 @@ def download_pkg(request, project_id, descriptor_id, descriptor_type):
 
 
 @login_required
-def custom_action(request, project_id=None, descriptor_id=None, descriptor_type=None, action_name=None):
+def custom_action(request, descriptor_id=None, descriptor_type=None, action_name=None):
     if request.method == 'GET':
         print "Custom action: " + action_name
-        return globals()[action_name](request, project_id, descriptor_id, descriptor_type)
+        return globals()[action_name](request, descriptor_id, descriptor_type)
 
 
 def __response_handler(request, data_res, url=None, to_redirect=None, *args, **kwargs):
index 60249a3..75d010d 100644 (file)
@@ -19,7 +19,7 @@
 
 {% block breadcrumb_body %}
     {{ block.super }}
-    <li><a href="{% url 'projects:sdns:list' project_id=project_id %}">SDN Controllers</a></li>
+    <li><a href="{% url 'projects:sdns:list'  %}">SDN Controllers</a></li>
 {% endblock %}
 
 {% block content_body %}
@@ -27,7 +27,7 @@
 
     <div class="row">
         <div class="col-md-12">
-            <form action='{% url 'projects:sdns:create' project_id=project_id %}' method="post">
+            <form action='{% url 'projects:sdns:create'  %}' method="post">
                 {% csrf_token %}
                 <div class="box">
                     <div class="box-header with-border">
 
                     </div>
                     <div class="box-footer">
-                        <button onclick="location.href='{% url 'projects:sdns:list' project_id=project_id %}'"
+                        <button onclick="location.href='{% url 'projects:sdns:list'  %}'"
                                 class="btn btn-default pull-left">Back to
                             SDN Controllers
                         </button>
index 8abb5e0..acb73d1 100644 (file)
@@ -17,7 +17,7 @@
 
 {% block breadcrumb_body %}
     {{ block.super }}
-    <li><a href="{% url 'projects:sdns:list' project_id=project_id %}">SDN Controllers</a></li>
+    <li><a href="{% url 'projects:sdns:list'  %}">SDN Controllers</a></li>
 {% endblock %}
 
 {% block content_body %}
@@ -31,7 +31,7 @@
                 <div class="box-header with-border">
                     <h3 class="box-title">Registered SDN Controllers</h3>
                     <div class="box-tools">
-                        <a href='{% url "projects:sdns:create" project_id=project_id %}' class="btn btn-block btn-primary btn-sm"><i
+                        <a href='{% url "projects:sdns:create"  %}' class="btn btn-block btn-primary btn-sm"><i
                                 class="fa fa-plus"></i><span> New SDN Controller</span></a>
                     </div>
                 </div>
                                 <td>
                                     <div class="btn-group">
                                         <button type="button" class="btn btn-default"
-                                                onclick="javascript:showSDN('{{ project_id }}', '{{ s|get:"_id" }}')" data-toggle="tooltip" data-placement="top" data-container="body" title="Show Info"><i
+                                                onclick="javascript:showSDN( '{{ s|get:"_id" }}')" data-toggle="tooltip" data-placement="top" data-container="body" title="Show Info"><i
                                                 class="fa fa-info"></i></button>
                                         <button type="button" class="btn btn-default"
-                                                onclick="javascript:deleteSDN('{{ project_id }}', '{{ s|get:"_id" }}')" data-toggle="tooltip" data-placement="top" data-container="body" title="Delete"><i
+                                                onclick="javascript:deleteSDN('{{ s|get:"_id" }}')" data-toggle="tooltip" data-placement="top" data-container="body" title="Delete"><i
                                                 class="far fa-trash-alt" ></i></button>
                                     </div>
                                 </td>
index f01f8b2..26488ce 100644 (file)
@@ -19,7 +19,7 @@ from django.contrib.auth.decorators import login_required
 from django.http import HttpResponse
 import json
 import logging
-#from lib.osm.osmclient.client import Client
+import authosm.utils as osmutils
 from lib.osm.osmclient.clientv2 import Client
 
 logging.basicConfig(level=logging.DEBUG)
@@ -27,9 +27,11 @@ log = logging.getLogger('sdnctrlhandler/view.py')
 
 
 @login_required
-def list(request, project_id):
+def list(request):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     client = Client()
-    result = client.sdn_list(request.session['token'])
+    result = client.sdn_list(user.get_token())
 
     result = {
         'project_id': project_id,
@@ -39,7 +41,9 @@ def list(request, project_id):
 
 
 @login_required
-def create(request, project_id):
+def create(request):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     result = {'project_id': project_id}
     if request.method == 'GET':
         return __response_handler(request, result, 'sdn_create.html')
@@ -57,25 +61,29 @@ def create(request, project_id):
         sdn_data = dict(filter(lambda i: i[0] in keys and len(i[1]) > 0, new_sdn_dict.items()))
         sdn_data['port'] = int(sdn_data['port'])
 
-        result = client.sdn_create(request.session['token'], sdn_data)
+        result = client.sdn_create(user.get_token(), sdn_data)
 
-        return __response_handler(request, result, 'projects:sdns:list', to_redirect=True, project_id=project_id)
+        return __response_handler(request, result, 'projects:sdns:list', to_redirect=True, )
 
 
 @login_required
-def delete(request, project_id, sdn_id=None):
+def delete(request, sdn_id=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     try:
         client = Client()
-        del_res = client.sdn_delete(request.session['token'], sdn_id)
+        del_res = client.sdn_delete(user.get_token(), sdn_id)
     except Exception as e:
         log.exception(e)
-    return __response_handler(request, {}, 'projects:sdns:list', to_redirect=True, project_id=project_id)
+    return __response_handler(request, {}, 'projects:sdns:list', to_redirect=True, )
 
 
 @login_required
-def show(request, project_id, sdn_id=None):
+def show(request, sdn_id=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     client = Client()
-    result = client.sdn_get(request.session['token'], sdn_id)
+    result = client.sdn_get(user.get_token(), sdn_id)
     if isinstance(result, dict) and 'error' in result and result['error']:
         return render(request, 'error.html')
     return __response_handler(request, {
index dedc230..53bde44 100644 (file)
@@ -57,6 +57,7 @@ INSTALLED_APPS = [
 MIDDLEWARE_CLASSES = [
     'django.middleware.security.SecurityMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
+    'projecthandler.middleware.OsmProjectMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
@@ -64,6 +65,7 @@ MIDDLEWARE_CLASSES = [
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
 
+
 ]
 
 SESSION_ENGINE ='django.contrib.sessions.backends.db'
index d0bbf01..3524ebb 100644 (file)
@@ -23,7 +23,6 @@ app_name = 'base'
 urlpatterns = [
     #url(r'^admin/', admin.site.urls),
     url(r'^auth/$', user_views.user_login, name='auth_user'),
-    #url(r'^auth_guest/$', user_views.guest_login, name='auth_user_guest'),
     #url(r'^register', user_views.register_view, name='register_user'),
     url(r'^projects/', include('projecthandler.urls.project', namespace='projects'), name='projects_base'),
 
index 810373f..547f20a 100644 (file)
@@ -7,14 +7,7 @@ from authosm.models import OsmUser
 
 @login_required
 def home(request):
-    user = OsmUser.objects.get(id=request.user.id)
-
-    projects = Project.objects.filter(owner=user).select_subclasses()
-    result = {
-        'projects': len(projects) if projects else 0,
-    }
-    return redirect('projects:open_project', project_id='admin')
-    #return render(request, 'home.html', result)
+    return redirect('projects:open_project')
 
 
 def forbidden(request):
diff --git a/sf_user/__init__.py b/sf_user/__init__.py
deleted file mode 100644 (file)
index e69de29..0000000
diff --git a/sf_user/admin.py b/sf_user/admin.py
deleted file mode 100644 (file)
index 2e9690a..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-#   Copyright 2018 CNIT - Consorzio Nazionale Interuniversitario per le Telecomunicazioni
-#
-#   Licensed under the Apache License, Version 2.0 (the "License");
-#   you may not use this file except in compliance with the License.
-#   You may obtain a copy of the License at
-#
-#       http://www.apache.org/licenses/LICENSE-2.0
-#
-#   Unless required by applicable law or agreed to in writing, software
-#   distributed under the License is distributed on an  BASIS,
-#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-#   See the License for the specific language governing permissions and
-#   limitations under the License.
-#
-
-from django.contrib import admin
-
-# Register your models here.
diff --git a/sf_user/apps.py b/sf_user/apps.py
deleted file mode 100644 (file)
index 902aa7d..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-#
-#   Copyright 2018 CNIT - Consorzio Nazionale Interuniversitario per le Telecomunicazioni
-#
-#   Licensed under the Apache License, Version 2.0 (the "License");
-#   you may not use this file except in compliance with the License.
-#   You may obtain a copy of the License at
-#
-#       http://www.apache.org/licenses/LICENSE-2.0
-#
-#   Unless required by applicable law or agreed to in writing, software
-#   distributed under the License is distributed on an  BASIS,
-#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-#   See the License for the specific language governing permissions and
-#   limitations under the License.
-#
-
-from django.apps import AppConfig
-
-
-class SfUserConfig(AppConfig):
-    name = 'sf_user'
diff --git a/sf_user/management/__init__.py b/sf_user/management/__init__.py
deleted file mode 100644 (file)
index e69de29..0000000
diff --git a/sf_user/management/commands/__init__.py b/sf_user/management/commands/__init__.py
deleted file mode 100644 (file)
index e69de29..0000000
diff --git a/sf_user/management/commands/clean_guest_data.py b/sf_user/management/commands/clean_guest_data.py
deleted file mode 100644 (file)
index 0ff087b..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-from django.core.management.base import BaseCommand, CommandError
-from sf_user.models import CustomSession, CustomUser
-
-
-class Command(BaseCommand):
-    help = 'Clean Guest Users Sessions'
-
-    #def add_arguments(self, parser):
-    #    parser.add_argument('poll_id', nargs='+', type=int)
-
-    def handle(self, *args, **options):
-        #for guest in CustomUser.objects.filter(is_guest_user="True"):
-        #    self.stdout.write(self.style.SUCCESS(guest.username))
-            try:
-                CustomUser.objects.filter(is_guest_user="True").delete()
-            except Exception:
-                raise CommandError('Error unable to clean guest users sessions')
-
-            self.stdout.write(self.style.SUCCESS('Successfully cleaned guest users sessions'))
diff --git a/sf_user/management/commands/clearsessions.py b/sf_user/management/commands/clearsessions.py
deleted file mode 100644 (file)
index 8717521..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-from django.core.management.base import BaseCommand, CommandError
-from sf_user.models import CustomSession
-
-
-class Command(BaseCommand):
-    help = 'Clean Users Sessions'
-
-    #def add_arguments(self, parser):
-    #    parser.add_argument('poll_id', nargs='+', type=int)
-
-    def handle(self, *args, **options):
-            try:
-                CustomSession.objects.all().delete()
-            except Exception:
-                raise CommandError('Error unable to clean users sessions')
-
-            self.stdout.write(self.style.SUCCESS('Successfully cleaned users sessions'))
\ No newline at end of file
diff --git a/sf_user/models.py b/sf_user/models.py
deleted file mode 100644 (file)
index 6485e82..0000000
+++ /dev/null
@@ -1,195 +0,0 @@
-#
-#   Copyright 2018 CNIT - Consorzio Nazionale Interuniversitario per le Telecomunicazioni
-#
-#   Licensed under the Apache License, Version 2.0 (the "License");
-#   you may not use this file except in compliance with the License.
-#   You may obtain a copy of the License at
-#
-#       http://www.apache.org/licenses/LICENSE-2.0
-#
-#   Unless required by applicable law or agreed to in writing, software
-#   distributed under the License is distributed on an  BASIS,
-#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-#   See the License for the specific language governing permissions and
-#   limitations under the License.
-#
-
-from __future__ import unicode_literals
-
-from django.contrib.auth.models import (
-    AbstractBaseUser, BaseUserManager, PermissionsMixin)
-from django.utils import timezone
-from django.utils.translation import ugettext_lazy as _
-from django.contrib.sessions.base_session import AbstractBaseSession
-from django.db import models
-
-class CustomUserManager(BaseUserManager):
-    """Custom manager for CustomUser."""
-
-    def _create_user(self, username, password, is_staff, is_superuser, **extra_fields):
-        """Create and save a CustomUser with the given username and password. """
-        now = timezone.now()
-
-        if not username:
-            raise ValueError('The given username must be set')
-
-        is_active = extra_fields.pop("is_active", True)
-        user = self.model(username=username, is_staff=is_staff, is_active=is_active,
-                          is_superuser=is_superuser, last_login=now,
-                          date_joined=now, **extra_fields)
-        user.set_password(password)
-        user.save(using=self._db)
-        return user
-
-    """Create and save an CustomUser with the given username and password."""
-    def create_superuser(self, username, password, **extra_fields):
-        return self._create_user(username, password, True, True, is_admin=True,
-                                 **extra_fields)
-
-    """Create and save an FullOperator with the given email and password. """
-    def create_full_operator(self, username, password=None, **extra_fields):
-        return self._create_user(username, password, False, False, is_full_operator=True,
-                                 **extra_fields)
-
-    """Create and save an BasicUser with the given email and password. """
-    def create_basic_user(self, username, password=None, **extra_fields):
-        return self._create_user(username, password, False, False, is_basic_user=True,
-                                 **extra_fields)
-
-    """Create and save an GuestUser with the given email and password. """
-    def create_guest_user(self, username, password="guest", **extra_fields):
-        return self._create_user(username, password, False, False, is_guest_user=True,
-                                 **extra_fields)
-
-
-class AbstractCustomUser(AbstractBaseUser, PermissionsMixin):
-    """Abstract User with the same behaviour as Django's default User.
-
-    AbstractCustomUser does not have username field. Uses email as the
-    USERNAME_FIELD for authentication.
-
-    Use this if you need to extend EmailUser.
-
-    Inherits from both the AbstractBaseUser and PermissionMixin.
-
-    The following attributes are inherited from the superclasses:
-        * password
-        * last_login
-        * is_superuser
-
-    """
-    username = models.CharField(_('username'), max_length=255, unique=True, db_index=True)
-
-    email = models.EmailField(_('email address'), max_length=255, unique=True)
-
-    first_name = models.CharField(_('first name'), max_length=255, blank=True)
-    last_name = models.CharField(_('last name'), max_length=255, blank=True)
-    phone = models.CharField(_('phone'), max_length=100, blank=True)
-    # user_groups = models.ManyToManyField(UserGroup, verbose_name=_('user groups'), blank=True)
-
-    is_admin = models.BooleanField(_('admin status'), default=False)
-    is_full_operator = models.BooleanField(_('full_operator status'), default=False)
-    is_basic_user = models.BooleanField(_('basic_user status'), default=False)
-    is_guest_user = models.BooleanField(_('guest_user status'), default=False)
-
-    is_staff = models.BooleanField(
-        _('staff status'), default=False, help_text=_(
-            'Designates whether the user can log into this admin site.'))
-    is_active = models.BooleanField(_('active'), default=True, help_text=_(
-        'Designates whether this user should be treated as '
-        'active. Unselect this instead of deleting accounts.'))
-
-    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
-
-    objects = CustomUserManager()
-
-    USERNAME_FIELD = 'username'
-    REQUIRED_FIELDS = ['email', 'first_name', 'last_name', 'phone', ]
-
-    class Meta:
-        verbose_name = _('custom user')
-        verbose_name_plural = _('custom users')
-        abstract = True
-
-    def get_full_name(self):
-        """Return the fullname."""
-        return "%s %s" % (self.last_name, self.first_name)
-
-    def get_short_name(self):
-        """Return the firstname."""
-        return self.first_name
-
-
-class CustomUser(AbstractCustomUser):
-    """
-    Concrete class of AbstractCustomUser.
-
-    Use this if you don't need to extend CustomUser.
-
-    """
-
-    class Meta(AbstractCustomUser.Meta):
-        swappable = 'AUTH_USER_MODEL'
-
-    def count_admins(self):
-        return CustomUser.objects.filter(is_admin=True).count()
-
-    def count_employee(self):
-        return CustomUser.objects.filter(is_full_operator=True).count()
-
-    def count_basic_users(self):
-        return CustomUser.objects.filter(is_basic_user=True).count()
-
-    def count_inactives(self):
-        return CustomUser.objects.filter(is_active=False).count()
-
-    def is_guest(self):
-        return self.is_guest_user
-
-    def get_avatar(self):
-        if self.is_admin:
-            return "assets/img/employer.png"
-        elif self.is_full_operator:
-            return "assets/img/employer.png"
-        elif self.is_basic_user:
-            return "assets/img/employer.png"
-        elif self.is_guest_user:
-            return "assets/img/account_circle.png"
-
-    def get_user_role(self):
-        if self.is_admin:
-            return 0, "Admin"
-        elif self.is_full_operator:
-            return 1, "Full operator"
-        elif self.is_basic_user:
-            return 2, "Basic user"
-        elif self.is_guest_user:
-            return 3, "Guest user"
-
-    def get_user_role_name(self):
-        if self.is_admin:
-            return "Admin"
-        elif self.is_full_operator:
-            return "Full operator"
-        elif self.is_basic_user:
-            return "Basic user"
-        elif self.is_guest_user:
-            return "Guest user"
-
-    def has_perm(self, perm, obj=None):
-        if perm == 'deploymenthandler':
-            if self.is_guest_user:
-                return False
-            else:
-                return True
-        else:
-            super.has_perm(perm, obj)
-
-
-class CustomSession(AbstractBaseSession):
-    account_id = models.IntegerField(null=True, db_index=True)
-
-    @classmethod
-    def get_session_store_class(cls):
-        return SessionStore
-
diff --git a/sf_user/sessions.py b/sf_user/sessions.py
deleted file mode 100644 (file)
index a2e1136..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-#
-#   Copyright 2018 CNIT - Consorzio Nazionale Interuniversitario per le Telecomunicazioni
-#
-#   Licensed under the Apache License, Version 2.0 (the "License");
-#   you may not use this file except in compliance with the License.
-#   You may obtain a copy of the License at
-#
-#       http://www.apache.org/licenses/LICENSE-2.0
-#
-#   Unless required by applicable law or agreed to in writing, software
-#   distributed under the License is distributed on an  BASIS,
-#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-#   See the License for the specific language governing permissions and
-#   limitations under the License.
-#
-
-# from django.contrib.sessions.backends.db import SessionStore as DBStore
-# import sf_user
-#
-# class SessionStore(DBStore):
-#     @classmethod
-#     def get_model_class(cls):
-#         return sf_user.models.CustomSession
-#
-#     def create_model_instance(self, data):
-#         obj = super(SessionStore, self).create_model_instance(data)
-#         try:
-#             account_id = int(data.get('_auth_user_id'))
-#         except (ValueError, TypeError):
-#             account_id = None
-#         obj.account_id = account_id
-#         return obj
\ No newline at end of file
diff --git a/sf_user/tests.py b/sf_user/tests.py
deleted file mode 100644 (file)
index 79947e6..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-#   Copyright 2018 CNIT - Consorzio Nazionale Interuniversitario per le Telecomunicazioni
-#
-#   Licensed under the Apache License, Version 2.0 (the "License");
-#   you may not use this file except in compliance with the License.
-#   You may obtain a copy of the License at
-#
-#       http://www.apache.org/licenses/LICENSE-2.0
-#
-#   Unless required by applicable law or agreed to in writing, software
-#   distributed under the License is distributed on an  BASIS,
-#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-#   See the License for the specific language governing permissions and
-#   limitations under the License.
-#
-
-from django.test import TestCase
-
-# Create your tests here.
diff --git a/sf_user/views.py b/sf_user/views.py
deleted file mode 100644 (file)
index fb33347..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-#
-#   Copyright 2018 CNIT - Consorzio Nazionale Interuniversitario per le Telecomunicazioni
-#
-#   Licensed under the Apache License, Version 2.0 (the "License");
-#   you may not use this file except in compliance with the License.
-#   You may obtain a copy of the License at
-#
-#       http://www.apache.org/licenses/LICENSE-2.0
-#
-#   Unless required by applicable law or agreed to in writing, software
-#   distributed under the License is distributed on an  BASIS,
-#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-#   See the License for the specific language governing permissions and
-#   limitations under the License.
-#
-
-from django.shortcuts import render
-from django.contrib.auth import login, logout, authenticate
-from django.http import HttpResponseRedirect
-from sf_user.models import CustomUser
-import urllib
-import uuid
-
-
-# Create your views here.
-def login_view(request):
-    if hasattr(request.user, "is_guest_user") and request.user.is_guest_user == True:
-        print "is_guest", request.user.is_guest_user
-        CustomUser.objects.get(id=request.user.id).delete()
-    logout(request)
-    extra_data = {}
-    next_page = ""
-    if request.GET:
-        next_page = request.GET['next']
-    error_message = ''
-    if request.POST:
-        print request.POST.get('username')
-        print request.POST.get('password')
-        next_page = request.POST.get('next')
-        next_page = urllib.unquote(next_page).decode('iso-8859-2')
-        user = authenticate(username=request.POST.get('username'), password=request.POST.get('password'))
-        print "Auth Result: " + str(user) + " -> " + str(user)
-        if user and user.is_active:
-            if user.is_authenticated():
-                login(request, user)
-                print next_page
-                if next_page == "" or next_page is None:
-                    return HttpResponseRedirect('/home')
-                else:
-                    return HttpResponseRedirect(next_page)
-        else:
-            error_message = 'Login failed!'
-    return render(request, 'login.html', {'error_message':error_message, 'collapsed_sidebar': False})
-
-
-def guest_login(request):
-    #user = CustomUser.objects.get(id=request.user.id)
-    if hasattr(request.user, "is_guest_user") and request.user.is_guest_user == True:
-        CustomUser.objects.get(id=request.user.id).delete()
-    logout(request)
-    next = ""
-
-    guest_user_name = "Guest_"+str(uuid.uuid4())
-    guest_user_email = guest_user_name+"@guest.it"
-    guest_user = CustomUser.objects.create(username=guest_user_name, is_guest_user="True", email=guest_user_email, first_name='User', last_name='Guest')
-    print guest_user.username
-
-    if guest_user and guest_user.is_active:
-        if guest_user.is_authenticated():
-            login(request, guest_user)
-            if next == "":
-                return HttpResponseRedirect('/home')
-            else:
-                return HttpResponseRedirect(next)
-
-    return render(request, 'login.html', {'error_message': 'New Guest session failed.'})
-
-
-def register_view(request):
-
-    logout(request)
-    extra_data = {}
-    next = ""
-    if request.GET:
-        next = request.GET['next']
-    error_message = ''
-    if request.POST:
-        print "new user"
-    return render(request, 'register_user.html', {'error_message': error_message, 'collapsed_sidebar': False})
\ No newline at end of file
index b4c0edc..eed9d96 100644 (file)
@@ -25,6 +25,10 @@ function exportMetricNs(url) {
     $('#modal_instance_export_metric').modal('show');
 }
 
+function showInstanceTopology(url) {
+    window.location.href = url;
+}
+
 function newAlarmNs(url) {
     $("#formAlarmNS").attr("action", url);
     $('#modal_instance_new_alarm').modal('show');
@@ -72,10 +76,17 @@ function showInstanceDetails(url_info) {
         dataType: "json",
         contentType: "application/json;charset=utf-8",
         success: function (result) {
-            editorJSON.setValue(JSON.stringify(result, null, "\t"));
-            editorJSON.setOption("autoRefresh", true);
-            dialog.modal('hide');
-            $('#modal_show_instance').modal('show');
+
+            if(result['data'] !== undefined) {
+                editorJSON.setValue(JSON.stringify(result['data'], null, "\t"));
+                editorJSON.setOption("autoRefresh", true);
+                dialog.modal('hide');
+                $('#modal_show_instance').modal('show');
+            }
+            else{
+                dialog.modal('hide');
+                bootbox.alert("An error occurred while retrieving the information.");
+            }
         },
         error: function (result) {
             dialog.modal('hide');
diff --git a/static/src/instancehandler/instance_topology_view.js b/static/src/instancehandler/instance_topology_view.js
new file mode 100644 (file)
index 0000000..f306443
--- /dev/null
@@ -0,0 +1,187 @@
+//GraphEditor instance
+var graph_editor = new dreamer.ModelGraphEditor();
+var selected_vnffgId = null;
+var show_all = null;
+
+// Enable Drop Action on the Graph
+initDropOnGraph();
+
+var type_view = {
+    "ns": ["vnf", "ns_vl"],
+    "vnf": ["vdu", "cp"]
+};
+
+var params = {
+        node: {
+            type: type_view['ns'],
+            group: []
+        },
+        link: {
+            group: [],
+            view: ['ns']
+        }
+    };
+$(document).ready(function() {
+
+    graph_editor.addListener("filters_changed", changeFilter);
+    graph_editor.addListener("refresh_graph_parameters", refreshGraphParameters);
+
+    console.log(osm_gui_properties)
+    // graph_editor initialization
+    graph_editor.init({
+        width: $('#graph_ed_container').width(),
+        height: $('#graph_ed_container').height(),
+        data_url: window.location.href,
+        desc_id: getUrlParameter('id'),
+        gui_properties: osm_gui_properties,
+        edit_mode: false,
+        behaviorsOnEvents:{
+            viewBased: false,
+            behaviors: buildBehaviorsOnEvents()
+        }
+    });
+    // this will filter in the different views, excluding the node types that are not listed in params
+    graph_editor.handleFiltersParams(params);
+
+});
+
+var filters = function(e, params) {
+    graph_editor.handleFiltersParams(params);
+    $('#' + e).nextAll('li').remove();
+}
+
+
+function initDropOnGraph() {
+
+    var dropZone = document.getElementById('graph_ed_container');
+    dropZone.ondrop = function(e) {
+        var group = graph_editor.getCurrentGroup()
+        e.preventDefault();
+        var elemet_id = e.dataTransfer.getData("text/plain");
+        var nodetype = $('#'+elemet_id).attr('type-name');
+        console.log(nodetype);
+        if (nodetype) {
+            var type_name = graph_editor.getTypeProperty()[nodetype].name;
+                $('#div_chose_id').show();
+                $('#input_choose_node_id').val(nodetype + "_" + generateUID());
+                $('#modal_chooser_title_add_node').text('Add ' + type_name);
+                $('#save_choose_node_id').off('click').on('click', function() {
+                    var name = $('#input_choose_node_id').val();
+                    var node_information = {
+                        'id': name,
+                        'info': {
+                            'type': nodetype,
+                            'group': [group],
+                            'desc_id': getUrlParameter('id'),
+                        },
+                        'x': e.layerX,
+                        'y': e.layerY
+                    }
+                    console.log(JSON.stringify(node_information))
+                    graph_editor.addNode(node_information, function() {
+                        $('#modal_choose_node_id').modal('hide');
+                    }, function(error){
+                        showAlert(error)
+                    });
+                });
+                $('#modal_choose_node_id').modal('show');
+
+
+        }
+
+    }
+
+    dropZone.ondragover = function(ev) {
+        console.log("ondragover");
+        return false;
+    }
+
+    dropZone.ondragleave = function() {
+        console.log("ondragleave");
+        return false;
+    }
+}
+
+function handleForce(el) {
+    if (el.id == "topology_play") {
+        $("#topology_pause").removeClass('active');
+        $("#topology_play").addClass('active');
+    } else {
+        $("#topology_pause").addClass('active');
+        $("#topology_play").removeClass('active');
+    }
+
+    graph_editor.handleForce((el.id == "topology_play") ? true : false);
+
+}
+
+function changeFilter(e, c) {
+
+    console.log("changeFilter", JSON.stringify(c));
+    //$("#title_header").text("OSHI Graph Editor");
+    //updateNodeDraggable({type_property: type_property, nodes_layer: graph_editor.getAvailableNodes()})
+    if(c)
+        new dreamer.GraphRequests().getAvailableNodes({layer: c.link.view[0]}, buildPalette, showAlert);
+
+}
+
+function refreshGraphParameters(e, graphParameters) {
+    var self = $(this);
+    if (graphParameters == null) return;
+
+}
+
+function resetFilters(){
+    graph_editor.handleFiltersParams(params);
+}
+
+function buildBehaviorsOnEvents() {
+    var self = this;
+    var contextmenuNodesAction = [{
+        title: 'Show info',
+        action: function (elm, d, i) {
+           // console.log('Show NodeInfo', elm, d, i);
+            var nodeData = {
+                "node": {
+                    "id": d.id
+                }
+            };
+        },
+        edit_mode: false
+
+    },
+        {
+            title: 'Explore',
+            action: function (elm, c_node, i) {
+                if (c_node.info.type != undefined) {
+                    var current_layer_nodes = Object.keys(graph_editor.model.layer[graph_editor.getCurrentView()].nodes);
+                    if (current_layer_nodes.indexOf(c_node.info.type) >= 0) {
+                        if (graph_editor.model.layer[graph_editor.getCurrentView()].nodes[c_node.info.type].expands) {
+                            var new_layer = graph_editor.model.layer[graph_editor.getCurrentView()].nodes[c_node.info.type].expands;
+                            graph_editor.handleFiltersParams({
+                                node: {
+                                    type: Object.keys(graph_editor.model.layer[new_layer].nodes),
+                                    group: [c_node.id]
+                                },
+                                link: {
+                                    group: [c_node.id],
+                                    view: [new_layer]
+                                }
+                            });
+
+                        }
+                        else {
+                            showAlert('This is not an explorable node.')
+                        }
+                    }
+                }
+            },
+            edit_mode: false
+        }];
+    var behavioursOnEvents = {
+        'nodes': contextmenuNodesAction
+
+    };
+
+    return behavioursOnEvents;
+}
\ No newline at end of file
diff --git a/static/src/osm_gui_properties.js b/static/src/osm_gui_properties.js
new file mode 100644 (file)
index 0000000..25a6aba
--- /dev/null
@@ -0,0 +1,50 @@
+var osm_gui_properties = {
+  "v1": {
+        "default": {
+            "shape": "cross",
+            "color": "#42f44e",
+            "label_color": "black",
+            "size": 15
+        },
+        "nodes": {
+            "ns_vl": {
+                "image": "vl-80.png",
+                // "shape": "triangle",
+                "color": "#196B90",
+                "size": 20,
+                "name": "VL"
+            },
+            "cp": {
+                "image": "cp-80.png",
+                // "shape": "circle",
+                "color": "#F27220",
+                "size": 20,
+                "name": "CP"
+            },
+            "vnf": {
+                "image": "vnf-100.png",
+                // "shape": "square",
+                "color": "#54A698",
+                "size": 35,
+                "name": "VNF"
+            },
+            "vnf_vl": {
+                "shape": "triangle",
+                //"color": "#5FC9DB",
+                "color": "#196B90",
+                "size": 11,
+                "name": "IntVL"
+            },
+
+            "vdu": {
+                "shape": "square",
+                //"color": "#50A7CC",
+                "color": "#54A698",
+                "size": 30,
+                "name": "VDU"
+            }
+        },
+        "graphs": null
+
+    }
+}
\ No newline at end of file
diff --git a/static/src/projecthandler/composer.js b/static/src/projecthandler/composer.js
new file mode 100644 (file)
index 0000000..8e1017a
--- /dev/null
@@ -0,0 +1,186 @@
+//GraphEditor instance
+var graph_editor = new dreamer.ModelGraphEditor();
+var selected_vnffgId = null;
+var show_all = null;
+
+// Enable Drop Action on the Graph
+initDropOnGraph();
+
+var type_view = {
+    "ns": ["vnf", "ns_vl"],
+    "vnf": ["vdu", "cp"]
+};
+
+var params = {
+        node: {
+            type: type_view['ns'],
+            group: []
+        },
+        link: {
+            group: [],
+            view: ['ns']
+        }
+    };
+$(document).ready(function() {
+
+    graph_editor.addListener("filters_changed", changeFilter);
+    graph_editor.addListener("refresh_graph_parameters", refreshGraphParameters);
+
+    console.log(osm_gui_properties)
+    // graph_editor initialization
+    graph_editor.init({
+        width: $('#graph_ed_container').width(),
+        height: $('#graph_ed_container').height(),
+        data_url: window.location.href,
+        desc_id: getUrlParameter('id'),
+        gui_properties: osm_gui_properties,
+        behaviorsOnEvents:{
+            viewBased: false,
+            behaviors: buildBehaviorsOnEvents()
+        }
+    });
+    // this will filter in the different views, excluding the node types that are not listed in params
+    graph_editor.handleFiltersParams(params);
+
+});
+
+var filters = function(e, params) {
+    graph_editor.handleFiltersParams(params);
+    $('#' + e).nextAll('li').remove();
+}
+
+
+function initDropOnGraph() {
+
+    var dropZone = document.getElementById('graph_ed_container');
+    dropZone.ondrop = function(e) {
+        var group = graph_editor.getCurrentGroup()
+        e.preventDefault();
+        var elemet_id = e.dataTransfer.getData("text/plain");
+        var nodetype = $('#'+elemet_id).attr('type-name');
+        console.log(nodetype);
+        if (nodetype) {
+            var type_name = graph_editor.getTypeProperty()[nodetype].name;
+                $('#div_chose_id').show();
+                $('#input_choose_node_id').val(nodetype + "_" + generateUID());
+                $('#modal_chooser_title_add_node').text('Add ' + type_name);
+                $('#save_choose_node_id').off('click').on('click', function() {
+                    var name = $('#input_choose_node_id').val();
+                    var node_information = {
+                        'id': name,
+                        'info': {
+                            'type': nodetype,
+                            'group': [group],
+                            'desc_id': getUrlParameter('id'),
+                        },
+                        'x': e.layerX,
+                        'y': e.layerY
+                    }
+                    console.log(JSON.stringify(node_information))
+                    graph_editor.addNode(node_information, function() {
+                        $('#modal_choose_node_id').modal('hide');
+                    }, function(error){
+                        showAlert(error)
+                    });
+                });
+                $('#modal_choose_node_id').modal('show');
+
+
+        }
+
+    }
+
+    dropZone.ondragover = function(ev) {
+        console.log("ondragover");
+        return false;
+    }
+
+    dropZone.ondragleave = function() {
+        console.log("ondragleave");
+        return false;
+    }
+}
+
+function handleForce(el) {
+    if (el.id == "topology_play") {
+        $("#topology_pause").removeClass('active');
+        $("#topology_play").addClass('active');
+    } else {
+        $("#topology_pause").addClass('active');
+        $("#topology_play").removeClass('active');
+    }
+
+    graph_editor.handleForce((el.id == "topology_play") ? true : false);
+
+}
+
+function changeFilter(e, c) {
+
+    console.log("changeFilter", JSON.stringify(c));
+    //$("#title_header").text("OSHI Graph Editor");
+    //updateNodeDraggable({type_property: type_property, nodes_layer: graph_editor.getAvailableNodes()})
+    if(c)
+        new dreamer.GraphRequests().getAvailableNodes({layer: c.link.view[0]}, buildPalette, showAlert);
+
+}
+
+function refreshGraphParameters(e, graphParameters) {
+    var self = $(this);
+    if (graphParameters == null) return;
+
+}
+
+function resetFilters(){
+    graph_editor.handleFiltersParams(params);
+}
+
+function buildBehaviorsOnEvents() {
+    var self = this;
+    var contextmenuNodesAction = [{
+        title: 'Show info',
+        action: function (elm, d, i) {
+           // console.log('Show NodeInfo', elm, d, i);
+            var nodeData = {
+                "node": {
+                    "id": d.id
+                }
+            };
+        },
+        edit_mode: false
+
+    },
+        {
+            title: 'Explore',
+            action: function (elm, c_node, i) {
+                if (c_node.info.type != undefined) {
+                    var current_layer_nodes = Object.keys(graph_editor.model.layer[graph_editor.getCurrentView()].nodes);
+                    if (current_layer_nodes.indexOf(c_node.info.type) >= 0) {
+                        if (graph_editor.model.layer[graph_editor.getCurrentView()].nodes[c_node.info.type].expands) {
+                            var new_layer = graph_editor.model.layer[graph_editor.getCurrentView()].nodes[c_node.info.type].expands;
+                            graph_editor.handleFiltersParams({
+                                node: {
+                                    type: Object.keys(graph_editor.model.layer[new_layer].nodes),
+                                    group: [c_node.id]
+                                },
+                                link: {
+                                    group: [c_node.id],
+                                    view: [new_layer]
+                                }
+                            });
+
+                        }
+                        else {
+                            showAlert('This is not an explorable node.')
+                        }
+                    }
+                }
+            },
+            edit_mode: false
+        }];
+    var behavioursOnEvents = {
+        'nodes': contextmenuNodesAction
+
+    };
+
+    return behavioursOnEvents;
+}
\ No newline at end of file
index 24b7ba5..7fe1966 100644 (file)
@@ -1,19 +1,19 @@
-function deletePackage(project_id, descriptor_type, package_id) {
+function deletePackage(descriptor_type, package_id) {
     bootbox.confirm("Are you sure want to delete?", function (result) {
         if (result) {
-            location.href = '/projects/' + project_id + '/descriptors/' + descriptor_type + '/' + package_id + '/delete'
+            location.href = '/projects/descriptors/' + descriptor_type + '/' + package_id + '/delete'
         }
     })
 }
 
 
-function openPackageContentList(project_id, type, pkg_id) {
+function openPackageContentList(type, pkg_id) {
     var dialog = bootbox.dialog({
         message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
         closeButton: true
     });
     $.ajax({
-        url: '/projects/' + project_id + '/descriptors/' + type + '/' + pkg_id + '/action/get_package_files_list',
+        url: '/projects/descriptors/' + type + '/' + pkg_id + '/action/get_package_files_list',
         type: 'GET',
         dataType: "json",
         contentType: "application/json;charset=utf-8",
index 072129f..5ee3522 100644 (file)
@@ -187,8 +187,8 @@ function updateBredCrumb(filter_parameters){
 }
 
 
-function openEditor(project_id) {
-    window.location.href = '/projects/' + project_id + '/descriptors/' + graph_editor.getCurrentView() + 'd/' + graph_editor.getCurrentGroup();
+function openEditor() {
+    window.location.href = '/projects/descriptors/' + graph_editor.getCurrentView() + 'd/' + graph_editor.getCurrentGroup();
 }
 
 
index 8069474..606da3a 100644 (file)
@@ -1,19 +1,19 @@
-function deleteSDN(project_id, sdn_uuid) {
+function deleteSDN(sdn_uuid) {
     bootbox.confirm("Are you sure want to delete?", function (result) {
         if (result) {
-            location.href = '/projects/' + project_id + '/sdn/' + sdn_uuid + '/delete'
+            location.href = '/projects/sdn/' + sdn_uuid + '/delete'
         }
     })
 }
 
-function showSDN(project_id, sdn_uuid) {
+function showSDN(sdn_uuid) {
     var dialog = bootbox.dialog({
         message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
         closeButton: true
     });
 
     $.ajax({
-        url: '/projects/' + project_id + '/sdn/' + sdn_uuid ,
+        url: '/projects/sdn/' + sdn_uuid ,
         //url: '/sdn/' + sdn_uuid,
         type: 'GET',
         dataType: "json",
index 6d5e820..83b580c 100644 (file)
@@ -7,9 +7,9 @@ function openProject(pId) {
 }
 
 
-function openDescriptorView(project_id, descriptor_type, descriptor_id) {
-    console.log("openDescriptorView", project_id, descriptor_type, descriptor_id);
-    window.location.href = '/projects/' + project_id + '/descriptors/' + descriptor_type + '/' + descriptor_id;
+function openDescriptorView( descriptor_type, descriptor_id) {
+    console.log("openDescriptorView", descriptor_type, descriptor_id);
+    window.location.href = '/projects/descriptors/' + descriptor_type + '/' + descriptor_id;
 
 }
 
index 36e7c8e..8343f05 100755 (executable)
@@ -184,7 +184,7 @@ dreamer.GraphEditor = (function (global) {
         this.container = chart.parent();
         $(window).on("resize", function() {
 
-            var palette_width = $("#palette").width()
+            var palette_width = ($("#palette").length > 0) ? $("#palette").width() : 0;
             var working_width = self.container.width() - palette_width;
             self.width = (working_width < 0) ? 0 : working_width;
             self.height = self.container.height();
@@ -197,7 +197,7 @@ dreamer.GraphEditor = (function (global) {
 
     GraphEditor.prototype.get_d3_symbol =
         function (myString) {
-            log(myString)
+
             switch (myString) {
             case "circle":
                 return d3.symbolCircle;
@@ -227,7 +227,6 @@ dreamer.GraphEditor = (function (global) {
 
      GraphEditor.prototype.get_name_from_d3_symbol =
         function (mySymbol) {
-            //log(myString)
             switch (mySymbol) {
             case d3.symbolCircle:
                 return "circle";
@@ -372,7 +371,7 @@ dreamer.GraphEditor = (function (global) {
      * @returns {boolean}
      */
     GraphEditor.prototype.addLink = function (link) {
-        console.log(JSON.stringify(link))
+        console.log("addLink" + JSON.stringify(link))
         if (link.source && link.target) {
             this.force.stop();
             this.cleanAll();
@@ -741,6 +740,7 @@ dreamer.GraphEditor = (function (global) {
                     return 80
                 })
                 .type(function (d) {
+                    console.log("popiup")
                     return (self.get_d3_symbol());
                 })
             )
@@ -948,7 +948,7 @@ dreamer.GraphEditor = (function (global) {
                     if (self.lastKeyDown == SHIFT_BUTTON && self._selected_node != undefined) {
                         var source_id = self._selected_node.id;
                         var target_id = d.id;
-                        log(JSON.stringify(self.filter_parameters.link.view));
+                        log("--" + JSON.stringify(self.filter_parameters.link.view));
                         var new_link = {
                             source: source_id,
                             target: target_id,
@@ -1036,7 +1036,7 @@ dreamer.GraphEditor = (function (global) {
      */
     GraphEditor.prototype.resizeSvg = function (width, height) {
         log("resizeSvg");
-        log(event);
+        //log(event);
         this.width = width || this.width;
         this.height = height || this.height;
         this.svg.attr('width', width);
index 3c275dd..be092a4 100644 (file)
@@ -56,6 +56,7 @@ dreamer.ModelGraphEditor = (function (global) {
         this._edit_mode = (args.edit_mode != undefined) ? args.edit_mode : this._edit_mode;
 
         Object.keys(args.gui_properties["nodes"]).forEach(function (key, index) {
+            console.log(key + " ####")
             this.type_property[key] = args.gui_properties["nodes"][key];
             if ( this.type_property[key]['property'] != undefined){
                 for(var c_prop in this.type_property[key]){
@@ -69,6 +70,7 @@ dreamer.ModelGraphEditor = (function (global) {
                 }
             }
             else{
+
                 this.type_property[key]["shape"] = this.parent.get_d3_symbol(this.type_property[key]["shape"]);
                 if (this.type_property[key]["image"] != undefined) {
                     this.type_property[key]["image"] = IMAGE_PATH + this.type_property[key]["image"];
@@ -331,7 +333,7 @@ dreamer.ModelGraphEditor = (function (global) {
     ModelGraphEditor.prototype.savePositions = function (data) {
         var vertices = {}
         this.node.each(function (d) {
-            vertices[d.id] = {}
+            vertices[d.id] = {};
             vertices[d.id]['x'] = d.x;
             vertices[d.id]['y'] = d.y;
         });
@@ -339,7 +341,7 @@ dreamer.ModelGraphEditor = (function (global) {
             'vertices': vertices
         });
 
-    }
+    };
 
     /**
      *  Internal functions
@@ -376,7 +378,7 @@ dreamer.ModelGraphEditor = (function (global) {
                     self.removeNode(d, null, showAlert);
                 },
                 edit_mode: true
-            },
+            }
 
         ];
         if(this.customBehavioursOnEvents){
index c5f8baa..e33a6a9 100644 (file)
@@ -21,6 +21,8 @@
 
     <button id="topology_info_button" type="button" title="Info keyboard" class="btn btn-default" data-toggle="modal"
             data-target="#modalTopologyInfoButton"><i class="fa fa-keyboard-o"></i></button>
+<button id="reset_filter" type="button" class="btn btn btn-default" onclick="resetFilters(this)"><i
+            class="fa fa-backward"></i></button>
 </div>
 {% block boxes_toolbar %}
 
diff --git a/template/topology_toolbar_instance.html b/template/topology_toolbar_instance.html
new file mode 100644 (file)
index 0000000..be42390
--- /dev/null
@@ -0,0 +1,21 @@
+<div class="btn-group-vertical left-tool-bar-monitoring">
+
+    <!-- <button id="topology_zoom_plus" type="button" class="btn btn-default"><i class="fa fa-plus"></i></button> -->
+    <!-- <button id="topology_zoom_minus" type="button" class="btn btn-default"><i class="fa fa-minus"></i></button> -->
+
+    <button id="topology_play" type="button" class="btn btn btn-default" onclick="handleForce(this)"><i
+            class="fa fa-play"></i></button>
+    <button id="topology_pause" type="button" class="btn btn btn-default active" onclick="handleForce(this)"><i
+            class="fa fa-pause"></i></button>
+    <button id="reset_filter" type="button" class="btn btn btn-default" onclick="resetFilters(this)"><i
+            class="fa fa-backward"></i></button>
+    {% block topology_toolbar_buttons %}
+
+    {% endblock %}
+
+
+</div>
+{% block boxes_toolbar %}
+
+{% endblock %}
+
index 4368735..187dc87 100644 (file)
@@ -19,7 +19,7 @@
 
 {% block breadcrumb_body %}
     {{ block.super }}
-    <li><a href="{% url 'projects:vims:list' project_id=project_id %}">VIMS</a></li>
+    <li><a href="{% url 'projects:vims:list'  %}">VIMS</a></li>
 {% endblock %}
 
 {% block content_body %}
@@ -27,7 +27,7 @@
 
     <div class="row">
         <div class="col-md-12">
-            <form action='{% url "projects:vims:create" project_id=project_id  %}' method="post">
+            <form action='{% url "projects:vims:create"   %}' method="post">
                 {% csrf_token %}
                 <div class="box">
                     <div class="box-header with-border">
 
                     </div>
                     <div class="box-footer">
-                        <button onclick="location.href='{% url 'projects:vims:list' project_id=project_id%}'" class="btn btn-default pull-left">Back to
+                        <button onclick="location.href='{% url 'projects:vims:list' %}'" class="btn btn-default pull-left">Back to
                             VIM Accounts
                         </button>
                         <button class="btn btn-primary pull-right">Create</button>
index 0729e00..535f4db 100644 (file)
@@ -19,7 +19,7 @@
 
 {% block breadcrumb_body %}
     {{ block.super }}
-    <li><a href="{% url "projects:vims:list"  project_id=project_id %}">VIMS</a></li>
+    <li><a href="{% url "projects:vims:list"   %}">VIMS</a></li>
 {% endblock %}
 
 {% block content_body %}
@@ -33,7 +33,7 @@
                 <div class="box-header with-border">
                     <h3 class="box-title">Registered VIM</h3>
                     <div class="box-tools">
-                        <a href='{% url "projects:vims:create"  project_id=project_id %}' class="btn btn-block btn-primary btn-sm"><i
+                        <a href='{% url "projects:vims:create"   %}' class="btn btn-block btn-primary btn-sm"><i
                                 class="fa fa-plus"></i><span> New VIM</span></a>
                     </div>
                 </div>
                                 <td>
                                     <div class="btn-group">
                                         <button type="button" class="btn btn-default"
-                                                onclick="location.href='{% url "projects:vims:show"  project_id=project_id vim_id=p|get:"_id" %}'" data-toggle="tooltip" data-placement="top" data-container="body" title="Show Info"><i
+                                                onclick="location.href='{% url "projects:vims:show"   vim_id=p|get:"_id" %}'" data-toggle="tooltip" data-placement="top" data-container="body" title="Show Info"><i
                                                 class="fa fa-info"></i></button>
                                         <button type="button" class="btn btn-default"
-                                                onclick="javascript:deleteVim('{% url "projects:vims:delete"  project_id=project_id vim_id=p|get:"_id" %}')" data-toggle="tooltip" data-placement="top" data-container="body" title="Delete"><i
+                                                onclick="javascript:deleteVim('{% url "projects:vims:delete"   vim_id=p|get:"_id" %}')" data-toggle="tooltip" data-placement="top" data-container="body" title="Delete"><i
                                                 class="far fa-trash-alt" ></i></button>
                                     </div>
                                 </td>
index 74e816a..13613de 100644 (file)
@@ -18,7 +18,7 @@
 
 {% block breadcrumb_body %}
     {{ block.super }}
-    <li><a href="{% url 'projects:vims:list' project_id=project_id%}">VIMS</a></li>
+    <li><a href="{% url 'projects:vims:list' %}">VIMS</a></li>
 {% endblock %}
 
 {% block content_body %}
             </div>
             <div class="box-footer">
                 <div class="">
-                    <button onclick="location.href='{% url 'projects:vims:list' project_id=project_id%}'" class="btn btn-primary">Back to VIM Accounts</button>
+                    <button onclick="location.href='{% url 'projects:vims:list' %}'" class="btn btn-primary">Back to VIM Accounts</button>
                 </div>
             </div>
         </div>
index abaab9c..bf88c11 100644 (file)
@@ -18,8 +18,8 @@ from django.shortcuts import render, redirect
 from django.contrib.auth.decorators import login_required
 from django.http import HttpResponse
 import json
-#from lib.osm.osmclient.client import Client
 from lib.osm.osmclient.clientv2 import Client
+import authosm.utils as osmutils
 import yaml
 import logging
 
@@ -28,9 +28,11 @@ log = logging.getLogger('vimhandler.py')
 
 
 @login_required
-def list(request, project_id):
+def list(request):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     client = Client()
-    result = client.vim_list(request.session['token'])
+    result = client.vim_list(user.get_token())
     print result
     result = {
         "project_id": project_id,
@@ -40,7 +42,9 @@ def list(request, project_id):
 
 
 @login_required
-def create(request, project_id):
+def create(request):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     result = {'project_id': project_id}
     if request.method == 'GET':
         return __response_handler(request, result, 'vim_create.html')
@@ -70,23 +74,26 @@ def create(request, project_id):
             except Exception as e:
                 # TODO return error on json.loads exception
                 print e
-        result = client.vim_create(request.session['token'], vim_data)
+        result = client.vim_create(user.get_token(), vim_data)
         # TODO  'vim:show', to_redirect=True, vim_id=vim_id
-        return __response_handler(request, result, 'projects:vims:list', to_redirect=True, project_id=project_id)
+        return __response_handler(request, result, 'projects:vims:list', to_redirect=True, )
 
 @login_required
-def delete(request, project_id, vim_id=None):
+def delete(request, vim_id=None):
+    user = osmutils.get_user(request)
     try:
         client = Client()
-        del_res = client.vim_delete(request.session['token'], vim_id)
+        del_res = client.vim_delete(user.get_token(), vim_id)
     except Exception as e:
         log.exception(e)
-    return __response_handler(request, {}, 'projects:vims:list', to_redirect=True, project_id=project_id)
+    return __response_handler(request, {}, 'projects:vims:list', to_redirect=True, )
 
 @login_required
-def show(request, project_id, vim_id=None):
+def show(request, vim_id=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
     client = Client()
-    result = client.vim_get(request.session['token'], vim_id)
+    result = client.vim_get(user.get_token(), vim_id)
     print result
     if isinstance(result, dict) and 'error' in result and result['error']:
         return render(request, 'error.html')