8
0
Fork 0
mirror of https://gitlab2.federez.net/re2o/re2o synced 2024-12-23 15:33:45 +00:00

Utilisation de django-field-permission, simplification du code

This commit is contained in:
Gabriel Detraz 2017-11-01 23:48:40 +01:00 committed by root
parent 0ed60c64fd
commit e66ff32fcc
5 changed files with 45 additions and 95 deletions

View file

@ -56,8 +56,10 @@ from .models import (
OuverturePortList, OuverturePortList,
) )
from field_permissions.forms import FieldPermissionFormMixin
class EditMachineForm(ModelForm):
class EditMachineForm(FieldPermissionFormMixin, ModelForm):
"""Formulaire d'édition d'une machine""" """Formulaire d'édition d'une machine"""
class Meta: class Meta:
model = Machine model = Machine
@ -69,55 +71,16 @@ class EditMachineForm(ModelForm):
self.fields['name'].label = 'Nom de la machine' self.fields['name'].label = 'Nom de la machine'
class NewMachineForm(EditMachineForm): class EditInterfaceForm(FieldPermissionFormMixin, ModelForm):
"""Creation d'une machine, ne renseigne que le nom""" """Ajout d'une interface à une machine. En fonction des droits,
class Meta(EditMachineForm.Meta): affiche ou non l'ensemble des ip disponibles"""
fields = ['name']
class BaseEditMachineForm(EditMachineForm):
"""Edition basique, ne permet que de changer le nom et le statut.
Réservé aux users sans droits spécifiques"""
class Meta(EditMachineForm.Meta):
fields = ['name', 'active']
class EditInterfaceForm(ModelForm):
"""Edition d'une interface. Edition complète"""
class Meta: class Meta:
model = Interface model = Interface
fields = ['machine', 'type', 'ipv4', 'mac_address', 'details'] fields = ['machine', 'type', 'ipv4', 'mac_address', 'details']
def __init__(self, *args, **kwargs):
prefix = kwargs.pop('prefix', self.Meta.model.__name__)
super(EditInterfaceForm, self).__init__(*args, prefix=prefix, **kwargs)
self.fields['mac_address'].label = 'Adresse mac'
self.fields['type'].label = 'Type de machine'
self.fields['type'].empty_label = "Séléctionner un type de machine"
if "ipv4" in self.fields:
self.fields['ipv4'].empty_label = "Assignation automatique\
de l'ipv4"
self.fields['ipv4'].queryset = IpList.objects.filter(
interface__isnull=True
)
# Add it's own address
self.fields['ipv4'].queryset |= IpList.objects.filter(
interface=self.instance
)
if "machine" in self.fields:
self.fields['machine'].queryset = Machine.objects.all()\
.select_related('user')
class AddInterfaceForm(EditInterfaceForm):
"""Ajout d'une interface à une machine. En fonction des droits,
affiche ou non l'ensemble des ip disponibles"""
class Meta(EditInterfaceForm.Meta):
fields = ['type', 'ipv4', 'mac_address', 'details']
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
infra = kwargs.pop('infra') infra = kwargs.pop('infra')
super(AddInterfaceForm, self).__init__(*args, **kwargs) super(EditInterfaceForm, self).__init__(*args, **kwargs)
self.fields['ipv4'].empty_label = "Assignation automatique de l'ipv4" self.fields['ipv4'].empty_label = "Assignation automatique de l'ipv4"
if not infra: if not infra:
self.fields['type'].queryset = MachineType.objects.filter( self.fields['type'].queryset = MachineType.objects.filter(
@ -126,36 +89,6 @@ class AddInterfaceForm(EditInterfaceForm):
self.fields['ipv4'].queryset = IpList.objects.filter( self.fields['ipv4'].queryset = IpList.objects.filter(
interface__isnull=True interface__isnull=True
).filter(ip_type__in=IpType.objects.filter(need_infra=False)) ).filter(ip_type__in=IpType.objects.filter(need_infra=False))
else:
self.fields['ipv4'].queryset = IpList.objects.filter(
interface__isnull=True
)
class NewInterfaceForm(EditInterfaceForm):
"""Formulaire light, sans choix de l'ipv4; d'ajout d'une interface"""
class Meta(EditInterfaceForm.Meta):
fields = ['type', 'mac_address', 'details']
class BaseEditInterfaceForm(EditInterfaceForm):
"""Edition basique d'une interface. En fonction des droits,
ajoute ou non l'ensemble des ipv4 disponibles (infra)"""
class Meta(EditInterfaceForm.Meta):
fields = ['type', 'ipv4', 'mac_address', 'details']
def __init__(self, *args, **kwargs):
infra = kwargs.pop('infra')
super(BaseEditInterfaceForm, self).__init__(*args, **kwargs)
self.fields['ipv4'].empty_label = "Assignation automatique de l'ipv4"
if not infra:
self.fields['type'].queryset = MachineType.objects.filter(
ip_type__in=IpType.objects.filter(need_infra=False)
)
self.fields['ipv4'].queryset = IpList.objects.filter(
interface__isnull=True
).filter(ip_type__in=IpType.objects.filter(need_infra=False))
# Add it's own address
self.fields['ipv4'].queryset |= IpList.objects.filter( self.fields['ipv4'].queryset |= IpList.objects.filter(
interface=self.instance interface=self.instance
) )
@ -168,6 +101,7 @@ class BaseEditInterfaceForm(EditInterfaceForm):
) )
class AliasForm(ModelForm): class AliasForm(ModelForm):
"""Ajout d'un alias (et edition), CNAME, contenant nom et extension""" """Ajout d'un alias (et edition), CNAME, contenant nom et extension"""
class Meta: class Meta:

View file

@ -35,10 +35,12 @@ from django.utils.functional import cached_property
from django.utils import timezone from django.utils import timezone
from django.core.validators import MaxValueValidator from django.core.validators import MaxValueValidator
from field_permissions.models import FieldPermissionModelMixin
from macaddress.fields import MACAddressField from macaddress.fields import MACAddressField
class Machine(models.Model): class Machine(FieldPermissionModelMixin, models.Model):
""" Class définissant une machine, object parent user, objets fils """ Class définissant une machine, object parent user, objets fils
interfaces""" interfaces"""
PRETTY_NAME = "Machine" PRETTY_NAME = "Machine"
@ -52,6 +54,16 @@ class Machine(models.Model):
) )
active = models.BooleanField(default=True) active = models.BooleanField(default=True)
def can_change_user(self, user, **kwargs):
return user.is_infra
field_permissions = {
'user': can_change_user,
}
class Meta:
abstract = False
def __str__(self): def __str__(self):
return str(self.user) + ' - ' + str(self.id) + ' - ' + str(self.name) return str(self.user) + ' - ' + str(self.id) + ' - ' + str(self.name)
@ -400,7 +412,7 @@ class Text(models.Model):
return str(self.field1).ljust(15) + " IN TXT " + str(self.field2) return str(self.field1).ljust(15) + " IN TXT " + str(self.field2)
class Interface(models.Model): class Interface(FieldPermissionModelMixin, models.Model):
""" Une interface. Objet clef de l'application machine : """ Une interface. Objet clef de l'application machine :
- une address mac unique. Possibilité de la rendre unique avec le - une address mac unique. Possibilité de la rendre unique avec le
typemachine typemachine
@ -422,6 +434,16 @@ class Interface(models.Model):
details = models.CharField(max_length=255, blank=True) details = models.CharField(max_length=255, blank=True)
port_lists = models.ManyToManyField('OuverturePortList', blank=True) port_lists = models.ManyToManyField('OuverturePortList', blank=True)
def can_change_machine(self, user, **kwargs):
return user.is_infra
field_permissions = {
'machine': can_change_machine,
}
class Meta:
abstract = False
@cached_property @cached_property
def is_active(self): def is_active(self):
""" Renvoie si une interface doit avoir accès ou non """ """ Renvoie si une interface doit avoir accès ou non """

View file

@ -59,16 +59,12 @@ from reversion.models import Version
import re import re
from .forms import ( from .forms import (
NewMachineForm,
EditMachineForm, EditMachineForm,
EditInterfaceForm, EditInterfaceForm,
AddInterfaceForm,
MachineTypeForm, MachineTypeForm,
DelMachineTypeForm, DelMachineTypeForm,
ExtensionForm, ExtensionForm,
DelExtensionForm, DelExtensionForm,
BaseEditInterfaceForm,
BaseEditMachineForm
) )
from .forms import ( from .forms import (
EditIpTypeForm, EditIpTypeForm,
@ -225,8 +221,8 @@ def new_machine(request, userid):
if user.user_interfaces().count() >= max_lambdauser_interfaces: if user.user_interfaces().count() >= max_lambdauser_interfaces:
messages.error(request, "Vous avez atteint le maximum d'interfaces autorisées que vous pouvez créer vous même (%s) " % max_lambdauser_interfaces) messages.error(request, "Vous avez atteint le maximum d'interfaces autorisées que vous pouvez créer vous même (%s) " % max_lambdauser_interfaces)
return redirect("/users/profil/" + str(request.user.id)) return redirect("/users/profil/" + str(request.user.id))
machine = NewMachineForm(request.POST or None) machine = EditMachineForm(request.POST or None, user=request.user)
interface = AddInterfaceForm(request.POST or None, infra=request.user.has_perms(('infra',))) interface = EditInterfaceForm(request.POST or None, infra=request.user.has_perms(('infra',)), user=request.user)
domain = DomainForm(request.POST or None, user=user) domain = DomainForm(request.POST or None, user=user)
if machine.is_valid() and interface.is_valid(): if machine.is_valid() and interface.is_valid():
new_machine = machine.save(commit=False) new_machine = machine.save(commit=False)
@ -267,11 +263,8 @@ def edit_interface(request, interfaceid):
if not request.user.has_perms(('cableur',)) and interface.machine.user != request.user: if not request.user.has_perms(('cableur',)) and interface.machine.user != request.user:
messages.error(request, "Vous ne pouvez pas éditer une machine d'un autre user que vous sans droit") messages.error(request, "Vous ne pouvez pas éditer une machine d'un autre user que vous sans droit")
return redirect("/users/profil/" + str(request.user.id)) return redirect("/users/profil/" + str(request.user.id))
machine_form = BaseEditMachineForm(request.POST or None, instance=interface.machine) interface_form = EditInterfaceForm(request.POST or None, instance=interface, infra=request.user.has_perms(('infra',)), user=request.user)
interface_form = BaseEditInterfaceForm(request.POST or None, instance=interface, infra=False) machine_form = EditMachineForm(request.POST or None, instance=interface.machine, user=request.user)
else:
machine_form = EditMachineForm(request.POST or None, instance=interface.machine)
interface_form = EditInterfaceForm(request.POST or None, instance=interface)
domain_form = DomainForm(request.POST or None, instance=interface.domain) domain_form = DomainForm(request.POST or None, instance=interface.domain)
if machine_form.is_valid() and interface_form.is_valid() and domain_form.is_valid(): if machine_form.is_valid() and interface_form.is_valid() and domain_form.is_valid():
new_machine = machine_form.save(commit=False) new_machine = machine_form.save(commit=False)
@ -331,7 +324,7 @@ def new_interface(request, machineid):
if machine.user.user_interfaces().count() >= max_lambdauser_interfaces: if machine.user.user_interfaces().count() >= max_lambdauser_interfaces:
messages.error(request, "Vous avez atteint le maximum d'interfaces autorisées que vous pouvez créer vous même (%s) " % max_lambdauser_interfaces) messages.error(request, "Vous avez atteint le maximum d'interfaces autorisées que vous pouvez créer vous même (%s) " % max_lambdauser_interfaces)
return redirect("/users/profil/" + str(request.user.id)) return redirect("/users/profil/" + str(request.user.id))
interface_form = AddInterfaceForm(request.POST or None, infra=request.user.has_perms(('infra',))) interface_form = EditInterfaceForm(request.POST or None, infra=request.user.has_perms(('infra',)), user=request.user)
domain_form = DomainForm(request.POST or None) domain_form = DomainForm(request.POST or None)
if interface_form.is_valid(): if interface_form.is_valid():
new_interface = interface_form.save(commit=False) new_interface = interface_form.save(commit=False)

View file

@ -76,7 +76,8 @@ INSTALLED_APPS = (
'preferences', 'preferences',
'logs', 'logs',
'rest_framework', 'rest_framework',
'reversion' 'reversion',
'field_permissions'
) + OPTIONNAL_APPS ) + OPTIONNAL_APPS
MIDDLEWARE_CLASSES = ( MIDDLEWARE_CLASSES = (

View file

@ -68,10 +68,8 @@ from users.views import form
from re2o.utils import SortTable from re2o.utils import SortTable
from machines.forms import ( from machines.forms import (
DomainForm, DomainForm,
NewMachineForm,
EditMachineForm, EditMachineForm,
EditInterfaceForm, EditInterfaceForm,
AddInterfaceForm
) )
from machines.views import generate_ipv4_mbf_param from machines.views import generate_ipv4_mbf_param
from preferences.models import AssoOption, GeneralOption from preferences.models import AssoOption, GeneralOption
@ -431,10 +429,11 @@ def new_switch(request):
associée. Vue complexe. Appelle successivement les 4 models forms associée. Vue complexe. Appelle successivement les 4 models forms
adaptés : machine, interface, domain et switch""" adaptés : machine, interface, domain et switch"""
switch = NewSwitchForm(request.POST or None) switch = NewSwitchForm(request.POST or None)
machine = NewMachineForm(request.POST or None) machine = EditMachineForm(request.POST or None, user=request.user)
interface = AddInterfaceForm( interface = EditInterfaceForm(
request.POST or None, request.POST or None,
infra=request.user.has_perms(('infra',)) infra=request.user.has_perms(('infra',)),
user=request.user,
) )
domain = DomainForm( domain = DomainForm(
request.POST or None, request.POST or None,
@ -549,7 +548,8 @@ def edit_switch(request, switch_id):
) )
interface_form = EditInterfaceForm( interface_form = EditInterfaceForm(
request.POST or None, request.POST or None,
instance=switch.switch_interface instance=switch.switch_interface,
user=request.user,
) )
domain_form = DomainForm( domain_form = DomainForm(
request.POST or None, request.POST or None,