user upadate: add/revoke project access 09/6609/1
authorlombardofr <lombardo@everyup.it>
Wed, 3 Oct 2018 09:52:15 +0000 (11:52 +0200)
committerlombardofr <lombardo@everyup.it>
Wed, 3 Oct 2018 09:52:15 +0000 (11:52 +0200)
Change-Id: I81565801160e91fc10bb68ce92431bdab9383477

lib/osm/osmclient/clientv2.py
static/src/userhandler/user_list.js
userhandler/templates/modal/user_edit.html
userhandler/templates/user_list.html
userhandler/urls.py
userhandler/views.py

index ad7072e..414019e 100644 (file)
@@ -117,14 +117,15 @@ class Client(object):
 
         _url = "{0}/admin/v1/users/{1}".format(self._base_path, id)
         try:
-            r = requests.post(_url, json=user_data, verify=False, headers=headers)
+            r = requests.patch(_url, json=user_data, verify=False, headers=headers)
         except Exception as e:
             log.exception(e)
             result['data'] = str(e)
             return result
-        if r.status_code == requests.codes.created:
+        if r.status_code == requests.codes.no_content:
             result['error'] = False
-        result['data'] = Util.json_loads_byteified(r.text)
+        else:
+            result['data'] = Util.json_loads_byteified(r.text)
         return result
 
     def user_delete(self, token, id):
index 0c53b9e..afa1ae3 100644 (file)
@@ -26,59 +26,36 @@ function openModalCreateUser(args) {
 }
 
 function openModalEditUser(args) {
-    var url = '/admin/users/'+args.user_id;
-    console.log(url)
+    var url = '/admin/users/' + args.user_id;
+    var user_projects = args.projects ? args.projects.split(',') : [];
     $("#formEditUser").attr("action", url);
-    select2_groups = $('#projects_edit').select2({
-        placeholder: 'Select Projects',
-        width: '100%',
-        ajax: {
-            url: '/projects/list',
-            dataType: 'json',
-            processResults: function (data) {
-                projects = [];
-                if (data['projects']) {
-                    for (d in data['projects']) {
-                        var project = data['projects'][d];
-                        projects.push({id: project['_id'], text: project['name']})
-                    }
-                }
+    $("#projects_old").val(user_projects.toString());
+    $('#projects_edit').val(null).trigger('change');
+    $('#default_project_edit').val(null).trigger('change');
 
-                return {
-                    results: projects
-                };
-            }
+    if (user_projects.length > 0) {
+            // Create a DOM Option and pre-select by default
+            var newOption = new Option(user_projects[0], user_projects[0], true, true);
+            // Append it to the select
+            $('#default_project_edit').append(newOption).trigger('change');
+
+        for (var d in user_projects) {
+            var project = user_projects[d];
+            // Create a DOM Option and pre-select by default
+            var newOption = new Option(project, project, true, true);
+            // Append it to the select
+            $('#projects_edit').append(newOption).trigger('change');
         }
-    });
 
-    select2_single = $('#default_project_edit').select2({
-        placeholder: 'Select Default Project',
-        width: '100%',
-        ajax: {
-            url: '/projects/list',
-            dataType: 'json',
-            processResults: function (data) {
-                projects = [];
-                if (data['projects']) {
-                    for (d in data['projects']) {
-                        var project = data['projects'][d];
-                        projects.push({id: project['_id'], text: project['name']})
-                    }
-                }
+    }
 
-                return {
-                    results: projects
-                };
-            }
-        }
-    });
 
     $('#modal_edit_user').modal('show');
 }
 
 function deleteUser(user_id, name) {
-    var delete_url = '/admin/users/'+user_id+'/delete';
-    bootbox.confirm("Are you sure want to delete "+name+"?", function (confirm) {
+    var delete_url = '/admin/users/' + user_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>',
index d3c3d38..caeeb3a 100644 (file)
                   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">
-                    <div class="form-group">
+                    {% 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>
+                    </div>{% endcomment %}
                     <div class="form-group">
                         <label for=projects" class="col-sm-3 control-label">Default project *</label>
                         <div class="col-sm-6">
index b83ec32..2a0092f 100644 (file)
                                 '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: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:deleteUser(\'' + row['_id'] + '\', \'' + row['username'] + '\')"' +
                                 'style="color:red"><i class="fa fa-trash"></i> Delete</a></li> </ul></div>';
                         },
                 ]
             });
 
+            var select2_groups = $('#projects_edit').select2({
+                placeholder: 'Select Projects',
+                width: '100%',
+                ajax: {
+                    url: '/projects/list',
+                    dataType: 'json',
+                    processResults: function (data) {
+                        projects = [];
+                        if (data['projects']) {
+                            for (d in data['projects']) {
+                                var project = data['projects'][d];
+                                projects.push({
+                                    "id": project['_id'],
+                                    "text": project['name']
+                                });
+
+                            }
+                        }
+
+                        return {
+                            results: projects
+                        };
+                    }
+                }
+            });
+
+            var select2_single = $('#default_project_edit').select2({
+                placeholder: 'Select Default Project',
+                width: '100%',
+                ajax: {
+                    url: '/projects/list',
+                    dataType: 'json',
+                    processResults: function (data) {
+                        projects = [];
+                        if (data['projects']) {
+                            for (d in data['projects']) {
+                                var project = data['projects'][d];
+                                projects.push({
+                                    id: project['_id'],
+                                    text: project['name']
+                                });
+                            }
+                        }
+
+                        return {
+                            results: projects
+                        };
+                    }
+                }
+            });
+
             setInterval(function () {
                 table.ajax.reload();
             }, 10000);
             $("#formEditUser").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 request_method = $(this).attr("method");
                 var form_data = new FormData(this); //Encode form elements for submission
-                console.log(post_url);
+
                 $.ajax({
                     url: post_url,
                     type: request_method,
                     processData: false
                 }).done(function (response, textStatus, jqXHR) {
                     $('#modal_edit_user').modal('hide');
+                    table.ajax.reload();
                     bootbox.alert({
                         title: "Result",
-                        message: "User edited successfully."
+                        message: "User modified successfully."
                     });
+
                 }).fail(function (result) {
                     var data = result.responseJSON;
                     var title = "Error " + (data.code ? data.code : 'unknown');
index 9b07f43..2bd735b 100644 (file)
@@ -18,7 +18,7 @@ from django.conf.urls import url
 from userhandler import views
 
 urlpatterns = [
-    url(r'^list$', views.list, name='list'),
+    url(r'^list$', views.user_list, name='list'),
     url(r'^create$', views.create, name='create'),
     url(r'^(?P<user_id>[0-9a-zA-Z]+)', views.update, name='update'),
     url(r'^(?P<user_id>[0-9a-zA-Z]+)/delete$', views.delete, name='delete')
index 05d5925..3aa227a 100644 (file)
@@ -11,7 +11,7 @@ log = logging.getLogger(__name__)
 
 
 @login_required
-def list(request):
+def user_list(request):
     user = osmutils.get_user(request)
     client = Client()
     result = client.user_list(user.get_token())
@@ -51,18 +51,29 @@ def update(request, user_id=None):
     user = osmutils.get_user(request)
     try:
         client = Client()
-        user_data = {
-            "projects": request.POST.getlist('projects')
-        }
-        print user_data
-        update_res = client.user_update(user.get_token(), user_id, user_data)
+        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))
+
+        payload = {}
+
+        for p in projects_to_remove:
+            payload["$"+str(p)] = None
+        for p in projects_to_add:
+            if p not in projects_old:
+                payload["$+"+str(p)] = str(p)
+        payload["$" + default_project] = None
+        payload["$+[0]"] = default_project
+
+        update_res = client.user_update(user.get_token(), user_id, {"projects": payload})
     except Exception as e:
         log.exception(e)
     return __response_handler(request, {}, 'users:list', to_redirect=True, )
 
 
-
-
 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: