Kaynağa Gözat

create access rights

Староверов Данила Андреевич 1 yıl önce
ebeveyn
işleme
7b58df91ad

+ 7 - 0
SharixAdmin/apps.py

@@ -1,7 +1,14 @@
 from django.apps import AppConfig
 
 
+
 class SharixadminConfig(AppConfig):
     default_auto_field = 'django.db.models.BigAutoField'
     name = 'SharixAdmin'
     verbose_name = "SHARIX_PLATFORM"
+
+    def ready(self):
+        # Импортируем обработчик сигнала, чтобы зарегистрировать его
+        from django.db.models.signals import post_migrate
+        from .groups import create_groups
+        post_migrate.connect(create_groups, sender=self)

+ 28 - 0
SharixAdmin/groups.py

@@ -0,0 +1,28 @@
+from django.contrib.auth.models import Group
+from django.dispatch import receiver
+from django.db.models.signals import post_migrate
+from django.contrib.auth.decorators import user_passes_test
+
+#Создание групп
+@receiver(post_migrate)
+def create_groups(sender, **kwargs):
+    Group.objects.get_or_create(name='METASERVICE-ADMIN')
+    Group.objects.get_or_create(name='METASERVICE-SUPERVISOR')
+    Group.objects.get_or_create(name='METASERVICE-SUPPORT')
+    Group.objects.get_or_create(name='METASERVICE-TECHSUPPORT')
+    Group.objects.get_or_create(name='PARTNER-ADMIN')
+    Group.objects.get_or_create(name='PARTNER-SUPERVISOR')
+    Group.objects.get_or_create(name='PARTNER-TECHSUPPORT')
+    Group.objects.get_or_create(name='GUEST')
+    
+
+
+# Функция позволяющая определить принадлежность к группе, перенаправляет на авторизацию
+def group_required(*group_names):
+    def in_groups(u):
+        if u.is_authenticated:
+            if u.groups.filter(name__in=group_names).exists() or u.is_superuser:
+                return True
+        return False
+
+    return user_passes_test(in_groups)

+ 24 - 8
SharixAdmin/views/context.py

@@ -11,21 +11,37 @@ menu = [
     {'title':'Сотрудничество',          'link':'test-page', 'sel':'sotrud'},
     {'title':'Техподдержка',            'link':'test-page', 'sel':'gear'},
     {'title':'Мои заявки',              'link':'tickets', 'sel':'tikets'},
-    {'title':'Исполнители',             'link':'provider', 'sel':'people'},
-    {'title':'Тарифы услуг',            'link':'service_tariff', 'sel':'person'},
-    {'title':'Партнеры',                'link':'partners', 'sel':'people'},
-    {'title':'Ресурсы',                 'link':'resource', 'sel':'sotrud'},
-    {'title':'Услуги сервиса',          'link':'service_type', 'sel':'hdd-network'},
-    {'title':'Информация о сервисе',    'link':'service_information/add/', 'sel':'hdd-network'},
-    {'title':'Информация о партнере',   'link':'partner_information/add/', 'sel':'person'},
+    {'title':'Исполнители',             'link':'provider', 'sel':'people', 
+     'roles':['METASERVICE-ADMIN']},
+    {'title':'Тарифы услуг',            'link':'service_tariff', 'sel':'person',
+     'roles':['PARTNER-ADMIN']},
+    {'title':'Партнеры',                'link':'partners', 'sel':'people',
+     'roles':['METASERVICE-ADMIN']},
+    {'title':'Ресурсы',                 'link':'resource', 'sel':'sotrud',
+     'roles':['PARTNER-ADMIN']},
+    {'title':'Услуги сервиса',          'link':'service_type', 'sel':'hdd-network',
+     'roles':['METASERVICE-ADMIN']},
+    {'title':'Информация о сервисе',    'link':'service_information/add/', 'sel':'hdd-network',
+     'roles':['METASERVICE-ADMIN']},
+    {'title':'Информация о партнере',   'link':'partner_information/add/', 'sel':'person',
+     'roles':['PARTNER-ADMIN']},
     {'title':'Тарифы',                  'link':'service', 'sel':'tikets'},
 ]
 
 def get_context(request, page_context) -> dict:
+    # Получаем роли текущего пользователя
+    user_roles = set(group.name for group in request.user.groups.all())
+    is_superuser = request.user.is_superuser
+    menu_items = []
+    # Добавляем только те страницы к которым должен быть доступ
+    for item in menu:
+        if not item.get('roles') or is_superuser or set(item['roles']) & set(user_roles):  
+            menu_items.append(item)
+
     base_context = {
         "title":page_context['title'],
         'url_path':resolve(request.path_info).url_name,
-        'menu':menu
+        'menu':menu_items
     }
     context = dict(list(base_context.items()) + list(page_context.items()))
     return context

+ 16 - 2
SharixAdmin/views/partner_info.py

@@ -1,11 +1,13 @@
 from django.shortcuts import render
 from SharixAdmin.forms import PartnerInformationCreateForm, PartnerInformationUpdateForm
+from SharixAdmin.groups import group_required
 from metaservicesynced.models import Company
+from django.contrib.auth.mixins import UserPassesTestMixin
 from django.views.generic.edit import UpdateView, CreateView
 from SharixAdmin.views.context import get_context
 from django.urls import reverse
 
-class PartnerInformationCreate(CreateView):
+class PartnerInformationCreate(UserPassesTestMixin, CreateView):
     model = Company
     form_class = PartnerInformationCreateForm
     template_name = "SharixAdmin/partner_information_form.html"
@@ -21,7 +23,13 @@ class PartnerInformationCreate(CreateView):
     def get_success_url(self):
         return reverse('test-page')
     
-class PartnerInformationUpdateView(UpdateView):
+    def test_func(self) -> bool or None:
+        group_names = ('PARTNER-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
+    
+class PartnerInformationUpdateView(UserPassesTestMixin, UpdateView):
     model = Company
     form_class = PartnerInformationUpdateForm
     template_name = "SharixAdmin/partner_information_form.html"
@@ -37,6 +45,12 @@ class PartnerInformationUpdateView(UpdateView):
     def get_success_url(self):
         return reverse('test-page')
     
+    def test_func(self) -> bool or None:
+        group_names = ('PARTNER-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
+    
 def partner_information(request):
     context = get_context(request, {
         'title':'Информация о партнере',

+ 10 - 1
SharixAdmin/views/partners.py

@@ -1,11 +1,13 @@
 from django_tables2 import SingleTableView
+from django.contrib.auth.mixins import UserPassesTestMixin
+from SharixAdmin.groups import group_required
 from SharixAdmin.tables import PartnersTable
 from django.contrib.auth.decorators import login_required
 from metaservicesynced.models import Company
 from SharixAdmin.views.context import get_context
 from django.http import JsonResponse
 
-class PartnersListView(SingleTableView):
+class PartnersListView(UserPassesTestMixin, SingleTableView):
     table_class = PartnersTable
     queryset = Company.objects.all()
     template_name = 'SharixAdmin/partners.html'
@@ -18,7 +20,14 @@ class PartnersListView(SingleTableView):
         }))
         return context
     
+    def test_func(self) -> bool or None:
+        group_names = ('METASERVICE-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
+
 @login_required
+@group_required('METASERVICE-ADMIN')
 def change_partners_status(request):
     if request.method == 'POST':
         partners_id = request.POST.get('partners_id')

+ 9 - 1
SharixAdmin/views/resource.py

@@ -1,11 +1,13 @@
 from django_tables2 import SingleTableView
+from django.contrib.auth.mixins import UserPassesTestMixin
+from SharixAdmin.groups import group_required
 from SharixAdmin.tables import ResourceTable
 from django.contrib.auth.decorators import login_required
 from metaservicesynced.models import Resource
 from SharixAdmin.views.context import get_context
 from django.http import JsonResponse
 
-class ResourceListView(SingleTableView):
+class ResourceListView(UserPassesTestMixin, SingleTableView):
     table_class = ResourceTable
     queryset = Resource.objects.all()
     template_name = 'SharixAdmin/resource.html'
@@ -18,8 +20,14 @@ class ResourceListView(SingleTableView):
         }))
         return context
     
+    def test_func(self) -> bool or None:
+        group_names = ('PARTNER-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
 
 @login_required
+@group_required('PARTNER-ADMIN')
 def change_resource_status(request):
     if request.method == 'POST':
         resource_id = request.POST.get('resource_id')

+ 10 - 1
SharixAdmin/views/service.py

@@ -1,10 +1,12 @@
 from django_tables2 import SingleTableView
+from SharixAdmin.groups import group_required
 from SharixAdmin.tables import ServiceTable
 from metaservicesynced.models import Service
 from django.contrib.auth.decorators import login_required
 from SharixAdmin.views.context import get_context
+from django.contrib.auth.mixins import UserPassesTestMixin
 
-class ServiceListView(SingleTableView):
+class ServiceListView(UserPassesTestMixin, SingleTableView):
     table_class = ServiceTable
     queryset = Service.objects.all()
     template_name = 'SharixAdmin/service.html'
@@ -17,7 +19,14 @@ class ServiceListView(SingleTableView):
         }))
         return context
     
+    def test_func(self) -> bool or None:
+        group_names = ('PARTNER-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
+
 @login_required
+@group_required('PARTNER-ADMIN')
 def change_service_status(request):
     if request.method == 'POST':
         service_id = request.POST.get('service_id')

+ 16 - 3
SharixAdmin/views/service_info.py

@@ -1,10 +1,11 @@
 from SharixAdmin.forms import ServiceInformationCreateForm, ServiceInformationUpdateForm
+from django.contrib.auth.mixins import UserPassesTestMixin
 from django.views.generic.edit import CreateView, UpdateView
 from metaservicesynced.models import Service
 from SharixAdmin.views.context import get_context
 from django.urls import reverse
 
-class ServiceInformationCreate(CreateView):
+class ServiceInformationCreate(UserPassesTestMixin, CreateView):
     model = Service
     form_class = ServiceInformationCreateForm
     template_name = "SharixAdmin/service_information_form.html"
@@ -21,7 +22,13 @@ class ServiceInformationCreate(CreateView):
     def get_success_url(self):
         return reverse('test-page')
     
-class ServiceInformationUpdateView(UpdateView):
+    def test_func(self) -> bool or None:
+        group_names = ('METASERVICE-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
+    
+class ServiceInformationUpdateView(UserPassesTestMixin, UpdateView):
     model = Service
     form_class = ServiceInformationUpdateForm
     template_name = "SharixAdmin/service_information_form.html"
@@ -35,4 +42,10 @@ class ServiceInformationUpdateView(UpdateView):
         return context
     
     def get_success_url(self):
-        return reverse('test-page')
+        return reverse('test-page')
+    
+    def test_func(self) -> bool or None:
+        group_names = ('METASERVICE-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False

+ 22 - 4
SharixAdmin/views/service_tariff.py

@@ -1,4 +1,5 @@
 from django_tables2 import SingleTableView
+from django.contrib.auth.mixins import UserPassesTestMixin
 from django.views.generic.edit import UpdateView, CreateView
 from SharixAdmin.tables import ServiceTariffTable
 from SharixAdmin.forms import ServiceTariffCreateForm, ServiceTariffUpdateForm
@@ -6,7 +7,7 @@ from metaservicesynced.models import Service
 from django.urls import reverse
 from SharixAdmin.views.context import get_context
 
-class ServiceTariffCreate(CreateView):
+class ServiceTariffCreate(UserPassesTestMixin, CreateView):
     model = Service
     form_class = ServiceTariffCreateForm
     template_name = "SharixAdmin/service_tariff_form.html"
@@ -21,9 +22,14 @@ class ServiceTariffCreate(CreateView):
     
     def get_success_url(self):
         return reverse('service_tariff')
+    
+    def test_func(self) -> bool or None:
+        group_names = ('PARTNER-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
 
-
-class ServiceTariffListView(SingleTableView):
+class ServiceTariffListView(UserPassesTestMixin, SingleTableView):
     table_class = ServiceTariffTable
     queryset = Service.objects.all()
     template_name = 'SharixAdmin/service_tariff.html'
@@ -35,9 +41,15 @@ class ServiceTariffListView(SingleTableView):
             'object_list': context['object_list'],
         }))
         return context
+    
+    def test_func(self) -> bool or None:
+        group_names = ('PARTNER-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
 
 
-class ServiceTariffUpdateView(UpdateView):
+class ServiceTariffUpdateView(UserPassesTestMixin, UpdateView):
     model = Service
     form_class = ServiceTariffUpdateForm
     template_name = "SharixAdmin/service_tariff_form.html"
@@ -52,4 +64,10 @@ class ServiceTariffUpdateView(UpdateView):
     
     def get_success_url(self):
         return reverse('service_tariff')
+    
+    def test_func(self) -> bool or None:
+        group_names = ('PARTNER-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
 

+ 29 - 5
SharixAdmin/views/service_type.py

@@ -1,12 +1,13 @@
 from django_tables2 import SingleTableView
 from django.views.generic.edit import UpdateView, CreateView, DeleteView
 from SharixAdmin.tables import ServiceTypeTable
+from django.contrib.auth.mixins import UserPassesTestMixin
 from SharixAdmin.forms import ServiceTypeCreateForm, ServiceTypeUpdateForm
 from metaservicesynced.models import ServiceType
 from django.urls import reverse
 from SharixAdmin.views.context import get_context
 
-class ServiceTypeCreate(CreateView):
+class ServiceTypeCreate(UserPassesTestMixin, CreateView):
     model = ServiceType
     form_class = ServiceTypeCreateForm
     template_name = "SharixAdmin/service_type_form.html"
@@ -22,8 +23,14 @@ class ServiceTypeCreate(CreateView):
     def get_success_url(self):
         return reverse('service_type')
     
+    def test_func(self) -> bool or None:
+        group_names = ('METASERVICE-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
+    
 
-class ServiceTypeListView(SingleTableView):
+class ServiceTypeListView(UserPassesTestMixin, SingleTableView):
     table_class = ServiceTypeTable
     queryset = ServiceType.objects.all()
     template_name = 'SharixAdmin/service_type.html'
@@ -36,8 +43,13 @@ class ServiceTypeListView(SingleTableView):
         }))
         return context
 
+    def test_func(self) -> bool or None:
+        group_names = ('METASERVICE-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
 
-class ServiceTypeUpdateView(UpdateView):
+class ServiceTypeUpdateView(UserPassesTestMixin, UpdateView):
     model = ServiceType
     form_class = ServiceTypeUpdateForm
     template_name = "SharixAdmin/service_type_form.html"
@@ -50,8 +62,14 @@ class ServiceTypeUpdateView(UpdateView):
         }))
         return context
     
+    def test_func(self) -> bool or None:
+        group_names = ('METASERVICE-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False
+    
 
-class ServiceTypeDelete(DeleteView):
+class ServiceTypeDelete(UserPassesTestMixin, DeleteView):
     model = ServiceType
     template_name = "SharixAdmin/service_type_delete.html"
 
@@ -64,4 +82,10 @@ class ServiceTypeDelete(DeleteView):
         return context
     
     def get_success_url(self):
-        return reverse('service_type')
+        return reverse('service_type')
+    
+    def test_func(self) -> bool or None:
+        group_names = ('METASERVICE-ADMIN')
+        if bool(self.request.user.groups.filter(name__in=group_names)) or self.request.user.is_superuser:
+            return True
+        return False