Skip to content

Commit

Permalink
Management users view
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelagz committed Apr 17, 2024
1 parent 4c07d29 commit bf1eb3c
Show file tree
Hide file tree
Showing 10 changed files with 187 additions and 5 deletions.
39 changes: 38 additions & 1 deletion src/auth_and_perms/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

from django.conf import settings

from laboratory.utils import check_user_access_kwargs_org_lab
from laboratory.utils import check_user_access_kwargs_org_lab, get_actions_by_perms

logger = logging.getLogger('organilab')

Expand Down Expand Up @@ -359,3 +359,40 @@ class ValidateLabOrgObjectSerializer(serializers.Serializer):
allow_null=False,allow_empty=False)


class UserSerializer(serializers.ModelSerializer):
delete_msg = serializers.SerializerMethodField()
actions = serializers.SerializerMethodField()

def get_delete_msg(self, obj):
return "%s %s %s" % (_("The user"), obj.get_full_name(),
_("could have relations with multiple elements."))

def get_actions(self, obj):
user = self.context["request"].user
action_list = {
"destroy": ["auth.delete_user", "auth.view_user"]
}
return get_actions_by_perms(user, action_list)

class Meta:
model = User
fields = ['id', 'username', 'first_name', 'last_name', 'email', 'delete_msg',
'actions']


class UserDataTableSerializer(serializers.Serializer):
data = serializers.ListField(child=UserSerializer(), required=True)
draw = serializers.IntegerField(required=True)
recordsFiltered = serializers.IntegerField(required=True)
recordsTotal = serializers.IntegerField(required=True)


class UserFilter(FilterSet):
class Meta:
model = User
fields = {'id': ['exact'],
'username': ['icontains'],
'first_name': ['icontains'],
'last_name': ['icontains'],
'email': ['icontains'],
}
22 changes: 21 additions & 1 deletion src/auth_and_perms/api/viewsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
from django_filters.rest_framework import DjangoFilterBackend
from djgentelella.objectmanagement import AuthAllPermBaseObjectManagement
from rest_framework import mixins, viewsets, status
from rest_framework.authentication import SessionAuthentication
from rest_framework.filters import SearchFilter, OrderingFilter
Expand All @@ -23,7 +24,8 @@
ProfileAssociateOrganizationSerializer, ValidateGroupsByProfileSerializer, \
ShelfObjectSerializer, ValidateSearchShelfObjectSerializer, \
ShelfObjectDataTableSerializer, ValidateOrganizationSerializer, \
ExternalUserSerializer, AddExternalUserSerializer
ExternalUserSerializer, AddExternalUserSerializer, UserDataTableSerializer, \
UserSerializer, UserFilter
from auth_and_perms.forms import LaboratoryAndOrganizationForm, \
OrganizationForViewsetForm, SearchShelfObjectViewsetForm
from auth_and_perms.models import Rol, ProfilePermission, Profile
Expand Down Expand Up @@ -458,3 +460,21 @@ def get(self, request):
else:
return JsonResponse({"errors": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)


class UserManagementViewset(AuthAllPermBaseObjectManagement):
serializer_class = {
'list': UserDataTableSerializer,
'destroy': UserSerializer,
}
perms = {
'list': ["auth.view_user"],
'destroy': ["auth.delete_user"]
}

queryset = User.objects.all()
pagination_class = LimitOffsetPagination
filter_backends = (DjangoFilterBackend, SearchFilter, OrderingFilter)
search_fields = ['id', 'username', 'first_name', 'last_name', 'email'] # for the global search
filterset_class = UserFilter
ordering_fields = ['username', 'first_name']
ordering = ('id',) # default order
18 changes: 18 additions & 0 deletions src/auth_and_perms/management/commands/urlname_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2652,5 +2652,23 @@
'category': 'Equipment Type',
'permission': 'laboratory.delete_equipmenttype'
}
],
'manage_users': [
{
'name': 'Change User',
'category': 'User',
'permission': 'auth.change_user'
},
{
'name': 'Delete User',
'category': 'User',
'permission': 'auth.delete_user'
},
{
'name': 'View User',
'category': 'User',
'permission': 'auth.view_user'
}
]

}
76 changes: 76 additions & 0 deletions src/auth_and_perms/templates/auth_and_perms/users_list.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
{% extends 'base.html' %}
{% load i18n %}
{% load static %}
{% load urlname_tags %}
{% load gtsettings %}
{% block pre_head %}
{% define_urlname_action 'manage_users' %}
{% endblock %}

{% block title %}{% trans 'Users List' %}{% endblock %}

{% block content %}
<h1 class="text-center">{% trans 'Users List' %}</h1>

<div class="row">
<table class="table table-striped w-100 table-responsive" id="users_table"></table>
</div>

{% url "auth_and_perms:api-users-detail" 0 as delete_obj_url %}
{% include 'gentelella/blocks/modal_template_delete.html' with form=delete_form id="delete_obj_modal" form_id="delete_obj_form" url=delete_obj_url %}


{% endblock %}
{% block js %}
{{block.super}}
<script>
window.name = "userlistview";

const selects2_api_urls = {}

var object_urls = {
list_url: "{% url 'auth_and_perms:api-users-list' %}",
destroy_url: "{% url "auth_and_perms:api-users-detail" 0 %}",
}

datatable_inits = {
columns: [
{data: "id", name: "id", title: gettext("Id"), type: "string", visible: false},
{data: "username", name: "username", title: gettext("Username"), type: "string", visible: true},
{data: "first_name", name: "first_name", title: gettext("First Name"), type: "string", visible: true},
{data: "last_name", name: "last_name", title: gettext("Last Name"), type: "string", visible: true},
{data: "email", name: "email", title: gettext("Email"), type: "string", visible: true},
{data: "actions", name: "actions", title: gettext("Actions"), type: "string", visible: true}
],
addfilter: true
}
var users_modalids = {
destroy: "#delete_obj_modal",
}

var users_actions = {
table_actions: [], //table_actions
object_actions: [],
title: gettext('Actions'),
className: "no-export-col"
}

let objconfig={
urls: object_urls,
datatable_element: "#users_table",
modal_ids: users_modalids,
actions: users_actions,
datatable_inits: datatable_inits,
add_filter: true,
relation_render: {'field_autocomplete': 'text' },
delete_display: data => data['delete_msg'],
create: "btn-success"
}


let ocrud=ObjectCRUD("userscrudobj", objconfig)
ocrud.init();


</script>
{% endblock %}
7 changes: 5 additions & 2 deletions src/auth_and_perms/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
OrganizationAPI, \
UserLaboratoryOrganization, UserInOrganization, DeleteUserFromContenttypeViewSet, \
ProfileToContenttypeObjectAPI, UpdateGroupsByProfile, SearchShelfObjectOrganization, \
OrganizationButtons, ExternalUserToOrganizationViewSet
OrganizationButtons, ExternalUserToOrganizationViewSet, UserManagementViewset
from auth_and_perms.views import organizationstructure as orgstruct

from rest_framework.routers import SimpleRouter

from auth_and_perms.views import user_org_creation
from auth_and_perms.views import fva_rest_authentication
from auth_and_perms.views.select_organization import select_organization_by_user
from auth_and_perms.views.users import users_list
from authentication.views import SignDataRequestViewSet

routes = SimpleRouter()
Expand All @@ -24,6 +25,7 @@
routes.register('deluserorgcontt', DeleteUserFromContenttypeViewSet, 'api-deluserorgcontt' )
routes.register('relusertocontenttype', ProfileToContenttypeObjectAPI, 'api-relusertocontenttype' )
routes.register('searchshelfobjectorg', SearchShelfObjectOrganization, 'api-searchshelfobjectorg' )
routes.register('users_list', UserManagementViewset, basename='api-users')

app_name='auth_and_perms'

Expand All @@ -46,5 +48,6 @@
path('organization/manage/relorgcont/add/', orgstruct.add_contenttype_to_org, name="add_contenttype_to_org"),
path('digitalsignature/notify', SignDataRequestViewSet.as_view({'post': 'create'})),
path('update_groups_by_profile/', UpdateGroupsByProfile.as_view(), name="api_update_groups_by_profile"),
path('organization_buttons/', OrganizationButtons.as_view(), name="api_organization_buttons")
path('organization_buttons/', OrganizationButtons.as_view(), name="api_organization_buttons"),
path('users/', users_list, name="users_list")
]
5 changes: 5 additions & 0 deletions src/auth_and_perms/views/users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.shortcuts import render


def users_list(request):
return render(request,"auth_and_perms/users_list.html", context={})
2 changes: 1 addition & 1 deletion src/laboratory/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,6 @@ def has_object_permission(self, request, view, obj):

def get_actions_by_perms(user, actions_list):
actions = {}
for action, perms in actions_list.items() :
for action, perms in actions_list.items():
actions[action] = all_permission(user, perms)
return actions
9 changes: 9 additions & 0 deletions src/locale/es/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -4569,3 +4569,12 @@ msgstr "Actualizar consejo de prudencia"

msgid "Update the Danger indication"
msgstr "Actualizar indicacion de peligro"

msgid "Users List"
msgstr "Lista de Usuarios"

msgid "The user"
msgstr "El usuario"

msgid "could have relations with multiple elements."
msgstr "puede tener relaciones con múltiples elementos."
9 changes: 9 additions & 0 deletions src/locale/es/LC_MESSAGES/djangojs.po
Original file line number Diff line number Diff line change
Expand Up @@ -617,3 +617,12 @@ msgstr "¿Desea eliminar esta palabra de advertencia?"

msgid "Weight"
msgstr "Peso"

msgid "Username"
msgstr "Nombre de usuario"

msgid "First Name"
msgstr "Nombre"

msgid "Last Name"
msgstr "Apellidos"
5 changes: 5 additions & 0 deletions src/presentation/templates/partials/auth_and_perms.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
<a href="{% url 'auth_and_perms:organizationManager' %}" title="{% trans 'Manage Organizations' %}">
<i class='fa fa-university'></i> {% trans 'Manage Organizations' %}
</a>
</li>
<li>
<a href="{% url 'auth_and_perms:users_list' %}" title="{% trans 'Users' %}">
<i class='fa fa-users'></i> {% trans 'Users' %}
</a>
</li>
</ul>
</li>
Expand Down

0 comments on commit bf1eb3c

Please sign in to comment.