fix on users and projects 92/7592/2
authorlombardofr <lombardo@everyup.it>
Sun, 2 Jun 2019 15:18:48 +0000 (17:18 +0200)
committerlombardofr <lombardo@everyup.it>
Sun, 2 Jun 2019 15:57:49 +0000 (17:57 +0200)
Change-Id: Ibb4258095eca92685e76187b66fca003f834dc6e
Signed-off-by: lombardofr <lombardo@everyup.it>
19 files changed:
build-debpkg.sh
lib/osm/osmclient/clientv2.py
projecthandler/template/project/osm/osm_project_left_sidebar.html
projecthandler/template/project/projectlist.html
rolehandler/__init__.py [new file with mode: 0644]
rolehandler/apps.py [new file with mode: 0644]
rolehandler/migrations/__init__.py [new file with mode: 0644]
rolehandler/models.py [new file with mode: 0644]
rolehandler/templates/modal/role_create.html [new file with mode: 0644]
rolehandler/templates/modal/role_edit.html [new file with mode: 0644]
rolehandler/templates/role_list.html [new file with mode: 0644]
rolehandler/urls.py [new file with mode: 0644]
rolehandler/views.py [new file with mode: 0644]
sf_t3d/settings.py
sf_t3d/urls.py
static/src/rolehandler/role_list.js [new file with mode: 0644]
userhandler/templates/modal/user_edit.html
userhandler/urls.py
userhandler/views.py

index 19565e1..607bfe5 100755 (executable)
@@ -15,7 +15,7 @@
 #    under the License.
 
 
-PKG_DIRECTORIES="authosm descriptorhandler instancehandler lib projecthandler sdnctrlhandler sf_t3d static template userhandler vimhandler packagehandler netslicehandler wimhandler"
+PKG_DIRECTORIES="authosm descriptorhandler instancehandler lib projecthandler sdnctrlhandler sf_t3d static template userhandler vimhandler packagehandler netslicehandler wimhandler rolehandler"
 PKG_FILES="bower.json django.ini LICENSE manage.py nginx-app.conf README.md requirements.txt supervisor-app.conf .bowerrc entrypoint.sh"
 MDG_NAME=lightui
 DEB_INSTALL=debian/osm-${MDG_NAME}.install
index 52e20b7..384eeaa 100644 (file)
@@ -73,6 +73,97 @@ class Client(object):
 
         return result
 
+    def role_list(self, token):
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/json", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+
+        _url = "{0}/admin/v1/roles".format(self._base_path)
+        try:
+            r = requests.get(_url, params=None, verify=False, stream=True, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code in (200, 201, 202, 204):
+            result['error'] = False
+        result['data'] = Util.json_loads_byteified(r.text)
+
+        return result
+
+    def role_create(self, token, role_data):
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/json", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+        _url = "{0}/admin/v1/roles".format(self._base_path)
+
+        try:
+            r = requests.post(_url, json=role_data, verify=False, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code in (200, 201, 202, 204):
+            result['error'] = False
+        result['data'] = Util.json_loads_byteified(r.text)
+        return result
+
+    def role_update(self, token, role_id, role_data):
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/json", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+        _url = "{0}/admin/v1/roles/{1}".format(self._base_path, role_id)
+        
+        try:
+            r = requests.patch(_url, json=role_data, verify=False, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code in (200, 201, 202, 204):
+            result['error'] = False
+        else:
+            result['data'] = Util.json_loads_byteified(r.text)
+        return result
+    
+    def role_delete(self, token, id, force=None):
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/json", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+        query_path = ''
+        if force:
+            query_path = '?FORCE=true'
+        _url = "{0}/admin/v1/roles/{1}{2}".format(self._base_path, id, query_path)
+        try:
+            r = requests.delete(_url, params=None, verify=False, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code in (200, 201, 202, 204):
+            result['error'] = False
+        else:
+            result['data'] = Util.json_loads_byteified(r.text)
+        return result
+
+    def role_get(self, token, id):
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/json", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+        
+        _url = "{0}/admin/v1/roles/{1}".format(self._base_path, id)
+        try:
+            r = requests.delete(_url, params=None, verify=False, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code in (200, 201, 202, 204):
+            result['error'] = False
+        else:
+            result['data'] = Util.json_loads_byteified(r.text)
+        return result
+
     def user_list(self, token):
         result = {'error': True, 'data': ''}
         headers = {"Content-Type": "application/json", "accept": "application/json",
@@ -230,7 +321,6 @@ class Client(object):
             return result
         if r.status_code in (200, 201, 202, 204):
             result['error'] = False
-        result['data'] = Util.json_loads_byteified(r.text)
         return result
 
     def project_delete(self, token, id):
index 7067ca7..7259834 100644 (file)
             </li>
             {% if user.is_admin %}
                 <li class="header">ADMIN</li>
+                {% url "projects:projects_list"   as  proj_list_url %}
+                <li {% if request.get_full_path == proj_list_url %} class="active" {% endif %}>
+                <a href='{% url "projects:projects_list"   %}'>
+                    <i class="fas fa-folder"></i> <span>Projects</span>
+                </a>
+                </li>
                 {% url "users:list"   as  user_list_url %}
                 <li {% if request.get_full_path == user_list_url %} class="active" {% endif %}>
                 <a href='{% url "users:list"   %}'>
                     <i class="fas fa-users"></i> <span>Users</span>
                 </a>
                 </li>
-                {% url "projects:projects_list"   as  proj_list_url %}
-                <li {% if request.get_full_path == proj_list_url %} class="active" {% endif %}>
-                <a href='{% url "projects:projects_list"   %}'>
-                    <i class="fas fa-folder"></i> <span>Projects</span>
+                {%comment%}
+                {% url "roles:list"   as  role_list_url %}
+                <li {% if request.get_full_path == role_list_url %} class="active" {% endif %}>
+                <a href='{% url "roles:list"   %}'>
+                    <i class="fas fa-user-tag"></i> <span>Roles</span>
                 </a>
                 </li>
+                {%endcomment%}
+                
             {% endif %}
         </ul>
     </section>
index 28888fc..62282ad 100644 (file)
@@ -67,8 +67,9 @@
     <script src="/static/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
 
     <script>
-   $(document).ready( function () {
-        var table = $('#projects_table').DataTable({
+        var table;
+    $(document).ready( function () {
+        table = $('#projects_table').DataTable({
             responsive: true,
             "ajax": {
                 "url": "/projects/list",
                         title: "Result",
                         message: "Project deleted.",
                         callback: function () {
-                            location.reload();
+                            table.ajax.reload();
                         }
                     });
                 }).fail(function(result){
                         title: "Result",
                         message: "Project created.",
                     callback: function () {
-                        location.reload();
+                        table.ajax.reload();
+                        $('#modal_new_project').modal('hide');
+                    }
+                    });
+            }).fail(function(result){
+                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
+                    });
+            });
+        });
+    
+        $("#formEditProject").submit(function(event){
+            event.preventDefault(); //prevent default action
+            var post_url = $(this).attr("action"); //get form action url
+            var request_method = $(this).attr("method"); //get form GET/POST method
+            var form_data = new FormData(this); //Encode form elements for submission
+            console.log(post_url);
+            $.ajax({
+                url: post_url,
+                type: request_method,
+                data: form_data,
+                headers: {
+                    "Accept": 'application/json'
+                },
+                contentType: false,
+                processData: false
+            }).done(function (response,textStatus, jqXHR) {
+                bootbox.alert({
+                        title: "Result",
+                        message: "Project updated.",
+                    callback: function () {
+                        table.ajax.reload();
+                        $('#modal_edit_project').modal('hide');
                     }
                     });
             }).fail(function(result){
diff --git a/rolehandler/__init__.py b/rolehandler/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/rolehandler/apps.py b/rolehandler/apps.py
new file mode 100644 (file)
index 0000000..438f107
--- /dev/null
@@ -0,0 +1,8 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.apps import AppConfig
+
+
+class RolehandlerConfig(AppConfig):
+    name = 'rolehandler'
diff --git a/rolehandler/migrations/__init__.py b/rolehandler/migrations/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/rolehandler/models.py b/rolehandler/models.py
new file mode 100644 (file)
index 0000000..1dfab76
--- /dev/null
@@ -0,0 +1,6 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models
+
+# Create your models here.
diff --git a/rolehandler/templates/modal/role_create.html b/rolehandler/templates/modal/role_create.html
new file mode 100644 (file)
index 0000000..58d68ca
--- /dev/null
@@ -0,0 +1,38 @@
+<div class="modal" id="modal_new_role" 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">New Role</h4>
+            </div>
+            <form id="formCreateRole" action='{% url "roles:create"   %}'
+                  class="form-horizontal"
+                  method="post" enctype="multipart/form-data">
+                {% csrf_token %}
+                <div class="modal-body" id="modal_new_role_body">
+                    <div class="form-group">
+                        <label for="rolename" class="col-sm-3 control-label">Name *</label>
+                        <div class="col-sm-6">
+                            <input class="form-control" id="rolename" name="name"
+                                   placeholder="Name" required>
+                        </div>
+                    </div>
+
+            
+
+                </div>
+                <div class="modal-footer">
+                    <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Cancel</button>
+                    <button class="btn btn-primary"
+                            data-loading-text="<i class='fa fa-circle-o-notch fa-spin'></i> Creating..."
+                            id="create_new_role">Create
+                    </button>
+
+                </div>
+            </form>
+        </div>
+        <!-- /.modal-content -->
+    </div>
+    <!-- /.modal-dialog -->
+</div>
diff --git a/rolehandler/templates/modal/role_edit.html b/rolehandler/templates/modal/role_edit.html
new file mode 100644 (file)
index 0000000..8541177
--- /dev/null
@@ -0,0 +1,38 @@
+<div class="modal" id="modal_edit_role" 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">Edit Role</h4>
+            </div>
+            <form id="formEditRole" action=""
+                  class="form-horizontal"
+                  method="post" enctype="multipart/form-data">
+                {% csrf_token %}
+                <input type="hidden"  id="projects_old" name="projects_old" value="asdasd">
+                <div class="modal-body" id="modal_edit_role_body">
+                    
+                    <div class="form-group">
+                        <label for="name" 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">
+                        </div>
+                    </div>
+                   
+                </div>
+                <div class="modal-footer">
+                    <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Cancel</button>
+                    <button class="btn btn-primary"
+                            data-loading-text="<i class='fa fa-circle-o-notch fa-spin'></i> Editing..."
+                            id="create_edit_role">Apply
+                    </button>
+
+                </div>
+            </form>
+        </div>
+        <!-- /.modal-content -->
+    </div>
+    <!-- /.modal-dialog -->
+</div>
diff --git a/rolehandler/templates/role_list.html b/rolehandler/templates/role_list.html
new file mode 100644 (file)
index 0000000..5cf49a1
--- /dev/null
@@ -0,0 +1,222 @@
+{% extends "base.html" %}
+{% load get %}
+{% load date_tag %}
+{% 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/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.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="#">roles</a></li>
+{% endblock %}
+
+{% block content_body %}
+    {{ block.super }}
+    {% include 'modal/role_create.html' %}
+    {% include 'modal/role_edit.html' %}
+
+    {% csrf_token %}
+    <div class="row">
+        <div class="col-md-12">
+
+            <div class="box">
+                <div class="box-header with-border">
+                    <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" %}'})"
+                                data-toggle="tooltip" data-placement="top" title="New role">
+
+                            <i class="fa fa-plus"></i> Create role
+                        </button>
+
+                    </div>
+                </div>
+                <div class="box-body">
+                    <table id="roles_table" class="table table-bordered table-striped">
+                        <thead>
+                        <tr>
+                            <th>Name</th>
+                            <th>Identifier</th>
+                            <th>Modified</th>
+                            <th>Created</th>
+                            <th>Actions</th>
+                        </tr>
+                        </thead>
+                        <tbody>
+                        </tbody>
+                    </table>
+                </div>
+            </div>
+        </div>
+
+    </div>
+{% endblock %}
+
+{% block resource_block %}
+    {{ block.super }}
+    <script src="/static/bower_components/datatables.net/js/jquery.dataTables.min.js"></script>
+    <script src="/static/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
+    <script src="/static/bower_components/select2/dist/js/select2.js"></script>
+    <script src="/static/src/rolehandler/role_list.js"></script>
+    <script>
+        var table;
+        
+        $(document).ready(function () {
+            table = $('#roles_table').DataTable({
+                responsive: true,
+                "ajax": {
+                    "url": "/admin/roles/list",
+                    "dataSrc": function (json) {
+                        return json['roles'];
+                    },
+                    statusCode: {
+                        401: function () {
+                            console.log("no auth");
+                            moveToLogin(window.location.pathname);
+                        }
+                    },
+                    "error": function (hxr, error, thrown) {
+                        console.log(hxr)
+                        console.log(thrown)
+                        console.log(error);
+                    }
+
+                },
+                "columns": [
+                    {
+                        "render": function (data, type, row) {
+                            return row["name"];
+                        },
+                        "targets": 0
+                    },
+                    
+                    {
+                        "render": function (data, type, row) {
+                            return row['_id'];
+                        },
+                        "targets": 1
+                    },
+                    {
+                        "render": function (data, type, row) {
+                            return moment.unix(row["_admin"]['modified']).format('YYYY-MM-DD hh:mm:ss a');
+                        },
+                        "targets": 2
+                    },
+                    {
+                        "render": function (data, type, row) {
+                            return moment.unix(row["_admin"]['created']).format('YYYY-MM-DD hh:mm:ss a');
+                        },
+                        "targets": 3
+                    },
+                    {
+                        "render": function (data, type, row) {
+                            return '<div class="btn-group">' +
+                                '<button type="button" class="btn btn-default dropdown-toggle"' +
+                                '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'] + '\'})">' +
+                                '<i class="fa fa-edit"></i> Edit</a></li>' +
+                                '<li> <a href="#" onclick="javascript:deleteRole(\'' + row['_id'] + '\', \'' + row['rolename'] + '\')"' +
+                                'style="color:red"><i class="fa fa-trash"></i> Delete</a></li> </ul></div>';
+                        },
+                        "targets": 4,
+                        "orderable": false
+                    }
+                ]
+            });
+
+            setInterval(function () {
+                table.ajax.reload();
+            }, 10000);
+
+            $("#formCreateRole").submit(function (event) {
+                event.preventDefault(); //prevent default action
+                var post_url = $(this).attr("action"); //get form action url
+                var request_method = $(this).attr("method");
+                var form_data = new FormData(this); //Encode form elements for submission
+                
+                $.ajax({
+                    url: post_url,
+                    type: request_method,
+                    data: form_data,
+                    headers: {
+                        "Accept": 'application/json'
+                    },
+                    contentType: false,
+                    processData: false
+                }).done(function (response, textStatus, jqXHR) {
+                    $('#modal_new_role').modal('hide');
+                    table.ajax.reload();
+                    bootbox.alert({
+                        title: "Result",
+                        message: "role successfully created."
+                    });
+
+                }).fail(function (result) {
+                    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").submit(function (event) {
+                event.preventDefault(); //prevent default action
+                var post_url = $(this).attr("action"); //get form action url
+                var request_method = $(this).attr("method");
+                var form_data = new FormData(this); //Encode form elements for submission
+
+                $.ajax({
+                    url: post_url,
+                    type: request_method,
+                    data: form_data,
+                    headers: {
+                        "Accept": 'application/json'
+                    },
+                    contentType: false,
+                    processData: false
+                }).done(function (response, textStatus, jqXHR) {
+                    $('#modal_edit_role').modal('hide');
+                    table.ajax.reload();
+                    bootbox.alert({
+                        title: "Result",
+                        message: "role successfully modified."
+                    });
+
+                }).fail(function (result) {
+                    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
+                    });
+                });
+            });
+        
+        });
+    </script>
+
+
+{% endblock %}
+
+{% block footer %}
+    {% include "footer.html"  %}
+{% endblock %}
\ No newline at end of file
diff --git a/rolehandler/urls.py b/rolehandler/urls.py
new file mode 100644 (file)
index 0000000..c37325d
--- /dev/null
@@ -0,0 +1,26 @@
+#
+#   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.conf.urls import url
+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')
+
+]
diff --git a/rolehandler/views.py b/rolehandler/views.py
new file mode 100644 (file)
index 0000000..f6a0799
--- /dev/null
@@ -0,0 +1,96 @@
+#
+#   Copyright 2019 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.
+#
+
+from django.shortcuts import render, redirect
+from sf_t3d.decorators import login_required
+from django.http import HttpResponse
+import json
+import logging
+import authosm.utils as osmutils
+from lib.osm.osmclient.clientv2 import Client
+
+logging.basicConfig(level=logging.DEBUG)
+log = logging.getLogger(__name__)
+
+
+@login_required
+def role_list(request):
+    user = osmutils.get_user(request)
+    client = Client()
+    result = client.role_list(user.get_token())
+    result = {
+        'roles': result['data'] if result and result['error'] is False else []
+    }
+    return __response_handler(request, result, 'role_list.html')
+
+
+@login_required
+def create(request):
+    user = osmutils.get_user(request)
+    client = Client()
+    role_data ={
+       'name'
+    }
+    result = client.role_create(user.get_token(), role_data)
+    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 delete(request, role_id=None):
+    user = osmutils.get_user(request)
+    try:
+        client = Client()
+        result = client.role_delete(user.get_token(), role_id)
+    except Exception as e:
+        log.exception(e)
+        result = {'error': True, 'data': str(e)}
+    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 update(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)
+    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)
+    else:
+        return __response_handler(request, {}, url=None, status=200)
+
+
+def __response_handler(request, data_res, url=None, to_redirect=None, *args, **kwargs):
+    raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
+    if 'application/json' in raw_content_types or url is None:
+        return HttpResponse(json.dumps(data_res), content_type="application/json", *args, **kwargs)
+    elif to_redirect:
+        return redirect(url, *args, **kwargs)
+    else:
+        return render(request, url, data_res)
index 768152a..644cba9 100644 (file)
@@ -61,6 +61,7 @@ INSTALLED_APPS = [
     'instancehandler',
     'sdnctrlhandler',
     'userhandler',
+    'rolehandler',
     'netslicehandler'
 
 ]
index d13bd0f..9c821b1 100644 (file)
@@ -31,6 +31,7 @@ urlpatterns = [
     url(r'^instances/', include('instancehandler.urls', namespace='instances'), name='instances_base'),
     url(r'^netslices/', include('netslicehandler.urls', namespace='netslices'), name='netslices_base'),
     url(r'^admin/users/', include('userhandler.urls', namespace='users'), name='users_base'),
+    url(r'^admin/roles/', include('rolehandler.urls', namespace='roles'), name='roles_base'),
     url(r'^forbidden', views.forbidden, name='forbidden'),
 
 ]
diff --git a/static/src/rolehandler/role_list.js b/static/src/rolehandler/role_list.js
new file mode 100644 (file)
index 0000000..fc19f52
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+   Copyright 2019 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.
+*/
+
+function openModalCreateRole(args) {
+
+    
+
+    $('#modal_new_role').modal('show');
+}
+
+function openModalEditRole(args) {
+    var url = '/admin/roles/' + args.role_id;
+    
+    $("#formEditRole").attr("action", url);
+    
+
+    $('#modal_edit_role').modal('show');
+}
+
+function deleteRole(role_id, name) {
+    var delete_url = '/admin/roles/' + role_id + '/delete';
+    bootbox.confirm("Are you sure want to delete " + name + "?", function (confirm) {
+        if (confirm) {
+            var dialog = bootbox.dialog({
+                message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
+                closeButton: false
+            });
+            $.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();
+                },
+                error: function (result) {
+                    dialog.modal('hide');
+                    bootbox.alert("An error occurred.");
+                }
+            });
+        }
+    })
+
+}
\ No newline at end of file
index 21dbe8a..49eda46 100644 (file)
                         </div>
                     </div>
                     <div class="form-group">
-                        <label for=projects" class="col-sm-3 control-label">Default project *</label>
+                        <label for="projects" class="col-sm-3 control-label">Default project *</label>
                         <div class="col-sm-6">
                             <select required id="default_project_edit" class="js-example-basic form-control" name="default_project">
                             </select>
                         </div>
                     </div>
                     <div class="form-group">
-                        <label for=projects" class="col-sm-3 control-label">Projects *</label>
+                        <label for="projects" class="col-sm-3 control-label">Projects *</label>
                         <div class="col-sm-6">
                             <select required id="projects_edit" class="js-example-basic-multiple form-control" name="projects"
                             multiple="multiple">
index 6447d69..4f38be8 100644 (file)
@@ -20,7 +20,7 @@ from userhandler import views
 urlpatterns = [
     url(r'^list$', views.user_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<user_id>[-\w]+)$', views.update, name='update'),
+    url(r'^(?P<user_id>[-\w]+)/delete$', views.delete, name='delete'),   
 
 ]
index 0c12a84..1703233 100644 (file)
@@ -31,9 +31,23 @@ def user_list(request):
     user = osmutils.get_user(request)
     client = Client()
     result = client.user_list(user.get_token())
+    result_projects = client.project_list(user.get_token())
+    p_map = {'admin': 'admin'}
+    for p in result_projects['data']:
+        p_map[p['_id']] = p['name']
+    users = result['data'] if result and result['error'] is False else []
+    for user in users:
+        user_project_ids = user['projects']
+        user_project_names = []
+        for p_id in user_project_ids:
+            if p_id in p_map:
+                user_project_names.append(p_map[p_id])
+        user['projects'] = user_project_names
+
     result = {
         'users': result['data'] if result and result['error'] is False else []
     }
+    
     return __response_handler(request, result, 'user_list.html')