integrate the user-group list page with its api;

parent d40aa49d
......@@ -45,3 +45,19 @@ class JSONResponseMixin(object):
def render_json_response(self, 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
from rest_framework.response import Response
from rest_framework_bulk import ListBulkCreateUpdateDestroyAPIView
from .serializers import UserSerializer, UserGroupSerializer, UserAttributeSerializer, GroupUserEditSerializer, \
GroupEditSerializer, UserPKUpdateSerializer, UserBulkUpdateSerializer
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')
class UserListAddApi(generics.ListCreateAPIView):
class UserDetailApi(generics.RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
serializer_class = UserDetailSerializer
class UserDetailDeleteUpdateApi(generics.RetrieveUpdateDestroyAPIView):
class UserAndGroupEditApi(generics.RetrieveUpdateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
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
serializer_class = UserAndGroupSerializer
class UserResetPasswordApi(generics.UpdateAPIView):
queryset = User.objects.all()
serializer_class = GroupUserEditSerializer
serializer_class = UserDetailSerializer
def perform_update(self, serializer):
# Note: we are not updating the user object here.
......@@ -68,7 +45,7 @@ class UserResetPasswordApi(generics.UpdateAPIView):
class UserResetPKApi(generics.UpdateAPIView):
queryset = User.objects.all()
serializer_class = GroupUserEditSerializer
serializer_class = UserDetailSerializer
def perform_update(self, serializer):
user = self.get_object()
......@@ -88,9 +65,9 @@ class UserUpdatePKApi(generics.UpdateAPIView):
user.save()
class GroupEditApi(generics.RetrieveUpdateDestroyAPIView):
class GroupDetailApi(generics.RetrieveUpdateDestroyAPIView):
queryset = UserGroup.objects.all()
serializer_class = GroupEditSerializer
serializer_class = GroupDetailSerializer
def perform_update(self, serializer):
users = serializer.validated_data.get('users')
......@@ -105,27 +82,19 @@ class GroupEditApi(generics.RetrieveUpdateDestroyAPIView):
serializer.save()
class UserBulkUpdateApi(ListBulkCreateUpdateDestroyAPIView):
class UserListUpdateApi(BulkDeleteApiMixin, ListBulkCreateUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserBulkUpdateSerializer
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:
logger.error(str(e))
return queryset
if isinstance(ids, list):
queryset = queryset.filter(id__in=ids)
return queryset
class GroupListUpdateApi(BulkDeleteApiMixin, ListBulkCreateUpdateDestroyAPIView):
queryset = UserGroup.objects.all()
serializer_class = GroupBulkUpdateSerializer
class DeleteUserFromGroupApi(generics.DestroyAPIView):
queryset = UserGroup.objects.all()
serializer_class = GroupEditSerializer
serializer_class = GroupDetailSerializer
def destroy(self, request, *args, **kwargs):
group = self.get_object()
......
......@@ -8,47 +8,13 @@ from rest_framework_bulk import BulkListSerializer, BulkSerializerMixin
from .models import User, UserGroup
class UserSerializer(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 UserDetailSerializer(serializers.ModelSerializer):
class Meta:
model = User
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 Meta:
......@@ -70,6 +36,21 @@ class UserPKUpdateSerializer(serializers.ModelSerializer):
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):
group_display = serializers.SerializerMethodField()
active_display = serializers.SerializerMethodField()
......@@ -88,3 +69,16 @@ class UserBulkUpdateSerializer(BulkSerializerMixin, serializers.ModelSerializer)
def get_active_display(self, obj):
# TODO: user ative state
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(){
users: plain_id_list.map(Number)
};
$('#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() {
toastr.success('{% trans "The selected users has been added to current group." %}');
var html = "";
......
{% extends '_base_list.html' %}
{% load i18n static %}
{% load common_tags %}
{% block custom_head_css_js %}
<link href="{% static "css/plugins/sweetalert/sweetalert.css" %}" rel="stylesheet">
<script src="{% static "js/plugins/sweetalert/sweetalert.min.js" %}"></script>
{% endblock %}
{% block content_left_head %}
<a href="{% url 'users:user-group-create' %}" class="btn btn-sm btn-primary ">{% trans "Add User Group" %}</a>
{% endblock %}
{{ block.super }}
<style>
div.dataTables_wrapper div.dataTables_filter,
.dataTables_length {
float: right !important;
}
{% block table_head %}
<th class="text-center">
<input type="checkbox" id="check_all" onclick="checkAll('check_all', 'checked')">
</th>
<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>
div.dataTables_wrapper div.dataTables_filter {
margin-left: 15px;
}
</style>
{% endblock %}
{% block table_body %}
{% for user_group in user_group_list %}
<tr class="gradeX">
<td class="text-center">
<input type="checkbox" name="checked" value="{{ user_group.id }}">
</td>
<td class="text-center">
<a href="{% url 'users:user-group-detail' pk=user_group.id %}">
{{ user_group.name }}
</a>
</td>
<td class="text-center">{{ user_group.users.count }}</td>
<td class="text-center">999</td>
<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>
{% block table_search %}{% endblock %}
{% block table_container %}
<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>
<table class="table table-striped table-bordered table-hover " id="group_list_table" >
<thead>
<tr>
<th class="text-center">
<div class="checkbox checkbox-default"><input id="" type="checkbox" class="ipt_check_all"><label></label></div>
</th>
<th class="text-center">{% trans 'Name' %}</a></th>
<th class="text-center">{% trans 'User Amount' %}</a></th>
<th class="text-center">{% trans 'Asset Amount' %}</th>
<th class="text-center">{% trans 'Comment' %}</th>
<th class="text-center">{% trans 'Action' %}</th>
</tr>
{% endfor %}
{% endblock %}
{% block content_bottom_left %}
<form id="" method="get" action="" class=" mail-search">
<div class="input-group">
<select class="form-control m-b" style="width: auto">
<option>{% trans "Bulk Update" %}</option>
<option>{% trans "Bulk Export" %}</option>
<option>{% trans "Bulk Update" %}</option>
</select>
<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>
</thead>
</table>
<div id="actions" class="hide">
<div class="input-group">
<select class="form-control m-b" style="width: auto" id="slct_bulk_update">
<option value="delete">{% trans 'Delete selected' %}</option>
</select>
<div class="input-group-btn pull-left" style="padding-left: 5px;">
<button id='btn_bulk_update' style="height: 32px;" class="btn btn-sm btn-primary">
{% trans 'Submit' %}
</button>
</div>
</form>
</div>
</div>
{% endblock %}
{% block content_bottom_left %}{% endblock %}
{% block custom_foot_js %}
<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);
function doDelete() {
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 success = function() {
var msg = "{% trans 'Group Deleted.' %}";
......@@ -95,6 +109,48 @@ $(document).on('click', '.btn_delete_user_group', function(){
}, function() {
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>
{% endblock %}
{% extends '_base_list.html' %}
{% load i18n static %}
{% get_current_language as LANGUAGE_CODE %}
{% load common_tags %}
{% block custom_head_css_js %}
{{ block.super }}
<style>
......@@ -54,8 +52,7 @@ div.dataTables_wrapper div.dataTables_filter {
{% include "users/_user_bulk_update_modal.html" %}
{% include "users/_user_import_modal.html" %}
{% endblock %}
{% block content_bottom_left %}
{% endblock %}
{% block content_bottom_left %}{% endblock %}
{% block custom_foot_js %}
<script src="{% static 'js/jquery.form.min.js' %}"></script>
<script>
......
......@@ -35,22 +35,15 @@ urlpatterns = [
urlpatterns += [
url(r'^v1/users$', api.UserListAddApi.as_view(), name='user-list-api'),
url(r'^v1/users/update/$', api.UserBulkUpdateApi.as_view(), name='user-bulk-update-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/$', api.UserListUpdateApi.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>\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+)/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/(?P<pk>[0-9]+)$',
api.UserGroupDetailDeleteUpdateApi.as_view(), name='user-group-detail-api'),
url(r'^v1/user-groups/$', api.GroupListUpdateApi.as_view(), name='user-group-bulk-update-api'),
url(r'^v1/user-groups/(?P<pk>\d+)/$', api.GroupDetailApi.as_view(), name='user-group-detail-api'),
url(r'^v1/user-groups/(?P<pk>\d+)/user/(?P<uid>\d+)/$',
api.DeleteUserFromGroupApi.as_view(), name='delete-user-from-group-api'),
url(r'^v1/user-groups/(?P<pk>[0-9]+)/users/$',
api.GroupUserEditApi.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'),
url(r'^v1/user-groups/(?P<pk>\d+)/users/$',
api.UserAndGroupEditApi.as_view(), name='group-user-edit-api'),
]
......@@ -151,27 +151,12 @@ class UserDetailView(AdminUserRequiredMixin, DetailView):
return super(UserDetailView, self).get_context_data(**kwargs)
class UserGroupListView(AdminUserRequiredMixin, ListView):
model = UserGroup
paginate_by = settings.CONFIG.DISPLAY_PER_PAGE
context_object_name = 'user_group_list'
class UserGroupListView(AdminUserRequiredMixin, TemplateView):
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):
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
......
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