[WIP] user editing 69/6469/1
authorlombardofr <lombardo@everyup.it>
Tue, 11 Sep 2018 16:14:39 +0000 (18:14 +0200)
committerlombardofr <lombardo@everyup.it>
Tue, 11 Sep 2018 16:14:39 +0000 (18:14 +0200)
Change-Id: I0cb42614bb750d95bd03376924cf8c85d60cb2b7

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

index 482ff07..fa4117e 100644 (file)
@@ -107,6 +107,25 @@ class Client(object):
         result['data'] = Util.json_loads_byteified(r.text)
         return result
 
+    def user_update(self, token, id, user_data):
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/json", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+
+        _url = "{0}/admin/v1/users/{1}".format(self._base_path, id)
+        print _url
+        print user_data
+        try:
+            r = requests.post(_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:
+            result['error'] = False
+        result['data'] = Util.json_loads_byteified(r.text)
+        return result
+
     def user_delete(self, token, id):
         result = {'error': True, 'data': ''}
         headers = {"Content-Type": "application/yaml", "accept": "application/json",
index 88f4770..0c53b9e 100644 (file)
@@ -1,6 +1,5 @@
 function openModalCreateUser(args) {
-    console.log(args)
-    // load projects list
+
     select2_groups = $('#projects').select2({
         placeholder: 'Select Projects',
         width: '100%',
@@ -26,6 +25,57 @@ function openModalCreateUser(args) {
     $('#modal_new_user').modal('show');
 }
 
+function openModalEditUser(args) {
+    var url = '/admin/users/'+args.user_id;
+    console.log(url)
+    $("#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']})
+                    }
+                }
+
+                return {
+                    results: projects
+                };
+            }
+        }
+    });
+
+    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) {
index 7967cc6..21afce0 100644 (file)
@@ -6,7 +6,7 @@
                     <span aria-hidden="true">×</span></button>
                 <h4 class="modal-title">New User</h4>
             </div>
-            <form id="formCreateNS" action='{% url "users:create"   %}'
+            <form id="formCreateUser" action='{% url "users:create"   %}'
                   class="form-horizontal"
                   method="post" enctype="multipart/form-data">
                 {% csrf_token %}
index b278e22..d3c3d38 100644 (file)
@@ -4,32 +4,31 @@
             <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 User</h4>
+                <h4 class="modal-title">Edit User</h4>
             </div>
-            <form id="formCreateNS" action='{% url "users:update"   %}'
+            <form id="formEditUser" action=""
                   class="form-horizontal"
                   method="post" enctype="multipart/form-data">
                 {% csrf_token %}
                 <div class="modal-body" id="modal_edit_user_body">
                     <div class="form-group">
-                        <label for="username" class="col-sm-3 control-label">Username *</label>
+                        <label for="username_edit" class="col-sm-3 control-label">Username *</label>
                         <div class="col-sm-6">
-                            <input class="form-control" id="username" name="username"
+                            <input class="form-control" id="username_edit" name="username"
                                    placeholder="Username" required>
                         </div>
                     </div>
-
                     <div class="form-group">
-                        <label for="password" class="col-sm-3 control-label">Password *</label>
+                        <label for=projects" class="col-sm-3 control-label">Default project *</label>
                         <div class="col-sm-6">
-                           <input class="form-control" id="password" name="password" type="password"
-                                   placeholder="Password" required>
+                            <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" class="js-example-basic-multiple form-control" name="projects"
+                            <select required id="projects_edit" class="js-example-basic-multiple form-control" name="projects"
                             multiple="multiple">
                             </select>
                         </div>
index 621df92..b83ec32 100644 (file)
@@ -26,6 +26,8 @@
     {{ block.super }}
     {% include 'modal/user_details.html' %}
     {% include 'modal/user_create.html' %}
+    {% include 'modal/user_edit.html' %}
+
     {% csrf_token %}
     <div class="row">
         <div class="col-md-12">
                     <h3 class="box-title">Users</h3>
                     <div class="box-tools">
                         <button type="button" class="btn btn-default" data-container="body"
-                                onclick="javascript:openModalCreateUser({'projects_list_url': '{% url "projects:projects_list"  %}'})"
-                                        data-toggle="tooltip" data-placement="top" title="New User">
+                                onclick="javascript:openModalCreateUser({'projects_list_url': '{% url "projects:projects_list" %}'})"
+                                data-toggle="tooltip" data-placement="top" title="New User">
 
-                                    <i class="fa fa-plus"></i> Create User</button>
+                            <i class="fa fa-plus"></i> Create User
+                        </button>
 
                     </div>
                 </div>
                             <th>Projects</th>
                             <th>Identifier</th>
                             <th>Modified</th>
-                             <th>Created</th>
+                            <th>Created</th>
                             <th>Actions</th>
-
                         </tr>
                         </thead>
                         <tbody>
-
                         </tbody>
                     </table>
                 </div>
     <script src="/static/bower_components/select2/dist/js/select2.js"></script>
     <script src="/static/src/userhandler/user_list.js"></script>
     <script>
-    $(document).ready( function () {
-        var table = $('#users_table').DataTable({
-            responsive: true,
-            "ajax": {
-                "url": "/admin/users/list",
-                "dataSrc": function (json) {
-                    return json['users'];
-                },
-                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["username"];
+        $(document).ready(function () {
+            var table = $('#users_table').DataTable({
+                responsive: true,
+                "ajax": {
+                    "url": "/admin/users/list",
+                    "dataSrc": function (json) {
+                        return json['users'];
                     },
-                    "targets": 0
-                },
-                {
-                    "render": function (data, type, row) {
-                        return row['projects'];
+                    statusCode: {
+                        401: function () {
+                            console.log("no auth");
+                            moveToLogin(window.location.pathname);
+                        }
                     },
-                    "targets": 1
+                    "error": function (hxr, error, thrown) {
+                        console.log(hxr)
+                        console.log(thrown)
+                        console.log(error);
+                    }
+
                 },
-                {
-                    "render": function (data, type, row) {
-                        return row['_id'];
+                "columns": [
+                    {
+                        "render": function (data, type, row) {
+                            return row["username"];
+                        },
+                        "targets": 0
                     },
-                    "targets": 2
-                },
-                {
-                    "render": function (data, type, row) {
-                        return moment.unix(row["_admin"]['modified']).format('YYYY-MM-DD hh:mm:ss a');
+                    {
+                        "render": function (data, type, row) {
+                            return row['projects'];
+                        },
+                        "targets": 1
                     },
-                    "targets": 3
-                },
-                {
-                    "render": function (data, type, row) {
-                        return moment.unix(row["_admin"]['created']).format('YYYY-MM-DD hh:mm:ss a');;
+                    {
+                        "render": function (data, type, row) {
+                            return row['_id'];
+                        },
+                        "targets": 2
                     },
-                    "targets": 4
-                },
-                {
-                    "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:deleteUser(\'' + row['_id'] + '\', \''+row['username']+'\')"' +
-                        'style="color:red"><i class="fa fa-trash"></i> Delete</a></li> </ul></div>';
+                    {
+                        "render": function (data, type, row) {
+                            return moment.unix(row["_admin"]['modified']).format('YYYY-MM-DD hh:mm:ss a');
+                        },
+                        "targets": 3
                     },
-                    "targets": 5
-                }
-            ]
-        });
+                    {
+                        "render": function (data, type, row) {
+                            return moment.unix(row["_admin"]['created']).format('YYYY-MM-DD hh:mm:ss a');
+                        },
+                        "targets": 4
+                    },
+                    {
+                        "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: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>';
+                        },
+                        "targets": 5
+                    }
+                ]
+            });
 
-        setInterval(function () {
+            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 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) {
+                    $('#modal_edit_user').modal('hide');
+                    bootbox.alert({
+                        title: "Result",
+                        message: "User edited successfully."
+                    });
+                }).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>
 
 
index 05d88f0..9b07f43 100644 (file)
@@ -20,6 +20,7 @@ from userhandler import views
 urlpatterns = [
     url(r'^list$', views.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>[0-9a-zA-Z]+)/delete$', views.delete, name='delete')
 
 ]
\ No newline at end of file
index aa0d8d2..05d5925 100644 (file)
@@ -46,6 +46,22 @@ def delete(request, user_id=None):
         log.exception(e)
     return __response_handler(request, {}, 'users:list', to_redirect=True, )
 
+@login_required
+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)
+    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(',')