fix bug 823; fix bug 800 49/7849/6
authorlombardofr <lombardo@everyup.it>
Mon, 19 Aug 2019 07:33:56 +0000 (09:33 +0200)
committerlombardofr <lombardo@everyup.it>
Thu, 29 Aug 2019 10:26:29 +0000 (12:26 +0200)
Change-Id: Idafe6cd3ab8db26cb763be9f334809429dbec913
Signed-off-by: lombardofr <lombardo@everyup.it>
16 files changed:
authosm/models.py
projecthandler/template/project/osm/osm_project_left_sidebar.html
projecthandler/views.py
rolehandler/templates/modal/role_create.html
rolehandler/templates/modal/role_edit.html
rolehandler/views.py
static/src/rolehandler/role_list.js
static/src/userhandler/user_list.js
template/base.html
userhandler/templates/modal/user_create.html
userhandler/templates/modal/user_credentials_edit.html [new file with mode: 0644]
userhandler/templates/modal/user_edit.html [deleted file]
userhandler/templates/modal/user_proj_role_edit.html [new file with mode: 0644]
userhandler/templates/user_list.html
userhandler/urls.py
userhandler/views.py

index f968dfa..74c1f1e 100644 (file)
@@ -93,11 +93,10 @@ class AbstractOsmUser(AbstractBaseUser, PermissionsMixin):
     def get_projects(self):
         client = Client()
         user_info = client.get_user_info(self.get_token(), self.username)
-        projects = client.get_projects(self.get_token(), user_info['data']['projects'])
-        if 'error' in projects and projects['error'] is True:
+        if 'error' in user_info and user_info['error'] is True:
             return []
         else:
-            return projects['data']
+            return user_info['data']['project_role_mappings']
 
     def switch_project(self, project_id):
         client = Client()
index 7259834..a16d86e 100644 (file)
@@ -1,3 +1,18 @@
+<!--
+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.
+-->
 <aside class="main-sidebar">
     <!-- sidebar: style can be found in sidebar.less -->
     <section class="sidebar">
                     <i class="fas fa-users"></i> <span>Users</span>
                 </a>
                 </li>
-                {%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>
index 8d4ac83..f36c7ab 100644 (file)
@@ -75,11 +75,13 @@ def open_project(request):
         vnfd = client.vnfd_list(user.get_token())
         ns = client.ns_list(user.get_token())
         vnf = client.vnf_list(user.get_token())
+
+        proj_data_admin =  prj['data']['_admin'] if prj and prj['data'] and  prj['data']['_admin'] and prj['error'] is False else None
         project_overview = {
             'owner': user.username,
             'name': user.project_name,
-            'updated_date': prj['data']['_admin']['modified'] if prj and prj['error'] is False else '-',
-            'created_date': prj['data']['_admin']['created'] if prj and prj['error'] is False else '-',
+            'updated_date': proj_data_admin['modified'] if proj_data_admin else '-',
+            'created_date': proj_data_admin['created'] if proj_data_admin else '-',
 
             'type': 'osm',
             'nsd': len(nsd['data']) if nsd and nsd['error'] is False else 0,
index d8282a7..bd734ad 100644 (file)
@@ -1,3 +1,18 @@
+<!--
+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.
+-->
 <div class="modal" id="modal_new_role" xmlns="http://www.w3.org/1999/html">
     <div class="modal-dialog">
         <div class="modal-content">
                         </div>
                        
                     </div>
+                   
                     <div class="form-group">
+                        <label for="permissions" class="col-sm-3 control-label">Permissions </label>
                         <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>
+                            <textarea class="form-control" id="permissions" name="permissions" placeholder="Yaml permissions"
+                                      rows="10"></textarea>
                         </div>
                     </div>
 
index ca3c4c0..515073b 100644 (file)
@@ -1,3 +1,18 @@
+<!--
+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.
+-->
 <div class="modal" id="modal_edit_role" xmlns="http://www.w3.org/1999/html">
     <div class="modal-dialog">
         <div class="modal-content">
                         </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>
+                        <label for="permissions" class="col-sm-3 control-label">Permissions </label>
                         <div class="col-sm-6">
-                            <textarea class="form-control" id="edit_definition" name="definition" placeholder="Yaml definition"
-                                      rows="3"></textarea>
+                            <textarea class="form-control" id="edit_permissions" name="permissions" placeholder="Yaml permissions"
+                                      rows="10"></textarea>
                         </div>
                     </div>
                    
index a13e28d..2537175 100644 (file)
@@ -44,17 +44,16 @@ def create(request):
     client = Client()
     role_data ={
        '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 'permissions' in request.POST and request.POST.get('permissions') != '':
+            role_permissions = yaml.load(request.POST.get('permissions'))
 
-            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(role_permissions, dict):
+                    raise ValueError('Role permissions should be provided in a key-value fashion')
+            for key, value in role_permissions.items():
                 if not isinstance(value, bool):
-                    raise ValueError('Value in a role definition should be boolean')
+                    raise ValueError("Value of '{}' in a role permissionss should be boolean".format(key))
                 role_data[key] = value
     except Exception as e:
         return __response_handler(request, {'status': 400, 'code': 'BAD_REQUEST', 'detail': e.message} , url=None, status=400)
@@ -86,19 +85,17 @@ 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 'permissions' in request.POST and request.POST.get('permissions') != '':
+            role_permissions = yaml.load(request.POST.get('permissions'))
 
-            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(role_permissions, dict):
+                    raise ValueError('Role permissions should be provided in a key-value fashion')
+            for key, value in role_permissions.items():
                 if not isinstance(value, bool):
-                    raise ValueError('Value in a role definition should be boolean')
+                    raise ValueError('Value in a role permissions 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)
@@ -126,8 +123,7 @@ def get(request, role_id=None):
         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'] }
+            'permissions': { key:value for key, value in role['permissions'].items() if key not in ['_id', 'name', 'root', '_admin'] }
         }
         return __response_handler(request, result, url=None, status=200)
 
index 5145a04..5ee1b35 100644 (file)
@@ -40,7 +40,7 @@ function openModalEditRole(args) {
         $("#formEditRole").attr("action", url_update);
         $('#modal_edit_role').modal('show');
         $('#edit_rolename').val(response['name'])
-        $('#edit_definition').val(JSON.stringify(response['definition']))
+        $('#edit_permissions').val(JSON.stringify(response['permissions']))
         if(response['root'] === true){
             $("#edit_root").attr("checked", true);
         }
index 9a52249..0000ecc 100644 (file)
@@ -41,7 +41,7 @@ function openModalCreateUser(args) {
     $('#modal_new_user').modal('show');
 }
 
-function openModalEditUser(args) {
+function openModalEditUserCredentials(args) {
     var url = '/admin/users/' + args.user_id;
     var user_projects = args.projects ? args.projects.split(',') : [];
     $("#formEditUser").attr("action", url);
@@ -66,9 +66,81 @@ function openModalEditUser(args) {
     }
 
 
-    $('#modal_edit_user').modal('show');
+    $('#modal_edit_user_credentials').modal('show');
 }
 
+function openModalEditUserRoleMap(user_id) {
+    $("#formEditUserRoleMap").attr("action", '/admin/users/' + user_id);
+    var dialog = bootbox.dialog({
+        message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
+        closeButton: false
+    });
+    $.ajax({
+        url: '/admin/users/' + user_id + '/info',
+        dataType: "json",
+        contentType: "application/json;charset=utf-8",
+        success: function (result) {
+            dialog.modal('hide');
+            resetMapGroup(result);
+            $('#modal_edit_user_role_map').modal('show');
+        },
+        error: function (result) {
+            dialog.modal('hide');
+            bootbox.alert("An error occurred.");
+        }
+    });
+    
+}
+
+function resetMapGroup(args){
+    var $formGroup = $('#modal_edit_proj_role_map_body');
+    $formGroup.empty();
+    $formGroup.append('<div class="proj-role-map-group-head">' + 
+       
+        '<button type="button" class="btn btn-success btn-add btn-sm">+</button>'+
+        '</div></br>');
+    if(args['project_role_mappings'] && args['project_role_mappings'].length > 0) {
+        
+        for(i = 0; i < args['project_role_mappings'].length; ++i){
+            var mapping = args['project_role_mappings'][i];
+            
+            $formGroup.append('<div class="proj-role-map-group"> <div class="form-group">' + 
+            '<label  class="col-sm-2">Project* </label><div class="col-sm-3">'+
+            '<input name="map_project_name" value="'+mapping.project_name+'" class="form-control input-sm" required></div>'+
+            '<label class="col-sm-2">Role* </label>'+
+            '<div class="col-sm-3">'+
+            '<input name="map_role_name" value="'+mapping.role_name+'" class="form-control input-sm" required>'+
+            '</div>'+
+            '<button type="button" class="btn btn-danger btn-remove btn-sm">-</button></div></div>');
+        }
+    } 
+    
+        
+    
+    
+}
+
+var addMapGroup = function (event) {
+    event.preventDefault();
+
+    var $formGroup = $('#modal_edit_proj_role_map_body');
+    $formGroup.append('<div class="proj-role-map-group"> <div class="form-group">' + 
+            '<label  class="col-sm-2">Project* </label><div class="col-sm-3">'+
+            '<input name="map_project_name" class="form-control input-sm" required></div>'+
+            '<label class="col-sm-2">Role* </label>'+
+            '<div class="col-sm-3">'+
+            '<input name="map_role_name" class="form-control input-sm" required>'+
+            '</div>'+
+            '<button type="button" class="btn btn-danger btn-remove btn-sm">-</button></div></div>');
+
+};
+
+var removeMapGroup = function (event) {
+    event.preventDefault();
+    var $formGroup = $(this).closest('.proj-role-map-group');
+    $formGroup.remove();
+};
+
 function deleteUser(user_id, name) {
     var delete_url = '/admin/users/' + user_id + '/delete';
     bootbox.confirm("Are you sure want to delete " + name + "?", function (confirm) {
@@ -94,4 +166,67 @@ function deleteUser(user_id, name) {
         }
     })
 
-}
\ No newline at end of file
+}
+
+function validatePswOnCreate() {
+    
+    var confirm_password = document.getElementById("password2");
+    if($("#password").val() == $("#password2").val()){
+        $("#pwmatch").removeClass("glyphicon-remove");
+        $("#pwmatch").addClass("glyphicon-ok");
+        $("#pwmatch").css("color","#00A41E");
+        confirm_password.setCustomValidity("");
+    }else{
+        $("#pwmatch").removeClass("glyphicon-ok");
+        $("#pwmatch").addClass("glyphicon-remove");
+        $("#pwmatch").css("color","#FF0004");
+        confirm_password.setCustomValidity("Passwords Don't Match");
+    }
+}
+
+function validatePswOnEdit() {
+    
+    var confirm_password = document.getElementById("edit_password2");
+    if($("#edit_password").val() == $("#edit_password2").val()){
+        $("#pwmatch_edit").removeClass("glyphicon-remove");
+        $("#pwmatch_edit").addClass("glyphicon-ok");
+        $("#pwmatch_edit").css("color","#00A41E");
+        confirm_password.setCustomValidity("");
+    }else{
+        $("#pwmatch_edit").removeClass("glyphicon-ok");
+        $("#pwmatch_edit").addClass("glyphicon-remove");
+        $("#pwmatch_edit").css("color","#FF0004");
+        confirm_password.setCustomValidity("Passwords Don't Match");
+    }
+}
+
+$(document).ready(function () {
+    $("#formEditUserRoleMap").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
+        $.ajax({
+            url: post_url,
+            type: request_method,
+            data: form_data,
+            headers: {
+                "Accept": 'application/json'
+            },
+            contentType: false,
+            processData: false
+        }).done(function (response, textStatus, jqXHR) {
+            table.ajax.reload();
+            $('#modal_edit_user_role_map').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
+            });
+        });
+    });
+
+})
\ No newline at end of file
index 82497cd..1c68bb1 100644 (file)
@@ -1,3 +1,18 @@
+<!--
+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.
+-->
 {% load staticfiles %}
 {% load get %}
 <!DOCTYPE html>
                             <!-- inner menu: contains the actual data -->
                             <ul class="menu">
                                 {% for p in request.session.projects %}
-                                    {% if p.name == user.project_name %}
+                                    {% if p.project_name == user.project_name %}
                                         <li>
                                             <a href="#">
                                                 <h3>
-                                                    <i class="fa fa-folder-open"></i> <span>{{ p.name }}</span>
+                                                    <i class="fa fa-folder-open"></i> <span>{{ p.project_name }}</span>
                                                 </h3>
                                             </a>
                                         </li>
                                     {% else %}
                                         <li>
-                                            <a href="{% url 'projects:switch_project' project_id=p|get:"_id" %}">
+                                            <a href="{% url 'projects:switch_project' project_id=p.project %}">
                                                 <h3>
-                                                    <i class="fa fa-folder"></i> <span>{{ p.name }}</span>
+                                                    <i class="fa fa-folder"></i> <span>{{ p.project_name }}</span>
                                                 </h3>
                                             </a>
                                         </li>
index 21afce0..5b8d73a 100644 (file)
@@ -1,3 +1,18 @@
+<!--
+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.
+-->
 <div class="modal" id="modal_new_user" xmlns="http://www.w3.org/1999/html">
     <div class="modal-dialog">
         <div class="modal-content">
@@ -11,6 +26,7 @@
                   method="post" enctype="multipart/form-data">
                 {% csrf_token %}
                 <div class="modal-body" id="modal_new_user_body">
+                    
                     <div class="form-group">
                         <label for="username" class="col-sm-3 control-label">Username *</label>
                         <div class="col-sm-6">
                         <label for="password" class="col-sm-3 control-label">Password *</label>
                         <div class="col-sm-6">
                            <input class="form-control" id="password" name="password" type="password"
-                                   placeholder="Password" required>
+                                   placeholder="Password" autocomplete="off" required>
                         </div>
                     </div>
+
                     <div class="form-group">
-                        <label for=projects" class="col-sm-3 control-label">Projects *</label>
-                        <div class="col-sm-6">
-                            <select required id="projects" class="js-example-basic-multiple form-control" name="projects"
-                            multiple="multiple">
-                            </select>
-                        </div>
+                            <label for="password" class="col-sm-3 control-label">Conf. Password *</label>
+                            <div class="col-sm-6">
+                               <input class="form-control" id="password2" name="password2" type="password"
+                                       placeholder="Repeat Password" autocomplete="off" required>
+                                <div class="row">
+                                    <div class="col-sm-12">
+                                       <span id="pwmatch" class="glyphicon glyphicon-remove" style="color:#FF0004;"></span> Passwords Match
+                                    </div>
+                                </div>
+                            </div>
                     </div>
 
 
+
                 </div>
                 <div class="modal-footer">
                     <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Cancel</button>
diff --git a/userhandler/templates/modal/user_credentials_edit.html b/userhandler/templates/modal/user_credentials_edit.html
new file mode 100644 (file)
index 0000000..b20da19
--- /dev/null
@@ -0,0 +1,88 @@
+<!--
+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.
+-->
+<div class="modal" id="modal_edit_user_credentials" 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 User Credentials</h4>
+            </div>
+            <form id="formEditUser" 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_user_credentials_body">
+                    {% comment %}<div class="form-group">
+                        <label for="username_edit" class="col-sm-3 control-label">Username *</label>
+                        <div class="col-sm-6">
+                            <input class="form-control" id="username_edit" name="username"
+                                   placeholder="Username" required>
+                        </div>
+                    </div>{% endcomment %}
+                    <div class="form-group">
+                        <label for="password" class="col-sm-3 control-label">New Password</label>
+                        <div class="col-sm-6">
+                           <input class="form-control" id="edit_password" name="password" type="password"
+                                   placeholder="Password">
+                        </div>
+                    </div>
+                    <div class="form-group">
+                            <label for="password" class="col-sm-3 control-label">Conf. Password</label>
+                            <div class="col-sm-6">
+                               <input class="form-control" id="edit_password2" name="password2" type="password"
+                                       placeholder="Repeat Password" autocomplete="off" required>
+                                <div class="row">
+                                    <div class="col-sm-12">
+                                       <span id="pwmatch_edit" class="glyphicon glyphicon-remove" style="color:#FF0004;"></span> Passwords Match
+                                    </div>
+                                </div>
+                            </div>
+                    </div>
+                    {% comment %}
+                    <div class="form-group">
+                        <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>
+                        <div class="col-sm-6">
+                            <select required id="projects_edit" class="js-example-basic-multiple form-control" name="projects"
+                            multiple="multiple">
+                            </select>
+                        </div>
+                    </div>
+                    {% endcomment %}
+
+                </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_user">Apply
+                    </button>
+
+                </div>
+            </form>
+        </div>
+        <!-- /.modal-content -->
+    </div>
+    <!-- /.modal-dialog -->
+</div>
diff --git a/userhandler/templates/modal/user_edit.html b/userhandler/templates/modal/user_edit.html
deleted file mode 100644 (file)
index 49eda46..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-<div class="modal" id="modal_edit_user" 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 User</h4>
-            </div>
-            <form id="formEditUser" 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_user_body">
-                    {% comment %}<div class="form-group">
-                        <label for="username_edit" class="col-sm-3 control-label">Username *</label>
-                        <div class="col-sm-6">
-                            <input class="form-control" id="username_edit" name="username"
-                                   placeholder="Username" required>
-                        </div>
-                    </div>{% endcomment %}
-                    <div class="form-group">
-                        <label for="password" class="col-sm-3 control-label">New Password</label>
-                        <div class="col-sm-6">
-                           <input class="form-control" id="edit_password" name="password" type="password"
-                                   placeholder="Password">
-                        </div>
-                    </div>
-                    <div class="form-group">
-                        <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>
-                        <div class="col-sm-6">
-                            <select required id="projects_edit" class="js-example-basic-multiple form-control" name="projects"
-                            multiple="multiple">
-                            </select>
-                        </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_user">Apply
-                    </button>
-
-                </div>
-            </form>
-        </div>
-        <!-- /.modal-content -->
-    </div>
-    <!-- /.modal-dialog -->
-</div>
diff --git a/userhandler/templates/modal/user_proj_role_edit.html b/userhandler/templates/modal/user_proj_role_edit.html
new file mode 100644 (file)
index 0000000..e1df9d5
--- /dev/null
@@ -0,0 +1,44 @@
+<!--
+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.
+-->
+<div class="modal" id="modal_edit_user_role_map" 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 Project Role Mapping</h4>
+            </div>
+            <form id="formEditUserRoleMap" action=""
+                  class="form-horizontal"
+                  method="post" enctype="multipart/form-data">
+                {% csrf_token %}
+                <div class="modal-body" id="modal_edit_proj_role_map_body">
+                       
+                </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="edit_user_map">Apply
+                    </button>
+
+                </div>
+            </form>
+        </div>
+        <!-- /.modal-content -->
+    </div>
+    <!-- /.modal-dialog -->
+</div>
index 361784c..b287b76 100644 (file)
@@ -1,3 +1,18 @@
+<!--
+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.
+-->
 {% extends "base.html" %}
 {% load get %}
 {% load date_tag %}
@@ -26,7 +41,9 @@
     {{ block.super }}
     {% include 'modal/user_details.html' %}
     {% include 'modal/user_create.html' %}
-    {% include 'modal/user_edit.html' %}
+    {% include 'modal/user_credentials_edit.html' %}
+    {% include 'modal/user_proj_role_edit.html' %}
+
 
     {% csrf_token %}
     <div class="row">
@@ -50,7 +67,6 @@
                         <thead>
                         <tr>
                             <th>Name</th>
-                            <th>Projects</th>
                             <th>Identifier</th>
                             <th>Modified</th>
                             <th>Created</th>
                     },
                     {
                         "render": function (data, type, row) {
-                            return row['projects'];
-                        },
-                        "targets": 1
-                    },
-                    {
-                        "render": function (data, type, row) {
+                            
                             return row['_id'];
                         },
-                        "targets": 2
+                        "targets": 1
                     },
                     {
                         "render": function (data, type, row) {
                             return moment.unix(row["_admin"]['modified']).format('YYYY-MM-DD hh:mm:ss a');
                         },
-                        "targets": 3
+                        "targets": 2
                     },
                     {
                         "render": function (data, type, row) {
                             return moment.unix(row["_admin"]['created']).format('YYYY-MM-DD hh:mm:ss a');
                         },
-                        "targets": 4
+                        "targets": 3
                     },
                     {
                         "render": function (data, type, row) {
                                 'data-toggle="dropdown" aria-expanded="false">Actions ' +
                                 '<span class="fa fa-caret-down"></span></button> ' +
                                 '<ul class="dropdown-menu">' +
-                                '<li> <a href="#" onclick="javascript:openModalEditUser({user_id:\'' + row['_id'] + '\', usernarme:\'' + row['username'] + '\', projects: \'' + row['projects'] + '\'})">' +
-                                '<i class="fa fa-edit"></i> Edit</a></li>' +
+                                '<li> <a href="#" onclick="javascript:openModalEditUserCredentials({user_id:\'' + row['_id'] + '\', usernarme:\'' + row['username'] + '\'})">' +
+                                '<i class="fa fa-lock"></i>Edit Credentials</a></li>' +
+                                '<li> <a href="#" onclick="javascript:openModalEditUserRoleMap(\''+row['_id']+'\')">' +
+                                '<i class="fa fa-user-tag"></i>Projects-Roles</a></li>' +
                                 '<li> <a href="#" onclick="javascript:deleteUser(\'' + row['_id'] + '\', \'' + row['username'] + '\')"' +
                                 'style="color:red"><i class="fa fa-trash"></i> Delete</a></li> </ul></div>';
                         },
-                        "targets": 5,
+                        "targets": 4,
                         "orderable": false
                     }
                 ]
             });
-
+            /*
             var select2_groups = $('#projects_edit').select2({
                 placeholder: 'Select Projects',
                 width: '100%',
                         };
                     }
                 }
-            });
-
+            });*/
+            /*
             var select2_single = $('#default_project_edit').select2({
                 placeholder: 'Select Default Project',
                 width: '100%',
                         };
                     }
                 }
-            });
+            });*/
 
             setInterval(function () {
                 table.ajax.reload();
                     contentType: false,
                     processData: false
                 }).done(function (response, textStatus, jqXHR) {
-                    $('#modal_edit_user').modal('hide');
+                    $('#modal_edit_user_credentials').modal('hide');
                     table.ajax.reload();
                     bootbox.alert({
                         title: "Result",
                 });
             });
         
+            $("#password2").keyup(validatePswOnCreate);
+            $("#edit_password2").keyup(validatePswOnEdit);
+
+            $(document).on('click', '.proj-role-map-group-head .btn-add', addMapGroup);
+            $(document).on('click', '.proj-role-map-group .btn-remove', removeMapGroup);
         });
     </script>
 
index 4f38be8..25156f0 100644 (file)
@@ -20,6 +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>[-\w]+)/info', views.user_info, name='info'),
     url(r'^(?P<user_id>[-\w]+)$', views.update, name='update'),
     url(r'^(?P<user_id>[-\w]+)/delete$', views.delete, name='delete'),   
 
index 1703233..66fc22a 100644 (file)
@@ -31,19 +31,8 @@ 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
 
+    users = result['data'] if result and result['error'] is False else []    
     result = {
         'users': result['data'] if result and result['error'] is False else []
     }
@@ -57,9 +46,9 @@ def create(request):
     client = Client()
     user_data ={
         "username": request.POST['username'],
-        "password": request.POST['password'],
-        "projects": request.POST.getlist('projects')
+        "password": request.POST['password']
     }
+    
     result = client.user_create(user.get_token(), user_data)
     if result['error']:
         return __response_handler(request, result['data'], url=None,
@@ -84,32 +73,41 @@ def delete(request, user_id=None):
         return __response_handler(request, {}, url=None, status=200)
 
 @login_required
-def update(request, user_id=None):
+def user_info(request, user_id=None):
     user = osmutils.get_user(request)
     try:
         client = Client()
-        projects_old = request.POST.get('projects_old').split(',')
-        projects_new = request.POST.getlist('projects')
-        default_project = request.POST.get('default_project')
-        projects_new.append(default_project)
-        projects_to_add = list(set(projects_new) - set(projects_old))
-        projects_to_remove = list(set(projects_old) - set(projects_new))
-
-        project_payload = {}
+        
+        info_res = client.get_user_info(user.get_token(), user_id)
+    except Exception as e:
+        log.exception(e)
+        info_res = {'error': True, 'data': str(e)}
+    if info_res['error']:
+        return __response_handler(request, info_res['data'], url=None,
+                                  status=info_res['data']['status'] if 'status' in info_res['data'] else 500)
+    else:
+        return __response_handler(request, info_res['data'], url=None, status=200)
 
-        for p in projects_to_remove:
-            project_payload["$"+str(p)] = None
-        for p in projects_to_add:
-            if p not in projects_old:
-                project_payload["$+"+str(p)] = str(p)
-        project_payload["$" + default_project] = None
-        project_payload["$+[0]"] = default_project
+@login_required
+def update(request, user_id=None):
+    user = osmutils.get_user(request)
+    try:
+        client = Client()
         payload = {}
-        if project_payload:
-            payload["projects"] = project_payload
+
         if request.POST.get('password') and request.POST.get('password') is not '':
             payload["password"] = request.POST.get('password')
 
+        if request.POST.getlist('map_project_name') and request.POST.getlist('map_role_name'):
+            project_param_name = request.POST.getlist('map_project_name')
+            role_param_ip = request.POST.getlist('map_role_name')
+            payload["project_role_mappings"] = []
+            for i, project in enumerate(project_param_name):
+                payload["project_role_mappings"].append({
+                    'project': project,
+                    'role': role_param_ip[i],
+                })
+        
         update_res = client.user_update(user.get_token(), user_id, payload)
     except Exception as e:
         log.exception(e)
@@ -119,7 +117,6 @@ def update(request, user_id=None):
                                   status=update_res['data']['status'] if 'status' in update_res['data'] else 500)
     else:
         return __response_handler(request, {}, url=None, status=200)
-        #return __response_handler(request, {}, 'users:list', to_redirect=True, )
 
 
 def __response_handler(request, data_res, url=None, to_redirect=None, *args, **kwargs):