improved role management 94/7694/1
authorlombardofr <lombardo@everyup.it>
Fri, 21 Jun 2019 17:35:14 +0000 (19:35 +0200)
committerlombardofr <lombardo@everyup.it>
Fri, 21 Jun 2019 17:35:14 +0000 (19:35 +0200)
Change-Id: Iaf87385269b2195ba964a951939deca6be938013
Signed-off-by: lombardofr <lombardo@everyup.it>
authosm/views.py
instancehandler/views.py
projecthandler/osm_model.py
rolehandler/templates/modal/role_create.html
rolehandler/templates/modal/role_edit.html
rolehandler/templates/role_list.html
rolehandler/urls.py
rolehandler/views.py
static/src/rolehandler/role_list.js
vimhandler/views.py

index f82f4dd..2cfe043 100644 (file)
@@ -26,8 +26,7 @@ def user_login(request):
 
     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')
         try:
index edf0da1..cf88f99 100644 (file)
@@ -167,7 +167,7 @@ def create(request, type=None):
         except Exception as e:
             return __response_handler(request, {'status': 400, 'code': 'BAD_REQUEST', 'detail': e.message} , url=None, status=400)
         result = client.ns_create(user.get_token(), ns_data)
-        print result
+        
         if result['error']:
             return __response_handler(request, result['data'], url=None,
                                   status=result['data']['status'] if 'status' in result['data'] else 500)
index 1775797..718c08d 100644 (file)
@@ -56,11 +56,10 @@ class OsmProject(object):
             client = Client()
             if type_descriptor == 'nsd':
                 result = client.nsd_get(descriptor_id)
-                print result
+                
             elif type_descriptor == 'vnfd':
                 result = client.vnfd_get(descriptor_id)
 
-                print result
         except Exception as e:
             log.exception(e)
             result = {}
@@ -175,11 +174,11 @@ class OsmProject(object):
             else:
                 return False
             result = yaml.load(result)
-            print result
+            
         except Exception as e:
             log.exception(e)
             result = False
-        print result
+        
         return result
 
     def get_add_element(self, request):
@@ -215,7 +214,6 @@ class OsmProject(object):
         except Exception as e:
             log.exception(e)
             result = False
-        print result
         return result
 
     @staticmethod
@@ -232,5 +230,4 @@ class OsmProject(object):
         except Exception as e:
             log.exception(e)
             result = False
-        print result
         return result
\ No newline at end of file
index 58d68ca..d8282a7 100644 (file)
                             <input class="form-control" id="rolename" name="name"
                                    placeholder="Name" required>
                         </div>
+                       
+                    </div>
+                    <div class="form-group">
+                        <div class="col-sm-6">
+                                <div class="checkbox">
+                                        <label><input type="checkbox" id="create_root" name="root"> Root</label>
+                                    </div>
+                        </div>
+                    </div>
+                    <div class="form-group">
+                        <label for="definition" class="col-sm-3 control-label">Definition </label>
+                        <div class="col-sm-6">
+                            <textarea class="form-control" id="definition" name="definition" placeholder="Yaml definition"
+                                      rows="3"></textarea>
+                        </div>
                     </div>
-
-            
 
                 </div>
                 <div class="modal-footer">
index 8541177..ca3c4c0 100644 (file)
                 <div class="modal-body" id="modal_edit_role_body">
                     
                     <div class="form-group">
-                        <label for="name" class="col-sm-3 control-label">Name</label>
+                        <label for="rolename" class="col-sm-3 control-label">Name *</label>
                         <div class="col-sm-6">
-                           <input class="form-control" id="edit_role_name" name="role" 
-                                   placeholder="Name">
+                            <input class="form-control" type="text" id="edit_rolename" name="name"
+                                       placeholder="Name" required>
+                        </div>
+                        
+                    </div>
+                    <div class="form-group">
+                            <div class="col-sm-6">
+                                    <div class="checkbox">
+                                            <label><input type="checkbox" id="edit_root" name="root"> Root</label>
+                                        </div>
+                            </div>
+                        </div>
+                        
+                    <div class="form-group">
+                        <label for="definition" class="col-sm-3 control-label">Definition </label>
+                        <div class="col-sm-6">
+                            <textarea class="form-control" id="edit_definition" name="definition" placeholder="Yaml definition"
+                                      rows="3"></textarea>
                         </div>
                     </div>
                    
index 5cf49a1..bfc7566 100644 (file)
@@ -19,7 +19,7 @@
 
 {% block breadcrumb_body %}
     {{ block.super }}
-    <li><a href="#">roles</a></li>
+    <li><a href="#">Roles</a></li>
 {% endblock %}
 
 {% block content_body %}
 
             <div class="box">
                 <div class="box-header with-border">
-                    <h3 class="box-title">roles</h3>
+                    <h3 class="box-title">Roles</h3>
                     <div class="box-tools">
                         <button type="button" class="btn btn-default" data-container="body"
-                                onclick="javascript:openModalCreateRole({'projects_list_url': '{% url "projects:projects_list" %}'})"
+                                onclick="javascript:openModalCreateRole()"
                                 data-toggle="tooltip" data-placement="top" title="New role">
 
                             <i class="fa fa-plus"></i> Create role
                                 'data-toggle="dropdown" aria-expanded="false">Actions ' +
                                 '<span class="fa fa-caret-down"></span></button> ' +
                                 '<ul class="dropdown-menu">' +
-                                '<li> <a href="#" onclick="javascript:openModalEditRole({role_id:\'' + row['_id'] + '\', rolename:\'' + row['rolename'] + '\'})">' +
+                                '<li> <a href="#" onclick="javascript:openModalEditRole({role_id:\'' + row['_id'] + '\'})">' +
                                 '<i class="fa fa-edit"></i> Edit</a></li>' +
-                                '<li> <a href="#" onclick="javascript:deleteRole(\'' + row['_id'] + '\', \'' + row['rolename'] + '\')"' +
+                                '<li> <a href="#" onclick="javascript:deleteRole(\'' + row['_id'] + '\', \'' + row['name'] + '\')"' +
                                 'style="color:red"><i class="fa fa-trash"></i> Delete</a></li> </ul></div>';
                         },
                         "targets": 4,
                     table.ajax.reload();
                     bootbox.alert({
                         title: "Result",
-                        message: "role successfully modified."
+                        message: "Role successfully modified."
                     });
 
                 }).fail(function (result) {
index c37325d..64d7ab1 100644 (file)
@@ -20,7 +20,8 @@ from rolehandler import views
 urlpatterns = [
     url(r'^list$', views.role_list, name='list'),
     url(r'^create$', views.create, name='create'),
-    url(r'^(?P<user_id>[0-9a-zA-Z]+)/delete$', views.delete, name='delete'),
-    url(r'^(?P<user_id>[0-9a-zA-Z]+)', views.update, name='update')
+    url(r'^(?P<role_id>[0-9a-zA-Z]+)/delete$', views.delete, name='delete'),
+    url(r'^(?P<role_id>[0-9a-zA-Z]+)/update$', views.update, name='update'),
+    url(r'^(?P<role_id>[0-9a-zA-Z]+)$', views.get, name='get')
 
 ]
index f6a0799..a13e28d 100644 (file)
@@ -17,6 +17,7 @@
 from django.shortcuts import render, redirect
 from sf_t3d.decorators import login_required
 from django.http import HttpResponse
+import yaml
 import json
 import logging
 import authosm.utils as osmutils
@@ -42,8 +43,21 @@ def create(request):
     user = osmutils.get_user(request)
     client = Client()
     role_data ={
-       'name'
+       'name': request.POST['name'],
+       'root': True if request.POST.get('root') else False
     }
+    try:
+        if 'definition' in request.POST and request.POST.get('definition') != '':
+            role_definition = yaml.load(request.POST.get('definition'))
+
+            if not isinstance(role_definition, dict):
+                    raise ValueError('Role definition should be provided in a key-value fashion')
+            for key, value in role_definition.items():
+                if not isinstance(value, bool):
+                    raise ValueError('Value in a role definition should be boolean')
+                role_data[key] = value
+    except Exception as e:
+        return __response_handler(request, {'status': 400, 'code': 'BAD_REQUEST', 'detail': e.message} , url=None, status=400)
     result = client.role_create(user.get_token(), role_data)
     if result['error']:
         return __response_handler(request, result['data'], url=None,
@@ -69,21 +83,53 @@ def delete(request, role_id=None):
 
 @login_required
 def update(request, role_id=None):
+    user = osmutils.get_user(request)
+    client = Client()
+    payload = {
+        '_id': role_id,
+        'name': request.POST['name'],
+        'root': True if request.POST.get('root') else False
+    }
+    try:
+        if 'definition' in request.POST and request.POST.get('definition') != '':
+            role_definition = yaml.load(request.POST.get('definition'))
+
+            if not isinstance(role_definition, dict):
+                    raise ValueError('Role definition should be provided in a key-value fashion')
+            for key, value in role_definition.items():
+                if not isinstance(value, bool):
+                    raise ValueError('Value in a role definition should be boolean')
+                payload[key] = value
+    except Exception as e:
+        return __response_handler(request, {'status': 400, 'code': 'BAD_REQUEST', 'detail': e.message} , url=None, status=400)
+    result = client.role_update(user.get_token(), role_id, payload)
+    if result['error']:
+        return __response_handler(request, result['data'], url=None,
+                                  status=result['data']['status'] if 'status' in result['data'] else 500)
+    else:
+        return __response_handler(request, {}, url=None, status=200)
+
+@login_required
+def get(request, role_id=None):
     user = osmutils.get_user(request)
     try:
         client = Client()
-        payload = {}
-        if request.POST.get('name') and request.POST.get('name') is not '':
-            payload["name"] = request.POST.get('name')
-        update_res = client.role_update(user.get_token(), role_id, payload)
+        get_res = client.role_get(user.get_token(), role_id)
     except Exception as e:
         log.exception(e)
-        update_res = {'error': True, 'data': str(e)}
-    if update_res['error']:
-        return __response_handler(request, update_res['data'], url=None,
-                                  status=update_res['data']['status'] if 'status' in update_res['data'] else 500)
+        get_res = {'error': True, 'data': str(e)}
+    if get_res['error']:
+        return __response_handler(request, get_res['data'], url=None,
+                                  status=get_res['data']['status'] if 'status' in get_res['data'] else 500)
     else:
-        return __response_handler(request, {}, url=None, status=200)
+        role = get_res['data']
+        result = {
+            '_id': role['_id'],
+            'name': role['name'],
+            'root': role['root'],
+            'definition': { key:value for key, value in role.items() if key not in ['_id', 'name', 'root', '_admin'] }
+        }
+        return __response_handler(request, result, url=None, status=200)
 
 
 def __response_handler(request, data_res, url=None, to_redirect=None, *args, **kwargs):
index fc19f52..5145a04 100644 (file)
 
 function openModalCreateRole(args) {
 
-    
-
     $('#modal_new_role').modal('show');
 }
 
 function openModalEditRole(args) {
     var url = '/admin/roles/' + args.role_id;
+    var url_update = '/admin/roles/' + args.role_id+'/update';
+    var dialog = bootbox.dialog({
+        message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
+        closeButton: false
+    });
+    $.ajax({
+        url: url,
+        type: 'GET',
+        headers: {
+            "Accept": 'application/json'
+        },
+        contentType: false,
+        processData: false
+    })
+    .done(function (response,textStatus, jqXHR) {
+        dialog.modal('hide');
+        $("#formEditRole").attr("action", url_update);
+        $('#modal_edit_role').modal('show');
+        $('#edit_rolename').val(response['name'])
+        $('#edit_definition').val(JSON.stringify(response['definition']))
+        if(response['root'] === true){
+            $("#edit_root").attr("checked", true);
+        }
+        else {
+            $("#edit_root").attr("checked", false);
+        }
+    }).fail(function(result){
+        dialog.modal('hide');
+        var data  = result.responseJSON;
+        var title = "Error " + (data.code ? data.code: 'unknown');
+        var message = data.detail ? data.detail: 'No detail available.';
+        bootbox.alert({
+            title: title,
+            message: message
+        });
+    });
     
-    $("#formEditRole").attr("action", url);
-    
-
-    $('#modal_edit_role').modal('show');
 }
 
 function deleteRole(role_id, name) {
@@ -40,17 +70,31 @@ function deleteRole(role_id, name) {
             });
             $.ajax({
                 url: delete_url,
-                dataType: "json",
-                contentType: "application/json;charset=utf-8",
-                success: function (result) {
-                    //$('#modal_show_vim_body').empty();
-                    dialog.modal('hide');
-                    table.ajax.reload();
+                type: 'GET',
+                headers: {
+                    "Accept": 'application/json'
                 },
-                error: function (result) {
-                    dialog.modal('hide');
-                    bootbox.alert("An error occurred.");
-                }
+                contentType: false,
+                processData: false
+            })
+            .done(function (response,textStatus, jqXHR) {
+                bootbox.alert({
+                    title: "Result",
+                    message: "Role deleted.",
+                    callback: function () {
+                        dialog.modal('hide');
+                        table.ajax.reload();
+                    }
+                });
+            }).fail(function(result){
+                dialog.modal('hide');
+                var data  = result.responseJSON;
+                var title = "Error " + (data.code ? data.code: 'unknown');
+                var message = data.detail ? data.detail: 'No detail available.';
+                bootbox.alert({
+                    title: title,
+                    message: message
+                });
             });
         }
     })
index d16fb7e..2a0d07e 100644 (file)
@@ -94,7 +94,6 @@ def show(request, vim_id=None):
     project_id = user.project_id
     client = Client()
     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')