Реализовал систему разрешений
This commit is contained in:
180
dbapp/mainapp/views/user_permissions.py
Normal file
180
dbapp/mainapp/views/user_permissions.py
Normal file
@@ -0,0 +1,180 @@
|
||||
"""
|
||||
Views для управления правами пользователей.
|
||||
"""
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib import messages
|
||||
from django.http import JsonResponse
|
||||
from django.shortcuts import render, get_object_or_404, redirect
|
||||
from django.views import View
|
||||
|
||||
from ..models import CustomUser, UserPermission
|
||||
from ..permissions import (
|
||||
PERMISSIONS,
|
||||
DEFAULT_ROLE_PERMISSIONS,
|
||||
PermissionRequiredMixin,
|
||||
has_permission
|
||||
)
|
||||
|
||||
|
||||
class UserPermissionsListView(LoginRequiredMixin, PermissionRequiredMixin, View):
|
||||
"""Список пользователей с их правами."""
|
||||
permission_required = 'admin_access'
|
||||
|
||||
def get(self, request):
|
||||
users = CustomUser.objects.select_related('user').prefetch_related(
|
||||
'user_permissions'
|
||||
).order_by('user__username')
|
||||
|
||||
context = {
|
||||
'users': users,
|
||||
'permissions': PERMISSIONS,
|
||||
'default_permissions': DEFAULT_ROLE_PERMISSIONS,
|
||||
}
|
||||
return render(request, 'mainapp/user_permissions_list.html', context)
|
||||
|
||||
|
||||
class UserPermissionsEditView(LoginRequiredMixin, PermissionRequiredMixin, View):
|
||||
"""Редактирование прав конкретного пользователя."""
|
||||
permission_required = 'admin_access'
|
||||
|
||||
def get(self, request, pk):
|
||||
custom_user = get_object_or_404(CustomUser.objects.select_related('user'), pk=pk)
|
||||
|
||||
# Получаем все разрешения
|
||||
all_permissions = UserPermission.objects.all()
|
||||
|
||||
# Текущие разрешения пользователя
|
||||
user_perm_codes = set(custom_user.user_permissions.values_list('code', flat=True))
|
||||
|
||||
# Права по умолчанию для роли
|
||||
default_perms = set(DEFAULT_ROLE_PERMISSIONS.get(custom_user.role, []))
|
||||
|
||||
# Группируем разрешения по категориям
|
||||
permission_groups = {
|
||||
'Источники': [],
|
||||
'Заявки': [],
|
||||
'Точки ГЛ': [],
|
||||
'Спутники': [],
|
||||
'Транспондеры': [],
|
||||
'Тех. анализ': [],
|
||||
'Отметки': [],
|
||||
'Прочее': [],
|
||||
}
|
||||
|
||||
for code, name, desc in PERMISSIONS:
|
||||
perm_data = {
|
||||
'code': code,
|
||||
'name': name,
|
||||
'description': desc,
|
||||
'has_permission': code in user_perm_codes if custom_user.use_custom_permissions else code in default_perms,
|
||||
'is_default': code in default_perms,
|
||||
}
|
||||
|
||||
if code.startswith('source_'):
|
||||
permission_groups['Источники'].append(perm_data)
|
||||
elif code.startswith('request_'):
|
||||
permission_groups['Заявки'].append(perm_data)
|
||||
elif code.startswith('objitem_'):
|
||||
permission_groups['Точки ГЛ'].append(perm_data)
|
||||
elif code.startswith('satellite_'):
|
||||
permission_groups['Спутники'].append(perm_data)
|
||||
elif code.startswith('transponder_'):
|
||||
permission_groups['Транспондеры'].append(perm_data)
|
||||
elif code.startswith('tech_analyze_'):
|
||||
permission_groups['Тех. анализ'].append(perm_data)
|
||||
elif code.startswith('mark_'):
|
||||
permission_groups['Отметки'].append(perm_data)
|
||||
else:
|
||||
permission_groups['Прочее'].append(perm_data)
|
||||
|
||||
context = {
|
||||
'custom_user': custom_user,
|
||||
'permission_groups': permission_groups,
|
||||
'default_perms': default_perms,
|
||||
}
|
||||
return render(request, 'mainapp/user_permissions_edit.html', context)
|
||||
|
||||
def post(self, request, pk):
|
||||
custom_user = get_object_or_404(CustomUser, pk=pk)
|
||||
|
||||
# Получаем выбранные разрешения
|
||||
selected_permissions = request.POST.getlist('permissions')
|
||||
use_custom = request.POST.get('use_custom_permissions') == 'on'
|
||||
|
||||
# Обновляем флаг использования индивидуальных разрешений
|
||||
custom_user.use_custom_permissions = use_custom
|
||||
|
||||
if use_custom:
|
||||
# Очищаем текущие разрешения и добавляем новые
|
||||
custom_user.user_permissions.clear()
|
||||
|
||||
for perm_code in selected_permissions:
|
||||
perm, created = UserPermission.objects.get_or_create(code=perm_code)
|
||||
custom_user.user_permissions.add(perm)
|
||||
|
||||
custom_user.save()
|
||||
|
||||
messages.success(request, f'Права пользователя {custom_user.user.username} обновлены.')
|
||||
return redirect('mainapp:user_permissions_list')
|
||||
|
||||
|
||||
class UserPermissionsApiView(LoginRequiredMixin, PermissionRequiredMixin, View):
|
||||
"""API для управления правами пользователей."""
|
||||
permission_required = 'admin_access'
|
||||
|
||||
def post(self, request, pk):
|
||||
"""Обновление прав пользователя через AJAX."""
|
||||
import json
|
||||
|
||||
try:
|
||||
data = json.loads(request.body)
|
||||
custom_user = get_object_or_404(CustomUser, pk=pk)
|
||||
|
||||
use_custom = data.get('use_custom_permissions', False)
|
||||
permissions = data.get('permissions', [])
|
||||
|
||||
custom_user.use_custom_permissions = use_custom
|
||||
|
||||
if use_custom:
|
||||
custom_user.user_permissions.clear()
|
||||
for perm_code in permissions:
|
||||
perm, _ = UserPermission.objects.get_or_create(code=perm_code)
|
||||
custom_user.user_permissions.add(perm)
|
||||
|
||||
custom_user.save()
|
||||
|
||||
return JsonResponse({
|
||||
'success': True,
|
||||
'message': f'Права пользователя {custom_user.user.username} обновлены'
|
||||
})
|
||||
except Exception as e:
|
||||
return JsonResponse({
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}, status=400)
|
||||
|
||||
|
||||
|
||||
class InitPermissionsView(LoginRequiredMixin, PermissionRequiredMixin, View):
|
||||
"""Инициализация всех разрешений в базе данных."""
|
||||
permission_required = 'admin_access'
|
||||
|
||||
def get(self, request):
|
||||
from ..permissions import PERMISSIONS
|
||||
|
||||
created_count = 0
|
||||
existing_count = 0
|
||||
|
||||
for code, name, description in PERMISSIONS:
|
||||
perm, created = UserPermission.objects.get_or_create(code=code)
|
||||
if created:
|
||||
created_count += 1
|
||||
else:
|
||||
existing_count += 1
|
||||
|
||||
messages.success(
|
||||
request,
|
||||
f'Разрешения инициализированы. Создано: {created_count}, уже существовало: {existing_count}'
|
||||
)
|
||||
return redirect('mainapp:user_permissions_list')
|
||||
Reference in New Issue
Block a user