integrate the user-group list page with its api;

parent d40aa49d
...@@ -45,3 +45,19 @@ class JSONResponseMixin(object): ...@@ -45,3 +45,19 @@ class JSONResponseMixin(object):
def render_json_response(self, context): def render_json_response(self, context):
return JsonResponse(context) return JsonResponse(context)
class BulkDeleteApiMixin(object):
def filter_queryset(self, queryset):
id_list = self.request.query_params.get('id__in')
if id_list:
import json
try:
ids = json.loads(id_list)
except Exception as e:
print e
return queryset
if isinstance(ids, list):
queryset = queryset.filter(id__in=ids)
return queryset
...@@ -9,51 +9,28 @@ from rest_framework import generics, status ...@@ -9,51 +9,28 @@ from rest_framework import generics, status
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework_bulk import ListBulkCreateUpdateDestroyAPIView from rest_framework_bulk import ListBulkCreateUpdateDestroyAPIView
from .serializers import UserSerializer, UserGroupSerializer, UserAttributeSerializer, GroupUserEditSerializer, \
GroupEditSerializer, UserPKUpdateSerializer, UserBulkUpdateSerializer
from .models import User, UserGroup from .models import User, UserGroup
from .serializers import UserDetailSerializer, UserAndGroupSerializer, \
GroupDetailSerializer, UserPKUpdateSerializer, UserBulkUpdateSerializer, GroupBulkUpdateSerializer
from common.mixins import BulkDeleteApiMixin
logger = logging.getLogger('jumpserver.users.api') logger = logging.getLogger('jumpserver.users.api')
class UserListAddApi(generics.ListCreateAPIView): class UserDetailApi(generics.RetrieveUpdateDestroyAPIView):
queryset = User.objects.all() queryset = User.objects.all()
serializer_class = UserSerializer serializer_class = UserDetailSerializer
class UserDetailDeleteUpdateApi(generics.RetrieveUpdateDestroyAPIView): class UserAndGroupEditApi(generics.RetrieveUpdateAPIView):
queryset = User.objects.all() queryset = User.objects.all()
serializer_class = UserSerializer serializer_class = UserAndGroupSerializer
def delete(self, request, *args, **kwargs):
print(self.request.data)
return super(UserDetailDeleteUpdateApi, self).delete(request, *args, **kwargs)
class UserGroupListAddApi(generics.ListCreateAPIView):
queryset = UserGroup.objects.all()
serializer_class = UserGroupSerializer
class UserGroupDetailDeleteUpdateApi(generics.RetrieveUpdateDestroyAPIView):
queryset = UserGroup.objects.all()
serializer_class = UserGroupSerializer
class UserAttributeApi(generics.RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserAttributeSerializer
class GroupUserEditApi(generics.RetrieveUpdateAPIView):
queryset = User.objects.all()
serializer_class = GroupUserEditSerializer
class UserResetPasswordApi(generics.UpdateAPIView): class UserResetPasswordApi(generics.UpdateAPIView):
queryset = User.objects.all() queryset = User.objects.all()
serializer_class = GroupUserEditSerializer serializer_class = UserDetailSerializer
def perform_update(self, serializer): def perform_update(self, serializer):
# Note: we are not updating the user object here. # Note: we are not updating the user object here.
...@@ -68,7 +45,7 @@ class UserResetPasswordApi(generics.UpdateAPIView): ...@@ -68,7 +45,7 @@ class UserResetPasswordApi(generics.UpdateAPIView):
class UserResetPKApi(generics.UpdateAPIView): class UserResetPKApi(generics.UpdateAPIView):
queryset = User.objects.all() queryset = User.objects.all()
serializer_class = GroupUserEditSerializer serializer_class = UserDetailSerializer
def perform_update(self, serializer): def perform_update(self, serializer):
user = self.get_object() user = self.get_object()
...@@ -88,9 +65,9 @@ class UserUpdatePKApi(generics.UpdateAPIView): ...@@ -88,9 +65,9 @@ class UserUpdatePKApi(generics.UpdateAPIView):
user.save() user.save()
class GroupEditApi(generics.RetrieveUpdateDestroyAPIView): class GroupDetailApi(generics.RetrieveUpdateDestroyAPIView):
queryset = UserGroup.objects.all() queryset = UserGroup.objects.all()
serializer_class = GroupEditSerializer serializer_class = GroupDetailSerializer
def perform_update(self, serializer): def perform_update(self, serializer):
users = serializer.validated_data.get('users') users = serializer.validated_data.get('users')
...@@ -105,27 +82,19 @@ class GroupEditApi(generics.RetrieveUpdateDestroyAPIView): ...@@ -105,27 +82,19 @@ class GroupEditApi(generics.RetrieveUpdateDestroyAPIView):
serializer.save() serializer.save()
class UserBulkUpdateApi(ListBulkCreateUpdateDestroyAPIView): class UserListUpdateApi(BulkDeleteApiMixin, ListBulkCreateUpdateDestroyAPIView):
queryset = User.objects.all() queryset = User.objects.all()
serializer_class = UserBulkUpdateSerializer serializer_class = UserBulkUpdateSerializer
def filter_queryset(self, queryset):
id_list = self.request.query_params.get('id__in') class GroupListUpdateApi(BulkDeleteApiMixin, ListBulkCreateUpdateDestroyAPIView):
if id_list: queryset = UserGroup.objects.all()
import json serializer_class = GroupBulkUpdateSerializer
try:
ids = json.loads(id_list)
except Exception as e:
logger.error(str(e))
return queryset
if isinstance(ids, list):
queryset = queryset.filter(id__in=ids)
return queryset
class DeleteUserFromGroupApi(generics.DestroyAPIView): class DeleteUserFromGroupApi(generics.DestroyAPIView):
queryset = UserGroup.objects.all() queryset = UserGroup.objects.all()
serializer_class = GroupEditSerializer serializer_class = GroupDetailSerializer
def destroy(self, request, *args, **kwargs): def destroy(self, request, *args, **kwargs):
group = self.get_object() group = self.get_object()
......
...@@ -8,47 +8,13 @@ from rest_framework_bulk import BulkListSerializer, BulkSerializerMixin ...@@ -8,47 +8,13 @@ from rest_framework_bulk import BulkListSerializer, BulkSerializerMixin
from .models import User, UserGroup from .models import User, UserGroup
class UserSerializer(serializers.ModelSerializer): class UserDetailSerializer(serializers.ModelSerializer):
groups = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='users:user-group-detail-api')
class Meta:
model = User
exclude = [
'password', 'first_name', 'last_name', 'secret_key_otp',
'private_key', 'public_key', 'avatar',
]
class UserGroupSerializer(serializers.ModelSerializer):
users = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='users:user-detail-api')
class Meta:
model = UserGroup
fields = '__all__'
class GroupEditSerializer(serializers.ModelSerializer):
class Meta:
model = UserGroup
fields = ['id', 'name', 'comment', 'date_created', 'created_by', 'users']
class UserAttributeSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = User model = User
fields = ['avatar', 'wechat', 'phone', 'enable_otp', 'comment', 'is_active', 'name'] fields = ['avatar', 'wechat', 'phone', 'enable_otp', 'comment', 'is_active', 'name']
class GroupUserEditSerializer(serializers.ModelSerializer):
groups = serializers.PrimaryKeyRelatedField(many=True, queryset=UserGroup.objects.all())
class Meta:
model = User
fields = ['id', 'groups']
class UserPKUpdateSerializer(serializers.ModelSerializer): class UserPKUpdateSerializer(serializers.ModelSerializer):
class Meta: class Meta:
...@@ -70,6 +36,21 @@ class UserPKUpdateSerializer(serializers.ModelSerializer): ...@@ -70,6 +36,21 @@ class UserPKUpdateSerializer(serializers.ModelSerializer):
return value return value
class UserAndGroupSerializer(serializers.ModelSerializer):
groups = serializers.PrimaryKeyRelatedField(many=True, queryset=UserGroup.objects.all())
class Meta:
model = User
fields = ['id', 'groups']
class GroupDetailSerializer(serializers.ModelSerializer):
class Meta:
model = UserGroup
fields = ['id', 'name', 'comment', 'date_created', 'created_by', 'users']
class UserBulkUpdateSerializer(BulkSerializerMixin, serializers.ModelSerializer): class UserBulkUpdateSerializer(BulkSerializerMixin, serializers.ModelSerializer):
group_display = serializers.SerializerMethodField() group_display = serializers.SerializerMethodField()
active_display = serializers.SerializerMethodField() active_display = serializers.SerializerMethodField()
...@@ -88,3 +69,16 @@ class UserBulkUpdateSerializer(BulkSerializerMixin, serializers.ModelSerializer) ...@@ -88,3 +69,16 @@ class UserBulkUpdateSerializer(BulkSerializerMixin, serializers.ModelSerializer)
def get_active_display(self, obj): def get_active_display(self, obj):
# TODO: user ative state # TODO: user ative state
return not (obj.is_expired and obj.is_active) return not (obj.is_expired and obj.is_active)
class GroupBulkUpdateSerializer(BulkSerializerMixin, serializers.ModelSerializer):
user_amount = serializers.SerializerMethodField()
class Meta:
model = UserGroup
list_serializer_class = BulkListSerializer
fields = ['id', 'name', 'comment', 'user_amount']
def get_user_amount(self, obj):
return obj.users.count()
...@@ -218,7 +218,7 @@ $(document).on('click', '.btn_remove', function(){ ...@@ -218,7 +218,7 @@ $(document).on('click', '.btn_remove', function(){
users: plain_id_list.map(Number) users: plain_id_list.map(Number)
}; };
$('#select_user_modal').modal('hide'); $('#select_user_modal').modal('hide');
var the_url = "{% url 'users:user-group-edit-api' pk=object.id %}"; var the_url = "{% url 'users:user-group-detail-api' pk=object.id %}";
var success = function() { var success = function() {
toastr.success('{% trans "The selected users has been added to current group." %}'); toastr.success('{% trans "The selected users has been added to current group." %}');
var html = ""; var html = "";
......
{% extends '_base_list.html' %} {% extends '_base_list.html' %}
{% load i18n static %} {% load i18n static %}
{% load common_tags %}
{% block custom_head_css_js %} {% block custom_head_css_js %}
<link href="{% static "css/plugins/sweetalert/sweetalert.css" %}" rel="stylesheet"> {{ block.super }}
<script src="{% static "js/plugins/sweetalert/sweetalert.min.js" %}"></script> <style>
{% endblock %} div.dataTables_wrapper div.dataTables_filter,
.dataTables_length {
{% block content_left_head %} float: right !important;
<a href="{% url 'users:user-group-create' %}" class="btn btn-sm btn-primary ">{% trans "Add User Group" %}</a> }
{% endblock %}
{% block table_head %} div.dataTables_wrapper div.dataTables_filter {
<th class="text-center"> margin-left: 15px;
<input type="checkbox" id="check_all" onclick="checkAll('check_all', 'checked')"> }
</th> </style>
<th class="text-center"><a href="{% url 'users:user-group-list' %}?sort=name">{% trans "Name" %}</a></th>
<th class="text-center">{% trans "User Amount" %}</th>
<th class="text-center">{% trans "Asset Amount" %}</th>
<th class="text-center">{% trans "Comment" %}</th>
<th class="text-center"></th>
{% endblock %} {% endblock %}
{% block table_search %}{% endblock %}
{% block table_body %} {% block table_container %}
{% for user_group in user_group_list %} <div class="pull-left m-r-5"><a href="{% url 'users:user-group-create' %}" class="btn btn-sm btn-primary ">{% trans "Add User Group" %}</a></div>
<tr class="gradeX"> <table class="table table-striped table-bordered table-hover " id="group_list_table" >
<td class="text-center"> <thead>
<input type="checkbox" name="checked" value="{{ user_group.id }}"> <tr>
</td> <th class="text-center">
<td class="text-center"> <div class="checkbox checkbox-default"><input id="" type="checkbox" class="ipt_check_all"><label></label></div>
<a href="{% url 'users:user-group-detail' pk=user_group.id %}"> </th>
{{ user_group.name }} <th class="text-center">{% trans 'Name' %}</a></th>
</a> <th class="text-center">{% trans 'User Amount' %}</a></th>
</td> <th class="text-center">{% trans 'Asset Amount' %}</th>
<td class="text-center">{{ user_group.users.count }}</td> <th class="text-center">{% trans 'Comment' %}</th>
<td class="text-center">999</td> <th class="text-center">{% trans 'Action' %}</th>
<th class="text-center">{{ user_group.comment|truncatewords:8 }}</th>
<td class="text-center">
<a href="{% url 'users:user-group-update' pk=user_group.id %}" class="btn btn-xs btn-info">{% trans "Edit" %}</a>
<a href="javascript:void(0)" data-gid="{{ user_group.id }}"
class="btn btn-xs btn-danger del {% ifequal user_group.name 'Default' %}disabled{% else %}btn_delete_user_group{% endifequal %}">{% trans "Delete" %}</a>
</td>
</tr> </tr>
{% endfor %} </thead>
{% endblock %} </table>
<div id="actions" class="hide">
{% block content_bottom_left %} <div class="input-group">
<form id="" method="get" action="" class=" mail-search"> <select class="form-control m-b" style="width: auto" id="slct_bulk_update">
<div class="input-group"> <option value="delete">{% trans 'Delete selected' %}</option>
<select class="form-control m-b" style="width: auto"> </select>
<option>{% trans "Bulk Update" %}</option> <div class="input-group-btn pull-left" style="padding-left: 5px;">
<option>{% trans "Bulk Export" %}</option> <button id='btn_bulk_update' style="height: 32px;" class="btn btn-sm btn-primary">
<option>{% trans "Bulk Update" %}</option> {% trans 'Submit' %}
</select> </button>
<div class="input-group-btn pull-left" style="padding-left: 5px;">
<button id='search_btn' type="submit" style="height: 32px;" class="btn btn-sm btn-primary">{% trans "Confirm" %}</button>
</div>
</div> </div>
</form> </div>
</div>
{% endblock %} {% endblock %}
{% block content_bottom_left %}{% endblock %}
{% block custom_foot_js %} {% block custom_foot_js %}
<script> <script>
$(document).on('click', '.btn_delete_user_group', function(){ $(document).ready(function() {
var options = {
ele: $('#group_list_table'),
buttons: [],
columnDefs: [
{targets: 1, createdCell: function (td, cellData, rowData) {
var detail_btn = '<a href="{% url "users:user-group-detail" pk=99991937 %}">' + cellData + '</a>';
$(td).html(detail_btn.replace('99991937', rowData.id));
}},
{targets: 4, createdCell: function (td, cellData) {
var innerHtml = cellData.length > 18 ? cellData.substring(0, 18) + '...': cellData;
$(td).html('<a href="javascript:void(0);" data-toggle="tooltip" title="' + cellData + '">' + innerHtml + '</a>');
}},
{targets: 5, createdCell: function (td, cellData, rowData) {
var update_btn = '<a href="{% url "users:user-group-update" pk=99991937 %}" class="btn btn-xs btn-info">{% trans "Update" %}</a>'.replace('99991937', cellData);
var del_btn = '<a class="btn btn-xs btn-danger m-l-xs btn_delete_user_group" data-uid="99991937">{% trans "Delete" %}</a>'.replace('99991937', cellData);
if (rowData.id === 1) {
$(td).html(update_btn)
} else {
$(td).html(update_btn + del_btn)
}
}}],
ajax_url: '{% url "users:user-group-bulk-update-api" %}',
columns: [{data: function(){return ""}}, {data: "name" }, {data: "user_amount"},
{data: function(){return 999}}, {data: "comment"}, {data: "id" }],
op_html: $('#actions').html()
};
jumpserver.initDataTable(options);
}).on('click', '.btn_delete_user_group', function(){
var $this = $(this); var $this = $(this);
function doDelete() { function doDelete() {
var group_id = $this.data('gid'); var group_id = $this.data('gid');
var the_url = "{% url 'users:user-group-edit-api' 99991937 %}".replace('99991937', group_id); var the_url = "{% url 'users:user-group-detail-api' 99991937 %}".replace('99991937', group_id);
var body = {}; var body = {};
var success = function() { var success = function() {
var msg = "{% trans 'Group Deleted.' %}"; var msg = "{% trans 'Group Deleted.' %}";
...@@ -95,6 +109,48 @@ $(document).on('click', '.btn_delete_user_group', function(){ ...@@ -95,6 +109,48 @@ $(document).on('click', '.btn_delete_user_group', function(){
}, function() { }, function() {
doDelete(); doDelete();
}); });
}).on('click', '#btn_bulk_update', function(){
var action = $('#slct_bulk_update').val();
var $data_table = $('#group_list_table').DataTable()
var plain_id_list = [];
$data_table.rows({selected: true}).every(function(){
plain_id_list.push(this.data().id);
});
if (plain_id_list === []) {
return false;
};
var the_url = "{% url 'users:user-group-bulk-update-api' %}";
function doDelete() {
swal({
title: "{% trans 'Are you sure?' %}",
text: "{% trans 'This will delete the selected groups !!!' %}",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "{% trans 'Confirm' %}",
closeOnConfirm: false
}, function() {
var success = function() {
var msg = "{% trans 'UserGroups Deleted.' %}";
swal("{% trans 'UserGroups Delete' %}", msg, "success");
$data_table.ajax.reload();
};
var fail = function() {
var msg = "{% trans 'UserGroup Deleting failed.' %}";
swal("{% trans 'UserGroups Delete' %}", msg, "error");
};
var url_delete = the_url + '?id__in=' + JSON.stringify(plain_id_list);
APIUpdateAttr({url: url_delete, method: 'DELETE', success: success, error: fail});
jumpserver.checked = false;
});
}
switch(action) {
case 'delete':
doDelete();
break;
default:
break;
}
}) })
</script> </script>
{% endblock %} {% endblock %}
{% extends '_base_list.html' %} {% extends '_base_list.html' %}
{% load i18n static %} {% load i18n static %}
{% get_current_language as LANGUAGE_CODE %}
{% load common_tags %}
{% block custom_head_css_js %} {% block custom_head_css_js %}
{{ block.super }} {{ block.super }}
<style> <style>
...@@ -54,8 +52,7 @@ div.dataTables_wrapper div.dataTables_filter { ...@@ -54,8 +52,7 @@ div.dataTables_wrapper div.dataTables_filter {
{% include "users/_user_bulk_update_modal.html" %} {% include "users/_user_bulk_update_modal.html" %}
{% include "users/_user_import_modal.html" %} {% include "users/_user_import_modal.html" %}
{% endblock %} {% endblock %}
{% block content_bottom_left %} {% block content_bottom_left %}{% endblock %}
{% endblock %}
{% block custom_foot_js %} {% block custom_foot_js %}
<script src="{% static 'js/jquery.form.min.js' %}"></script> <script src="{% static 'js/jquery.form.min.js' %}"></script>
<script> <script>
......
...@@ -35,22 +35,15 @@ urlpatterns = [ ...@@ -35,22 +35,15 @@ urlpatterns = [
urlpatterns += [ urlpatterns += [
url(r'^v1/users$', api.UserListAddApi.as_view(), name='user-list-api'), url(r'^v1/users/$', api.UserListUpdateApi.as_view(), name='user-bulk-update-api'),
url(r'^v1/users/update/$', api.UserBulkUpdateApi.as_view(), name='user-bulk-update-api'), url(r'^v1/users/(?P<pk>\d+)/$', api.UserDetailApi.as_view(), name='user-patch-api'),
url(r'^v1/users/(?P<pk>[0-9]+)$',
api.UserDetailDeleteUpdateApi.as_view(), name='user-detail-api'),
url(r'^v1/users/(?P<pk>[0-9]+)/patch$',
api.UserAttributeApi.as_view(), name='user-patch-api'),
url(r'^v1/users/(?P<pk>\d+)/reset-password/$', api.UserResetPasswordApi.as_view(), name='user-reset-password-api'), url(r'^v1/users/(?P<pk>\d+)/reset-password/$', api.UserResetPasswordApi.as_view(), name='user-reset-password-api'),
url(r'^v1/users/(?P<pk>\d+)/reset-pk/$', api.UserResetPKApi.as_view(), name='user-reset-pk-api'), url(r'^v1/users/(?P<pk>\d+)/reset-pk/$', api.UserResetPKApi.as_view(), name='user-reset-pk-api'),
url(r'^v1/users/(?P<pk>\d+)/update-pk/$', api.UserUpdatePKApi.as_view(), name='user-update-pk-api'), url(r'^v1/users/(?P<pk>\d+)/update-pk/$', api.UserUpdatePKApi.as_view(), name='user-update-pk-api'),
url(r'^v1/user-groups$', api.UserGroupListAddApi.as_view(), name='user-group-list-api'), url(r'^v1/user-groups/$', api.GroupListUpdateApi.as_view(), name='user-group-bulk-update-api'),
url(r'^v1/user-groups/(?P<pk>[0-9]+)$', url(r'^v1/user-groups/(?P<pk>\d+)/$', api.GroupDetailApi.as_view(), name='user-group-detail-api'),
api.UserGroupDetailDeleteUpdateApi.as_view(), name='user-group-detail-api'),
url(r'^v1/user-groups/(?P<pk>\d+)/user/(?P<uid>\d+)/$', url(r'^v1/user-groups/(?P<pk>\d+)/user/(?P<uid>\d+)/$',
api.DeleteUserFromGroupApi.as_view(), name='delete-user-from-group-api'), api.DeleteUserFromGroupApi.as_view(), name='delete-user-from-group-api'),
url(r'^v1/user-groups/(?P<pk>[0-9]+)/users/$', url(r'^v1/user-groups/(?P<pk>\d+)/users/$',
api.GroupUserEditApi.as_view(), name='group-user-edit-api'), api.UserAndGroupEditApi.as_view(), name='group-user-edit-api'),
url(r'^v1/user-groups/(?P<pk>[0-9]+)/edit/$', api.GroupEditApi.as_view(),
name='user-group-edit-api'),
] ]
...@@ -151,27 +151,12 @@ class UserDetailView(AdminUserRequiredMixin, DetailView): ...@@ -151,27 +151,12 @@ class UserDetailView(AdminUserRequiredMixin, DetailView):
return super(UserDetailView, self).get_context_data(**kwargs) return super(UserDetailView, self).get_context_data(**kwargs)
class UserGroupListView(AdminUserRequiredMixin, ListView): class UserGroupListView(AdminUserRequiredMixin, TemplateView):
model = UserGroup
paginate_by = settings.CONFIG.DISPLAY_PER_PAGE
context_object_name = 'user_group_list'
template_name = 'users/user_group_list.html' template_name = 'users/user_group_list.html'
ordering = '-date_created'
def get_queryset(self):
self.queryset = super(UserGroupListView, self).get_queryset()
self.keyword = keyword = self.request.GET.get('keyword', '')
self.sort = sort = self.request.GET.get('sort')
if keyword:
self.queryset = self.queryset.filter(name__icontains=keyword)
if sort:
self.queryset = self.queryset.order_by(sort)
return self.queryset
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(UserGroupListView, self).get_context_data(**kwargs) context = super(UserGroupListView, self).get_context_data(**kwargs)
context.update({'app': _('Users'), 'action': _('User group list'), 'keyword': self.keyword}) context.update({'app': _('Users'), 'action': _('User group list')})
return context return context
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment