8
0
Fork 0
mirror of https://gitlab2.federez.net/re2o/re2o synced 2024-11-22 19:33:11 +00:00

Différencie iptype et machinetype

This commit is contained in:
chirac 2016-10-23 00:55:58 +02:00
parent 7b59cafba3
commit 99724e91e2
11 changed files with 213 additions and 19 deletions

View file

@ -1,14 +1,18 @@
from django.contrib import admin from django.contrib import admin
from reversion.admin import VersionAdmin from reversion.admin import VersionAdmin
from .models import Machine, MachineType, IpList, Interface, Extension from .models import IpType, Machine, MachineType, IpList, Interface, Extension
class MachineAdmin(VersionAdmin): class MachineAdmin(VersionAdmin):
list_display = ('user','name','active') list_display = ('user','name','active')
class MachineTypeAdmin(VersionAdmin): class IpTypeAdmin(VersionAdmin):
list_display = ('type','extension','need_infra') list_display = ('type','extension','need_infra')
class MachineTypeAdmin(VersionAdmin):
list_display = ('type','ip_type')
class ExtensionAdmin(VersionAdmin): class ExtensionAdmin(VersionAdmin):
list_display = ('name',) list_display = ('name',)
@ -20,6 +24,7 @@ class InterfaceAdmin(VersionAdmin):
admin.site.register(Machine, MachineAdmin) admin.site.register(Machine, MachineAdmin)
admin.site.register(MachineType, MachineTypeAdmin) admin.site.register(MachineType, MachineTypeAdmin)
admin.site.register(IpType, IpTypeAdmin)
admin.site.register(Extension, ExtensionAdmin) admin.site.register(Extension, ExtensionAdmin)
admin.site.register(IpList, IpListAdmin) admin.site.register(IpList, IpListAdmin)
admin.site.register(Interface, InterfaceAdmin) admin.site.register(Interface, InterfaceAdmin)

View file

@ -1,6 +1,6 @@
from django.forms import ModelForm, Form, ValidationError from django.forms import ModelForm, Form, ValidationError
from django import forms from django import forms
from .models import Machine, Interface, IpList, MachineType, Extension from .models import Machine, Interface, IpList, MachineType, Extension, IpType
class EditMachineForm(ModelForm): class EditMachineForm(ModelForm):
class Meta: class Meta:
@ -40,8 +40,8 @@ class AddInterfaceForm(EditInterfaceForm):
super(AddInterfaceForm, self).__init__(*args, **kwargs) super(AddInterfaceForm, 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(need_infra=False) self.fields['type'].queryset = MachineType.objects.filter(ip_type=IpType.objects.filter(need_infra=False))
self.fields['ipv4'].queryset = IpList.objects.filter(ip_type=MachineType.objects.filter(need_infra=False)) self.fields['ipv4'].queryset = IpList.objects.filter(ip_type=IpType.objects.filter(need_infra=False))
class NewInterfaceForm(EditInterfaceForm): class NewInterfaceForm(EditInterfaceForm):
class Meta(EditInterfaceForm.Meta): class Meta(EditInterfaceForm.Meta):
@ -56,25 +56,43 @@ class BaseEditInterfaceForm(EditInterfaceForm):
super(BaseEditInterfaceForm, self).__init__(*args, **kwargs) super(BaseEditInterfaceForm, 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(need_infra=False) self.fields['type'].queryset = MachineType.objects.filter(IpType.objects.filter(need_infra=False))
self.fields['ipv4'].queryset = IpList.objects.filter(ip_type=MachineType.objects.filter(need_infra=False)) self.fields['ipv4'].queryset = IpList.objects.filter(ip_type=IpType.objects.filter(need_infra=False))
class MachineTypeForm(ModelForm): class MachineTypeForm(ModelForm):
class Meta: class Meta:
model = MachineType model = MachineType
fields = ['type','extension','need_infra'] fields = ['type','ip_type']
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(MachineTypeForm, self).__init__(*args, **kwargs) super(MachineTypeForm, self).__init__(*args, **kwargs)
self.fields['type'].label = 'Type de machine à ajouter' self.fields['type'].label = 'Type de machine à ajouter'
self.fields['ip_type'].label = "Type d'ip relié"
class DelMachineTypeForm(ModelForm): class DelMachineTypeForm(ModelForm):
machinetypes = forms.ModelMultipleChoiceField(queryset=MachineType.objects.all(), label="Types de machines actuelles", widget=forms.CheckboxSelectMultiple) machinetypes = forms.ModelMultipleChoiceField(queryset=MachineType.objects.all(), label="Types de machines actuelles", widget=forms.CheckboxSelectMultiple)
class Meta: class Meta:
exclude = ['type','extension'] exclude = ['type','ip_type']
model = MachineType model = MachineType
class IpTypeForm(ModelForm):
class Meta:
model = IpType
fields = ['type','extension','need_infra']
def __init__(self, *args, **kwargs):
super(IpTypeForm, self).__init__(*args, **kwargs)
self.fields['type'].label = 'Type ip à ajouter'
class DelIpTypeForm(ModelForm):
iptypes = forms.ModelMultipleChoiceField(queryset=IpType.objects.all(), label="Types d'ip actuelles", widget=forms.CheckboxSelectMultiple)
class Meta:
exclude = ['type','extension','need_infra']
model = IpType
class ExtensionForm(ModelForm): class ExtensionForm(ModelForm):
class Meta: class Meta:
model = Extension model = Extension

View file

@ -0,0 +1,42 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('machines', '0024_machinetype_need_infra'),
]
operations = [
migrations.CreateModel(
name='IpType',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
('type', models.CharField(max_length=255)),
('need_infra', models.BooleanField(default=False)),
('extension', models.ForeignKey(to='machines.Extension', on_delete=django.db.models.deletion.PROTECT)),
],
),
migrations.RemoveField(
model_name='machinetype',
name='extension',
),
migrations.RemoveField(
model_name='machinetype',
name='need_infra',
),
migrations.AlterField(
model_name='iplist',
name='ip_type',
field=models.ForeignKey(to='machines.IpType', on_delete=django.db.models.deletion.PROTECT),
),
migrations.AddField(
model_name='machinetype',
name='ip_type',
field=models.ForeignKey(to='machines.IpType', null=True, blank=True, on_delete=django.db.models.deletion.PROTECT),
),
]

View file

@ -16,6 +16,13 @@ class Machine(models.Model):
return str(self.user) + ' - ' + str(self.id) + ' - ' + str(self.name) return str(self.user) + ' - ' + str(self.id) + ' - ' + str(self.name)
class MachineType(models.Model): class MachineType(models.Model):
type = models.CharField(max_length=255)
ip_type = models.ForeignKey('IpType', on_delete=models.PROTECT, blank=True, null=True)
def __str__(self):
return self.type
class IpType(models.Model):
type = models.CharField(max_length=255) type = models.CharField(max_length=255)
extension = models.ForeignKey('Extension', on_delete=models.PROTECT) extension = models.ForeignKey('Extension', on_delete=models.PROTECT)
need_infra = models.BooleanField(default=False) need_infra = models.BooleanField(default=False)
@ -49,7 +56,7 @@ class Interface(models.Model):
class IpList(models.Model): class IpList(models.Model):
ipv4 = models.GenericIPAddressField(protocol='IPv4', unique=True) ipv4 = models.GenericIPAddressField(protocol='IPv4', unique=True)
ip_type = models.ForeignKey('MachineType', on_delete=models.PROTECT) ip_type = models.ForeignKey('IpType', on_delete=models.PROTECT)
def __str__(self): def __str__(self):
return self.ipv4 return self.ipv4

View file

@ -0,0 +1,21 @@
<table class="table table-striped">
<thead>
<tr>
<th>Type d'ip</th>
<th>Extension</th>
<th>Nécessite l'autorisation infra</th>
<th></th>
<th></th>
</tr>
</thead>
{% for type in iptype_list %}
<tr>
<td>{{ type.type }}</td>
<td>{{ type.extension }}</td>
<td>{{ type.need_infra }}</td>
<td>{% if is_infra %}<a class="btn btn-primary btn-sm" role="button" href="{% url 'machines:edit-iptype' type.id %}"><i class="glyphicon glyphicon-pushpin"></i> Editer</a>{% endif %}</td>
<td><a class="btn btn-info btn-sm" role="button" href="{% url 'machines:history' 'iptype' type.id %}"><i class="glyphicon glyphicon-repeat"></i> Historique</a></td>
</tr>
{% endfor %}
</table>

View file

@ -2,8 +2,7 @@
<thead> <thead>
<tr> <tr>
<th>Type de machine</th> <th>Type de machine</th>
<th>Extension</th> <th>Type d'ip correspondant</th>
<th>Nécessite l'autorisation infra</th>
<th></th> <th></th>
<th></th> <th></th>
</tr> </tr>
@ -11,8 +10,7 @@
{% for type in machinetype_list %} {% for type in machinetype_list %}
<tr> <tr>
<td>{{ type.type }}</td> <td>{{ type.type }}</td>
<td>{{ type.extension }}</td> <td>{{ type.ip_type }}</td>
<td>{{ type.need_infra }}</td>
<td>{% if is_infra %}<a class="btn btn-primary btn-sm" role="button" href="{% url 'machines:edit-machinetype' type.id %}"><i class="glyphicon glyphicon-pushpin"></i> Editer</a>{% endif %}</td> <td>{% if is_infra %}<a class="btn btn-primary btn-sm" role="button" href="{% url 'machines:edit-machinetype' type.id %}"><i class="glyphicon glyphicon-pushpin"></i> Editer</a>{% endif %}</td>
<td><a class="btn btn-info btn-sm" role="button" href="{% url 'machines:history' 'machinetype' type.id %}"><i class="glyphicon glyphicon-repeat"></i> Historique</a></td> <td><a class="btn btn-info btn-sm" role="button" href="{% url 'machines:history' 'machinetype' type.id %}"><i class="glyphicon glyphicon-repeat"></i> Historique</a></td>
</tr> </tr>

View file

@ -0,0 +1,17 @@
{% extends "machines/sidebar.html" %}
{% load bootstrap3 %}
{% block title %}Ip{% endblock %}
{% block content %}
<h2>Liste des types d'ip</h2>
{% if is_infra %}
<a class="btn btn-primary btn-sm" role="button" href="{% url 'machines:add-iptype' %}"><i class="glyphicon glyphicon-plus"></i> Ajouter un type d'ip</a>
<a class="btn btn-danger btn-sm" role="button" href="{% url 'machines:del-iptype' %}"><i class="glyphicon glyphicon-trash"></i> Supprimer un ou plusieurs types d'ip</a>
{% endif %}
{% include "machines/aff_iptype.html" with iptype_list=iptype_list %}
<br />
<br />
<br />
{% endblock %}

View file

@ -4,5 +4,6 @@
{% if is_cableur %} {% if is_cableur %}
<p><a href="{% url "machines:index-machinetype" %}">Liste des types de machine</a></p> <p><a href="{% url "machines:index-machinetype" %}">Liste des types de machine</a></p>
<p><a href="{% url "machines:index-extension" %}">Liste des types des extensions</a></p> <p><a href="{% url "machines:index-extension" %}">Liste des types des extensions</a></p>
<p><a href="{% url "machines:index-iptype" %}">Liste des types d'ip</a></p>
{% endif %} {% endif %}
{% endblock %} {% endblock %}

View file

@ -12,6 +12,10 @@ urlpatterns = [
url(r'^edit_machinetype/(?P<machinetypeid>[0-9]+)$', views.edit_machinetype, name='edit-machinetype'), url(r'^edit_machinetype/(?P<machinetypeid>[0-9]+)$', views.edit_machinetype, name='edit-machinetype'),
url(r'^del_machinetype/$', views.del_machinetype, name='del-machinetype'), url(r'^del_machinetype/$', views.del_machinetype, name='del-machinetype'),
url(r'^index_machinetype/$', views.index_machinetype, name='index-machinetype'), url(r'^index_machinetype/$', views.index_machinetype, name='index-machinetype'),
url(r'^add_iptype/$', views.add_iptype, name='add-iptype'),
url(r'^edit_iptype/(?P<iptypeid>[0-9]+)$', views.edit_iptype, name='edit-iptype'),
url(r'^del_iptype/$', views.del_iptype, name='del-iptype'),
url(r'^index_iptype/$', views.index_iptype, name='index-iptype'),
url(r'^add_extension/$', views.add_extension, name='add-extension'), url(r'^add_extension/$', views.add_extension, name='add-extension'),
url(r'^edit_extension/(?P<extensionid>[0-9]+)$', views.edit_extension, name='edit-extension'), url(r'^edit_extension/(?P<extensionid>[0-9]+)$', views.edit_extension, name='edit-extension'),
url(r'^del_extension/$', views.del_extension, name='del-extension'), url(r'^del_extension/$', views.del_extension, name='del-extension'),
@ -20,6 +24,7 @@ urlpatterns = [
url(r'^history/(?P<object>interface)/(?P<id>[0-9]+)$', views.history, name='history'), url(r'^history/(?P<object>interface)/(?P<id>[0-9]+)$', views.history, name='history'),
url(r'^history/(?P<object>machinetype)/(?P<id>[0-9]+)$', views.history, name='history'), url(r'^history/(?P<object>machinetype)/(?P<id>[0-9]+)$', views.history, name='history'),
url(r'^history/(?P<object>extension)/(?P<id>[0-9]+)$', views.history, name='history'), url(r'^history/(?P<object>extension)/(?P<id>[0-9]+)$', views.history, name='history'),
url(r'^history/(?P<object>iptype)/(?P<id>[0-9]+)$', views.history, name='history'),
url(r'^$', views.index, name='index'), url(r'^$', views.index, name='index'),
url(r'^rest/mac-ip/$', views.mac_ip, name='mac-ip'), url(r'^rest/mac-ip/$', views.mac_ip, name='mac-ip'),
url(r'^rest/mac-ip-dns/$', views.mac_ip_dns, name='mac-ip-dns'), url(r'^rest/mac-ip-dns/$', views.mac_ip_dns, name='mac-ip-dns'),

View file

@ -20,7 +20,8 @@ from reversion import revisions as reversion
import re import re
from .forms import NewMachineForm, EditMachineForm, EditInterfaceForm, AddInterfaceForm, MachineTypeForm, DelMachineTypeForm, ExtensionForm, DelExtensionForm, BaseEditInterfaceForm, BaseEditMachineForm from .forms import NewMachineForm, EditMachineForm, EditInterfaceForm, AddInterfaceForm, MachineTypeForm, DelMachineTypeForm, ExtensionForm, DelExtensionForm, BaseEditInterfaceForm, BaseEditMachineForm
from .models import Machine, Interface, IpList, MachineType, Extension from .forms import IpTypeForm, DelIpTypeForm
from .models import IpType, Machine, Interface, IpList, MachineType, Extension
from users.models import User from users.models import User
from re2o.settings import PAGINATION_NUMBER, PAGINATION_LARGE_NUMBER from re2o.settings import PAGINATION_NUMBER, PAGINATION_LARGE_NUMBER
@ -28,7 +29,7 @@ def full_domain_validator(request, interface):
""" Validation du nom de domaine, extensions dans type de machine, prefixe pas plus long que 63 caractères """ """ Validation du nom de domaine, extensions dans type de machine, prefixe pas plus long que 63 caractères """
HOSTNAME_LABEL_PATTERN = re.compile("(?!-)[A-Z\d-]+(?<!-)$", re.IGNORECASE) HOSTNAME_LABEL_PATTERN = re.compile("(?!-)[A-Z\d-]+(?<!-)$", re.IGNORECASE)
dns = interface.dns.lower() dns = interface.dns.lower()
allowed_extension = interface.type.extension.name allowed_extension = interface.ipv4.type.extension.name
if not dns.endswith(allowed_extension): if not dns.endswith(allowed_extension):
messages.error(request, messages.error(request,
"Le nom de domaine %s doit comporter une extension valide en %s" % (dns, allowed_extension) ) "Le nom de domaine %s doit comporter une extension valide en %s" % (dns, allowed_extension) )
@ -67,7 +68,7 @@ def free_ip(type):
def assign_ipv4(interface): def assign_ipv4(interface):
""" Assigne une ip à l'interface """ """ Assigne une ip à l'interface """
free_ips = free_ip(interface.type) free_ips = free_ip(interface.type.ip_type)
if free_ips: if free_ips:
interface.ipv4 = free_ips[0] interface.ipv4 = free_ips[0]
return interface return interface
@ -105,7 +106,7 @@ def new_machine(request, userid):
reversion.set_user(request.user) reversion.set_user(request.user)
reversion.set_comment("Création") reversion.set_comment("Création")
new_interface.machine = new_machine new_interface.machine = new_machine
if free_ip(new_interface.type) and not new_interface.ipv4: if free_ip(new_interface.type.ip_type) and not new_interface.ipv4:
new_interface = assign_ipv4(new_interface) new_interface = assign_ipv4(new_interface)
elif not new_interface.ipv4: elif not new_interface.ipv4:
messages.error(request, u"Il n'y a plus d'ip disponibles") messages.error(request, u"Il n'y a plus d'ip disponibles")
@ -184,7 +185,7 @@ def new_interface(request, machineid):
new_interface = interface_form.save(commit=False) new_interface = interface_form.save(commit=False)
new_interface.machine = machine new_interface.machine = machine
if full_domain_validator(request, new_interface): if full_domain_validator(request, new_interface):
if free_ip(new_interface.type) and not new_interface.ipv4: if free_ip(new_interface.type.ip_type) and not new_interface.ipv4:
new_interface = assign_ipv4(new_interface) new_interface = assign_ipv4(new_interface)
elif not new_interface.ipv4: elif not new_interface.ipv4:
messages.error(request, u"Il n'y a plus d'ip disponibles") messages.error(request, u"Il n'y a plus d'ip disponibles")
@ -215,6 +216,54 @@ def del_interface(request, interfaceid):
return redirect("/users/profil/" + str(request.user.id)) return redirect("/users/profil/" + str(request.user.id))
return form({'objet': interface, 'objet_name': 'interface'}, 'machines/delete.html', request) return form({'objet': interface, 'objet_name': 'interface'}, 'machines/delete.html', request)
@login_required
@permission_required('infra')
def add_iptype(request):
iptype = IpTypeForm(request.POST or None)
if iptype.is_valid():
with transaction.atomic(), reversion.create_revision():
iptype.save()
reversion.set_user(request.user)
reversion.set_comment("Création")
messages.success(request, "Ce type d'ip a été ajouté")
return redirect("/machines/index_iptype")
return form({'machineform': iptype, 'interfaceform': None}, 'machines/machine.html', request)
@login_required
@permission_required('infra')
def edit_iptype(request, iptypeid):
try:
iptype_instance = IpType.objects.get(pk=iptypeid)
except IpType.DoesNotExist:
messages.error(request, u"Entrée inexistante" )
return redirect("/machines/index_iptype/")
iptype = IpTypeForm(request.POST or None, instance=iptype_instance)
if iptype.is_valid():
with transaction.atomic(), reversion.create_revision():
iptype.save()
reversion.set_user(request.user)
reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in iptype.changed_data))
messages.success(request, "Type d'ip modifié")
return redirect("/machines/index_iptype/")
return form({'machineform': iptype}, 'machines/machine.html', request)
@login_required
@permission_required('infra')
def del_iptype(request):
iptype = DelIpTypeForm(request.POST or None)
if iptype.is_valid():
iptype_dels = iptype.cleaned_data['iptypes']
for iptype_del in iptype_dels:
try:
with transaction.atomic(), reversion.create_revision():
iptype_del.delete()
reversion.set_user(request.user)
messages.success(request, "Le type d'ip a été supprimé")
except ProtectedError:
messages.error(request, "Le type d'ip %s est affectée à au moins une machine, vous ne pouvez pas le supprimer" % iptype_del)
return redirect("/machines/index_iptype")
return form({'machineform': iptype, 'interfaceform': None}, 'machines/machine.html', request)
@login_required @login_required
@permission_required('infra') @permission_required('infra')
def add_machinetype(request): def add_machinetype(request):
@ -327,6 +376,12 @@ def index(request):
machines_list = paginator.page(paginator.num_pages) machines_list = paginator.page(paginator.num_pages)
return render(request, 'machines/index.html', {'machines_list': machines_list}) return render(request, 'machines/index.html', {'machines_list': machines_list})
@login_required
@permission_required('cableur')
def index_iptype(request):
iptype_list = IpType.objects.order_by('type')
return render(request, 'machines/index_iptype.html', {'iptype_list':iptype_list})
@login_required @login_required
@permission_required('cableur') @permission_required('cableur')
def index_machinetype(request): def index_machinetype(request):
@ -365,6 +420,12 @@ def history(request, object, id):
except MachineType.DoesNotExist: except MachineType.DoesNotExist:
messages.error(request, "Type de machine inexistant") messages.error(request, "Type de machine inexistant")
return redirect("/machines/") return redirect("/machines/")
elif object == 'iptype' and request.user.has_perms(('cableur',)):
try:
object_instance = IpType.objects.get(pk=id)
except IpType.DoesNotExist:
messages.error(request, "Type d'ip inexistant")
return redirect("/machines/")
elif object == 'extension' and request.user.has_perms(('cableur',)): elif object == 'extension' and request.user.has_perms(('cableur',)):
try: try:
object_instance = Extension.objects.get(pk=id) object_instance = Extension.objects.get(pk=id)

View file

@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0035_auto_20161018_0046'),
]
operations = [
migrations.AlterField(
model_name='user',
name='state',
field=models.IntegerField(default=0, choices=[(0, 'STATE_ACTIVE'), (1, 'STATE_DISABLED'), (2, 'STATE_ARCHIVE')]),
),
]