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

Merge branch 'acl_mixins' into 'master'

Acl mixins

See merge request federez/re2o!108
This commit is contained in:
klafyvel 2018-03-29 15:26:13 +02:00
commit a2bde7fc1a
27 changed files with 320 additions and 1925 deletions

0
api/__init__.py Normal file
View file

View file

@ -57,9 +57,9 @@ from django.utils import timezone
from machines.models import regen from machines.models import regen
from re2o.field_permissions import FieldPermissionModelMixin from re2o.field_permissions import FieldPermissionModelMixin
from re2o.mixins import AclMixin
class Facture(AclMixin, FieldPermissionModelMixin, models.Model):
class Facture(FieldPermissionModelMixin, models.Model):
""" Définition du modèle des factures. Une facture regroupe une ou """ Définition du modèle des factures. Une facture regroupe une ou
plusieurs ventes, rattachée à un user, et reliée à un moyen de paiement plusieurs ventes, rattachée à un user, et reliée à un moyen de paiement
et si il y a lieu un numero pour les chèques. Possède les valeurs et si il y a lieu un numero pour les chèques. Possède les valeurs
@ -114,13 +114,6 @@ class Facture(FieldPermissionModelMixin, models.Model):
).values_list('name', flat=True)) ).values_list('name', flat=True))
return name return name
def get_instance(factureid, *args, **kwargs):
return Facture.objects.get(pk=factureid)
def can_create(user_request, *args, **kwargs):
return user_request.has_perm('cotisations.add_facture'), u"Vous n'avez pas le\
droit de créer des factures"
def can_edit(self, user_request, *args, **kwargs): def can_edit(self, user_request, *args, **kwargs):
if not user_request.has_perm('cotisations.change_facture'): if not user_request.has_perm('cotisations.change_facture'):
return False, u"Vous n'avez pas le droit d'éditer les factures" return False, u"Vous n'avez pas le droit d'éditer les factures"
@ -144,11 +137,6 @@ class Facture(FieldPermissionModelMixin, models.Model):
else: else:
return True, None return True, None
def can_view_all(user_request, *args, **kwargs):
if not user_request.has_perm('cotisations.view_facture'):
return False, u"Vous n'avez pas le droit de voir les factures"
return True, None
def can_view(self, user_request, *args, **kwargs): def can_view(self, user_request, *args, **kwargs):
if not user_request.has_perm('cotisations.view_facture') and\ if not user_request.has_perm('cotisations.view_facture') and\
self.user != user_request: self.user != user_request:
@ -192,7 +180,7 @@ def facture_post_delete(sender, **kwargs):
user.ldap_sync(base=False, access_refresh=True, mac_refresh=False) user.ldap_sync(base=False, access_refresh=True, mac_refresh=False)
class Vente(models.Model): class Vente(AclMixin, models.Model):
"""Objet vente, contient une quantité, une facture parente, un nom, """Objet vente, contient une quantité, une facture parente, un nom,
un prix. Peut-être relié à un objet cotisation, via le boolean un prix. Peut-être relié à un objet cotisation, via le boolean
iscotisation""" iscotisation"""
@ -277,14 +265,6 @@ class Vente(models.Model):
self.update_cotisation() self.update_cotisation()
super(Vente, self).save(*args, **kwargs) super(Vente, self).save(*args, **kwargs)
def get_instance(venteid, *args, **kwargs):
return Vente.objects.get(pk=venteid)
def can_create(user_request, *args, **kwargs):
return user_request.has_perm('cotisations.add_vente'), u"Vous n'avez pas le\
droit de créer des ventes"
return True, None
def can_edit(self, user_request, *args, **kwargs): def can_edit(self, user_request, *args, **kwargs):
if not user_request.has_perm('cotisations.change_vente'): if not user_request.has_perm('cotisations.change_vente'):
return False, u"Vous n'avez pas le droit d'éditer les ventes" return False, u"Vous n'avez pas le droit d'éditer les ventes"
@ -308,11 +288,6 @@ class Vente(models.Model):
else: else:
return True, None return True, None
def can_view_all(user_request, *args, **kwargs):
if not user_request.has_perm('cotisations.view_vente'):
return False, u"Vous n'avez pas le droit de voir les ventes"
return True, None
def can_view(self, user_request, *args, **kwargs): def can_view(self, user_request, *args, **kwargs):
if not user_request.has_perm('cotisations.view_vente') and\ if not user_request.has_perm('cotisations.view_vente') and\
self.facture.user != user_request: self.facture.user != user_request:
@ -350,7 +325,7 @@ def vente_post_delete(sender, **kwargs):
user.ldap_sync(base=False, access_refresh=True, mac_refresh=False) user.ldap_sync(base=False, access_refresh=True, mac_refresh=False)
class Article(models.Model): class Article(AclMixin, models.Model):
"""Liste des articles en vente : prix, nom, et attribut iscotisation """Liste des articles en vente : prix, nom, et attribut iscotisation
et duree si c'est une cotisation""" et duree si c'est une cotisation"""
PRETTY_NAME = "Articles en vente" PRETTY_NAME = "Articles en vente"
@ -402,34 +377,11 @@ class Article(models.Model):
"La durée est obligatoire si il s'agit d'une cotisation" "La durée est obligatoire si il s'agit d'une cotisation"
) )
def get_instance(articleid, *args, **kwargs):
return Article.objects.get(pk=articleid)
def can_create(user_request, *args, **kwargs):
return user_request.has_perm('cotisations.add_article'), u"Vous n'avez pas le\
droit d'ajouter des articles"
def can_edit(self, user_request, *args, **kwargs):
return user_request.has_perm('cotisations.change_article'), u"Vous n'avez pas le\
droit d'éditer des articles"
def can_delete(self, user_request, *args, **kwargs):
return user_request.has_perm('cotisations.delete_article'), u"Vous n'avez pas le\
droit de supprimer des articles"
def can_view_all(user_request, *args, **kwargs):
return user_request.has_perm('cotisations.view_article'), u"Vous n'avez pas le\
droit de voir des articles"
def can_view(self, user_request, *args, **kwargs):
return user_request.has_perm('cotisations.view_article'), u"Vous n'avez pas le\
droit de voir des articles"
def __str__(self): def __str__(self):
return self.name return self.name
class Banque(models.Model): class Banque(AclMixin, models.Model):
"""Liste des banques""" """Liste des banques"""
PRETTY_NAME = "Banques enregistrées" PRETTY_NAME = "Banques enregistrées"
@ -440,34 +392,11 @@ class Banque(models.Model):
("view_banque", "Peut voir un objet banque"), ("view_banque", "Peut voir un objet banque"),
) )
def get_instance(banqueid, *args, **kwargs):
return Banque.objects.get(pk=banqueid)
def can_create(user_request, *args, **kwargs):
return user_request.has_perm('cotisations.add_banque'), u"Vous n'avez pas le\
droit d'ajouter des banques"
def can_edit(self, user_request, *args, **kwargs):
return user_request.has_perm('cotisations.change_banque'), u"Vous n'avez pas le\
droit d'éditer des banques"
def can_delete(self, user_request, *args, **kwargs):
return user_request.has_perm('cotisations.delete_banque'), u"Vous n'avez pas le\
droit de supprimer des banques"
def can_view_all(user_request, *args, **kwargs):
return user_request.has_perm('cotisations.view_banque'), u"Vous n'avez pas le\
droit de voir des banques"
def can_view(self, user_request, *args, **kwargs):
return user_request.has_perm('cotisations.view_banque'), u"Vous n'avez pas le\
droit de voir des banques"
def __str__(self): def __str__(self):
return self.name return self.name
class Paiement(models.Model): class Paiement(AclMixin, models.Model):
"""Moyens de paiement""" """Moyens de paiement"""
PRETTY_NAME = "Moyens de paiement" PRETTY_NAME = "Moyens de paiement"
PAYMENT_TYPES = ( PAYMENT_TYPES = (
@ -483,29 +412,6 @@ class Paiement(models.Model):
("view_paiement", "Peut voir un objet paiement"), ("view_paiement", "Peut voir un objet paiement"),
) )
def get_instance(paiementid, *args, **kwargs):
return Paiement.objects.get(pk=paiementid)
def can_create(user_request, *args, **kwargs):
return user_request.has_perm('cotisations.add_paiement'), u"Vous n'avez pas le\
droit d'ajouter des paiements"
def can_edit(self, user_request, *args, **kwargs):
return user_request.has_perm('cotisations.change_paiement'), u"Vous n'avez pas le\
droit d'éditer des paiements"
def can_delete(self, user_request, *args, **kwargs):
return user_request.has_perm('cotisations.delete_paiement'), u"Vous n'avez pas le\
droit de supprimer des paiements"
def can_view_all(user_request, *args, **kwargs):
return user_request.has_perm('cotisations.view_paiement'), u"Vous n'avez pas le\
droit de voir des paiements"
def can_view(self, user_request, *args, **kwargs):
return user_request.has_perm('cotisations.view_paiement'), u"Vous n'avez pas le\
droit de voir des paiements"
def __str__(self): def __str__(self):
return self.moyen return self.moyen
@ -520,7 +426,7 @@ class Paiement(models.Model):
super(Paiement, self).save(*args, **kwargs) super(Paiement, self).save(*args, **kwargs)
class Cotisation(models.Model): class Cotisation(AclMixin, models.Model):
"""Objet cotisation, debut et fin, relié en onetoone à une vente""" """Objet cotisation, debut et fin, relié en onetoone à une vente"""
PRETTY_NAME = "Cotisations" PRETTY_NAME = "Cotisations"
@ -545,14 +451,6 @@ class Cotisation(models.Model):
("change_all_cotisation", "Superdroit, peut modifier toutes les cotisations"), ("change_all_cotisation", "Superdroit, peut modifier toutes les cotisations"),
) )
def get_instance(cotisationid, *args, **kwargs):
return Cotisations.objects.get(pk=cotisationid)
def can_create(user_request, *args, **kwargs):
return user_request.has_perm('cotisations.add_cotisation'), u"Vous n'avez pas le\
droit de créer des cotisations"
return True, None
def can_edit(self, user_request, *args, **kwargs): def can_edit(self, user_request, *args, **kwargs):
if not user_request.has_perm('cotisations.change_cotisation'): if not user_request.has_perm('cotisations.change_cotisation'):
return False, u"Vous n'avez pas le droit d'éditer les cotisations" return False, u"Vous n'avez pas le droit d'éditer les cotisations"
@ -572,11 +470,6 @@ class Cotisation(models.Model):
else: else:
return True, None return True, None
def can_view_all(user_request, *args, **kwargs):
if not user_request.has_perm('cotisations.view_cotisation'):
return False, u"Vous n'avez pas le droit de voir les cotisations"
return True, None
def can_view(self, user_request, *args, **kwargs): def can_view(self, user_request, *args, **kwargs):
if not user_request.has_perm('cotisations.view_cotisation') and\ if not user_request.has_perm('cotisations.view_cotisation') and\
self.vente.facture.user != user_request: self.vente.facture.user != user_request:

View file

@ -90,7 +90,8 @@ from topologie.models import (
Room, Room,
Stack, Stack,
ModelSwitch, ModelSwitch,
ConstructorSwitch ConstructorSwitch,
AccessPoint
) )
from preferences.models import GeneralOption from preferences.models import GeneralOption
from re2o.views import form from re2o.views import form
@ -360,6 +361,7 @@ def stats_models(request):
}, },
'Topologie': { 'Topologie': {
'switch': [Switch.PRETTY_NAME, Switch.objects.count()], 'switch': [Switch.PRETTY_NAME, Switch.objects.count()],
'bornes': [AccessPoint.PRETTY_NAME, AccessPoint.objects.count()],
'port': [Port.PRETTY_NAME, Port.objects.count()], 'port': [Port.PRETTY_NAME, Port.objects.count()],
'chambre': [Room.PRETTY_NAME, Room.objects.count()], 'chambre': [Room.PRETTY_NAME, Room.objects.count()],
'stack': [Stack.PRETTY_NAME, Stack.objects.count()], 'stack': [Stack.PRETTY_NAME, Stack.objects.count()],

View file

@ -38,6 +38,7 @@ from .models import (
Nas, Nas,
Service, Service,
OuverturePort, OuverturePort,
Ipv6List,
OuverturePortList OuverturePortList
) )
@ -46,6 +47,10 @@ class MachineAdmin(VersionAdmin):
pass pass
class Ipv6ListAdmin(VersionAdmin):
pass
class IpTypeAdmin(VersionAdmin): class IpTypeAdmin(VersionAdmin):
pass pass
@ -124,6 +129,7 @@ admin.site.register(Interface, InterfaceAdmin)
admin.site.register(Domain, DomainAdmin) admin.site.register(Domain, DomainAdmin)
admin.site.register(Service, ServiceAdmin) admin.site.register(Service, ServiceAdmin)
admin.site.register(Vlan, VlanAdmin) admin.site.register(Vlan, VlanAdmin)
admin.site.register(Ipv6List, Ipv6ListAdmin)
admin.site.register(Nas, NasAdmin) admin.site.register(Nas, NasAdmin)
admin.site.register(OuverturePort, OuverturePortAdmin) admin.site.register(OuverturePort, OuverturePortAdmin)
admin.site.register(OuverturePortList, OuverturePortListAdmin) admin.site.register(OuverturePortList, OuverturePortListAdmin)

File diff suppressed because it is too large Load diff

View file

@ -24,6 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
{% load acl %} {% load acl %}
<div class="table-responsive">
<table class="table table-striped"> <table class="table table-striped">
<thead> <thead>
<tr> <tr>
@ -47,7 +48,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
<td>{{ extension.origin_v6 }}</td> <td>{{ extension.origin_v6 }}</td>
{% endif %} {% endif %}
<td class="text-right"> <td class="text-right">
{% can_create Extension %} {% can_edit extension %}
{% include 'buttons/edit.html' with href='machines:edit-extension' id=extension.id %} {% include 'buttons/edit.html' with href='machines:edit-extension' id=extension.id %}
{% acl_end %} {% acl_end %}
{% include 'buttons/history.html' with href='machines:history' name='extension' id=extension.id %} {% include 'buttons/history.html' with href='machines:history' name='extension' id=extension.id %}
@ -55,4 +56,4 @@ with this program; if not, write to the Free Software Foundation, Inc.,
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
</div>

View file

@ -23,15 +23,14 @@ with this program; if not, write to the Free Software Foundation, Inc.,
{% endcomment %} {% endcomment %}
{% load acl %} {% load acl %}
<div class="table-responsive">
<table class="table table-striped"> <table class="table table-striped">
<thead> <thead>
<tr> <tr>
<th>Type d'ip</th> <th>Type d'ip</th>
<th>Extension</th> <th>Extension</th>
<th>Nécessite l'autorisation infra</th> <th>Nécessite l'autorisation infra</th>
<th>Début</th> <th>Plage ipv4</th>
<th>Fin</th>
<th>Préfixe v6</th> <th>Préfixe v6</th>
<th>Sur vlan</th> <th>Sur vlan</th>
<th>Ouverture ports par défault</th> <th>Ouverture ports par défault</th>
@ -44,8 +43,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
<td>{{ type.type }}</td> <td>{{ type.type }}</td>
<td>{{ type.extension }}</td> <td>{{ type.extension }}</td>
<td>{{ type.need_infra }}</td> <td>{{ type.need_infra }}</td>
<td>{{ type.domaine_ip_start }}</td> <td>{{ type.domaine_ip_start }}-{{ type.domaine_ip_stop }}</td>
<td>{{ type.domaine_ip_stop }}</td>
<td>{{ type.prefix_v6 }}</td> <td>{{ type.prefix_v6 }}</td>
<td>{{ type.vlan }}</td> <td>{{ type.vlan }}</td>
<td>{{ type.ouverture_ports }}</td> <td>{{ type.ouverture_ports }}</td>
@ -58,4 +56,4 @@ with this program; if not, write to the Free Software Foundation, Inc.,
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
</div>

View file

@ -24,6 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
{% load acl %} {% load acl %}
<div class="table-responsive">
<table class="table table-striped"> <table class="table table-striped">
<thead> <thead>
<tr> <tr>
@ -41,7 +42,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
<td>{{ vlan.comment }}</td> <td>{{ vlan.comment }}</td>
<td>{% for range in vlan.iptype_set.all %}{{ range }}, {% endfor%}</td> <td>{% for range in vlan.iptype_set.all %}{{ range }}, {% endfor%}</td>
<td class="text-right"> <td class="text-right">
{% can_create Vlan %} {% can_edit vlan %}
{% include 'buttons/edit.html' with href='machines:edit-vlan' id=vlan.id %} {% include 'buttons/edit.html' with href='machines:edit-vlan' id=vlan.id %}
{% acl_end %} {% acl_end %}
{% include 'buttons/history.html' with href='machines:history' name='vlan' id=vlan.id %} {% include 'buttons/history.html' with href='machines:history' name='vlan' id=vlan.id %}
@ -49,4 +50,4 @@ with this program; if not, write to the Free Software Foundation, Inc.,
</tr> </tr>
{% endfor %} {% endfor %}
</table> </table>
</div>

View file

@ -34,7 +34,7 @@ from django.dispatch import receiver
from django.core.cache import cache from django.core.cache import cache
from .aes_field import AESEncryptedField from .aes_field import AESEncryptedField
from re2o.mixins import AclMixin
class PreferencesModel(models.Model): class PreferencesModel(models.Model):
@classmethod @classmethod
@ -54,7 +54,7 @@ class PreferencesModel(models.Model):
abstract = True abstract = True
class OptionalUser(PreferencesModel): class OptionalUser(AclMixin, PreferencesModel):
"""Options pour l'user : obligation ou nom du telephone, """Options pour l'user : obligation ou nom du telephone,
activation ou non du solde, autorisation du negatif, fingerprint etc""" activation ou non du solde, autorisation du negatif, fingerprint etc"""
PRETTY_NAME = "Options utilisateur" PRETTY_NAME = "Options utilisateur"
@ -101,58 +101,6 @@ class OptionalUser(PreferencesModel):
("view_optionaluser", "Peut voir les options de l'user"), ("view_optionaluser", "Peut voir les options de l'user"),
) )
def get_instance(*args, **kwargs):
return OptionalUser.objects.get_or_create()
def can_create(user_request, *args, **kwargs):
"""Check if an user can create a OptionalUser object.
:param user_request: The user who wants to create a user object.
:return: a message and a boolean which is True if the user can create.
"""
return user_request.has_perm('preferences.add_optionaluser'), u"Vous n'avez pas le droit\
de créer les préférences concernant les users"
def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit a OptionalUser object.
:param self: The OptionalUser which is to be edited.
:param user_request: The user who requests to edit self.
:return: a message and a boolean which is True if edition is granted.
"""
return user_request.has_perm('preferences.change_optionaluser'), u"Vous n'avez pas le droit\
d'éditer les préférences concernant les users"
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete a OptionalUser object.
:param self: The OptionalUser which is to be deleted.
:param user_request: The user who requests deletion.
:return: True if deletion is granted, and a message.
"""
return user_request.has_perm('preferences.delete_optionaluser'), u"Vous n'avez pas le droit\
de supprimer les préférences concernant les users"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every OptionalUser objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('preferences.view_optionaluser'), u"Vous n'avez pas le droit\
de voir les préférences concernant les utilisateurs"
def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view a OptionalUser object.
:param self: The targeted OptionalUser.
:param user_request: The user who ask for viewing the target.
:return: A boolean telling if the acces is granted and an explanation
text
"""
return user_request.has_perm('preferences.view_optionaluser'), u"Vous n'avez pas le droit\
de voir les préférences concernant les utilisateurs"
def clean(self): def clean(self):
"""Creation du mode de paiement par solde""" """Creation du mode de paiement par solde"""
if self.user_solde: if self.user_solde:
@ -169,7 +117,7 @@ def optionaluser_post_save(sender, **kwargs):
user_pref.set_in_cache() user_pref.set_in_cache()
class OptionalMachine(PreferencesModel): class OptionalMachine(AclMixin, PreferencesModel):
"""Options pour les machines : maximum de machines ou d'alias par user """Options pour les machines : maximum de machines ou d'alias par user
sans droit, activation de l'ipv6""" sans droit, activation de l'ipv6"""
PRETTY_NAME = "Options machines" PRETTY_NAME = "Options machines"
@ -205,59 +153,6 @@ class OptionalMachine(PreferencesModel):
("view_optionalmachine", "Peut voir les options de machine"), ("view_optionalmachine", "Peut voir les options de machine"),
) )
def get_instance(*args, **kwargs):
return OptionalMachine.objects.get_or_create()
def can_create(user_request, *args, **kwargs):
"""Check if an user can create a OptionalMachine object.
:param user_request: The user who wants to create an object.
:return: a message and a boolean which is True if the user can create.
"""
return user_request.has_perm('preferences.add_optionalmachine'), u"Vous n'avez pas le droit\
de créer les préférences concernant les machines"
def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit a OptionalMachine object.
:param self: The OptionalMachine which is to be edited.
:param user_request: The user who requests to edit self.
:return: a message and a boolean which is True if edition is granted.
"""
return user_request.has_perm('preferences.change_optionalmachine'), u"Vous n'avez pas le droit\
d'éditer les préférences concernant les machines"
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete a OptionalMachine object.
:param self: The OptionalMachine which is to be deleted.
:param user_request: The user who requests deletion.
:return: True if deletion is granted, and a message.
"""
return user_request.has_perm('preferences.delete_optionalmachine'), u"Vous n'avez pas le droit\
de supprimer les préférences concernant les machines"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every OptionalMachine objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('preferences.view_optionalmachine'), u"Vous n'avez pas le droit\
de voir les préférences concernant les machines"
def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view a OptionalMachine object.
:param self: The targeted OptionalMachine.
:param user_request: The user who ask for viewing the target.
:return: A boolean telling if the acces is granted and an explanation
text
"""
return user_request.has_perm('preferences.view_optionalmachine'), u"Vous n'avez pas le droit\
de voir les préférences concernant les machines"
@receiver(post_save, sender=OptionalMachine) @receiver(post_save, sender=OptionalMachine)
def optionalmachine_post_save(sender, **kwargs): def optionalmachine_post_save(sender, **kwargs):
@ -269,7 +164,7 @@ def optionalmachine_post_save(sender, **kwargs):
interface.sync_ipv6() interface.sync_ipv6()
class OptionalTopologie(PreferencesModel): class OptionalTopologie(AclMixin, PreferencesModel):
"""Reglages pour la topologie : mode d'accès radius, vlan où placer """Reglages pour la topologie : mode d'accès radius, vlan où placer
les machines en accept ou reject""" les machines en accept ou reject"""
PRETTY_NAME = "Options topologie" PRETTY_NAME = "Options topologie"
@ -306,58 +201,6 @@ class OptionalTopologie(PreferencesModel):
("view_optionaltopologie", "Peut voir les options de topologie"), ("view_optionaltopologie", "Peut voir les options de topologie"),
) )
def get_instance(*args, **kwargs):
return OptionalTopologie.objects.get_or_create()
def can_create(user_request, *args, **kwargs):
"""Check if an user can create a OptionalTopologie object.
:param user_request: The user who wants to create an object.
:return: a message and a boolean which is True if the user can create.
"""
return user_request.has_perm('preferences.add_optionaltopologie'), u"Vous n'avez pas le droit\
de créer les préférences concernant la topologie"
def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit a OptionalTopologie object.
:param self: The OptionalTopologie which is to be edited.
:param user_request: The user who requests to edit self.
:return: a message and a boolean which is True if edition is granted.
"""
return user_request.has_perm('preferences.change_optionaltopologie'), u"Vous n'avez pas le droit\
d'éditer les préférences concernant la topologie"
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete a OptionalTopologie object.
:param self: The OptionalTopologie which is to be deleted.
:param user_request: The user who requests deletion.
:return: True if deletion is granted, and a message.
"""
return user_request.has_perm('preferences.delete_optionaltoplogie'), u"Vous n'avez pas le droit\
d'éditer les préférences concernant la topologie"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every OptionalTopologie objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('preferences.view_optionaltopologie'), u"Vous n'avez pas le droit\
de voir les préférences concernant la topologie"
def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view a OptionalTopologie object.
:param self: The targeted OptionalTopologie.
:param user_request: The user who ask for viewing the target.
:return: A boolean telling if the acces is granted and an explanation
text
"""
return user_request.has_perm('preferences.view_optionaltopologie'), u"Vous n'avez pas le droit\
de voir les préférences concernant la topologie"
@receiver(post_save, sender=OptionalTopologie) @receiver(post_save, sender=OptionalTopologie)
def optionaltopologie_post_save(sender, **kwargs): def optionaltopologie_post_save(sender, **kwargs):
@ -366,7 +209,7 @@ def optionaltopologie_post_save(sender, **kwargs):
topologie_pref.set_in_cache() topologie_pref.set_in_cache()
class GeneralOption(PreferencesModel): class GeneralOption(AclMixin, PreferencesModel):
"""Options générales : nombre de resultats par page, nom du site, """Options générales : nombre de resultats par page, nom du site,
temps les liens sont valides""" temps les liens sont valides"""
PRETTY_NAME = "Options générales" PRETTY_NAME = "Options générales"
@ -398,59 +241,6 @@ class GeneralOption(PreferencesModel):
("view_generaloption", "Peut voir les options générales"), ("view_generaloption", "Peut voir les options générales"),
) )
def get_instance(*args, **kwargs):
return GeneralOption.objects.get_or_create()
def can_create(user_request, *args, **kwargs):
"""Check if an user can create a GeneralOption object.
:param user_request: The user who wants to create an object.
:return: a message and a boolean which is True if the user can create.
"""
return user_request.has_perm('preferences.add_generaloption'), u"Vous n'avez pas le droit\
de créer les préférences générales"
def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit a GeneralOption object.
:param self: The GeneralOption which is to be edited.
:param user_request: The user who requests to edit self.
:return: a message and a boolean which is True if edition is granted.
"""
return user_request.has_perm('preferences.change_generaloption'), u"Vous n'avez pas le droit\
d'éditer les préférences générales"
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete a GeneralOption object.
:param self: The GeneralOption which is to be deleted.
:param user_request: The user who requests deletion.
:return: True if deletion is granted, and a message.
"""
return user_request.has_perm('preferences.delete_generaloption'), u"Vous n'avez pas le droit\
d'éditer les préférences générales"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every GeneralOption objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('preferences.view_generaloption'), u"Vous n'avez pas le droit\
de voir les préférences générales"
def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view a GeneralOption object.
:param self: The targeted GeneralOption.
:param user_request: The user who ask for viewing the target.
:return: A boolean telling if the acces is granted and an explanation
text
"""
return user_request.has_perm('preferences.view_generaloption'), u"Vous n'avez pas le droit\
de voir les préférences générales"
@receiver(post_save, sender=GeneralOption) @receiver(post_save, sender=GeneralOption)
def generaloption_post_save(sender, **kwargs): def generaloption_post_save(sender, **kwargs):
@ -459,7 +249,7 @@ def generaloption_post_save(sender, **kwargs):
general_pref.set_in_cache() general_pref.set_in_cache()
class Service(models.Model): class Service(AclMixin, models.Model):
"""Liste des services affichés sur la page d'accueil : url, description, """Liste des services affichés sur la page d'accueil : url, description,
image et nom""" image et nom"""
name = models.CharField(max_length=32) name = models.CharField(max_length=32)
@ -472,65 +262,11 @@ class Service(models.Model):
("view_service", "Peut voir les options de service"), ("view_service", "Peut voir les options de service"),
) )
def get_instance(serviceid, *args, **kwargs):
return Service.objects.get(pk=serviceid)
def can_create(user_request, *args, **kwargs):
"""Check if an user can create a Service object.
:param user_request: The user who wants to create an object.
:return: a message and a boolean which is True if the user can create.
"""
return user_request.has_perm('preferences.add_service'), u"Vous n'avez pas le droit\
de créer un service pour la page d'accueil"
def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit a Service object.
:param self: The Service which is to be edited.
:param user_request: The user who requests to edit self.
:return: a message and a boolean which is True if edition is granted.
"""
return user_request.has_perm('preferences.change_service'), u"Vous n'avez pas le droit\
d'éditer les services pour la page d'accueil"
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete a Service object.
:param self: The Right which is to be deleted.
:param user_request: The user who requests deletion.
:return: True if deletion is granted, and a message.
"""
return user_request.has_perm('preferences.delete_service'), u"Vous n'avez pas le droit\
de supprimer les services pour la page d'accueil"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every Service objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('preferences.view_service'), u"Vous n'avez pas le droit\
de voir les services pour la page d'accueil"
def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view a Service object.
:param self: The targeted Service.
:param user_request: The user who ask for viewing the target.
:return: A boolean telling if the acces is granted and an explanation
text
"""
return user_request.has_perm('preferences.view_service'), u"Vous n'avez pas le droit\
de voir les services pour la page d'accueil"
def __str__(self): def __str__(self):
return str(self.name) return str(self.name)
class AssoOption(PreferencesModel): class AssoOption(AclMixin, PreferencesModel):
"""Options générales de l'asso : siret, addresse, nom, etc""" """Options générales de l'asso : siret, addresse, nom, etc"""
PRETTY_NAME = "Options de l'association" PRETTY_NAME = "Options de l'association"
@ -579,58 +315,6 @@ class AssoOption(PreferencesModel):
("view_assooption", "Peut voir les options de l'asso"), ("view_assooption", "Peut voir les options de l'asso"),
) )
def get_instance(*args, **kwargs):
return AssoOption.objects.get_or_create()
def can_create(user_request, *args, **kwargs):
"""Check if an user can create a AssoOption object.
:param user_request: The user who wants to create an object.
:return: a message and a boolean which is True if the user can create.
"""
return user_request.has_perm('preferences.add_assooption'), u"Vous n'avez pas le droit\
d'éditer les préférences concernant l'association"
def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit a AssoOption object.
:param self: The AssoOption which is to be edited.
:param user_request: The user who requests to edit self.
:return: a message and a boolean which is True if edition is granted.
"""
return user_request.has_perm('preferences.change_assooption'), u"Vous n'avez pas le droit\
d'éditer les préférences concernant l'association"
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete a AssoOption object.
:param self: The AssoOption which is to be deleted.
:param user_request: The user who requests deletion.
:return: True if deletion is granted, and a message.
"""
return user_request.has_perm('preferences.delete_assooption'), u"Vous n'avez pas le droit\
d'éditer les préférences concernant l'association"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every AssoOption objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('preferences.view_assooption'), u"Vous n'avez pas le droit\
de voir les préférences concernant l'association"
def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view a AssoOption object.
:param self: The targeted AssoOption.
:param user_request: The user who ask for viewing the target.
:return: A boolean telling if the acces is granted and an explanation
text
"""
return user_request.has_perm('preferences.view_assooption'), u"Vous n'avez pas le droit\
de voir les préférences concernant l'association"
@receiver(post_save, sender=AssoOption) @receiver(post_save, sender=AssoOption)
def assooption_post_save(sender, **kwargs): def assooption_post_save(sender, **kwargs):
@ -639,7 +323,7 @@ def assooption_post_save(sender, **kwargs):
asso_pref.set_in_cache() asso_pref.set_in_cache()
class MailMessageOption(models.Model): class MailMessageOption(AclMixin, models.Model):
"""Reglages, mail de bienvenue et autre""" """Reglages, mail de bienvenue et autre"""
PRETTY_NAME = "Options de corps de mail" PRETTY_NAME = "Options de corps de mail"
@ -650,56 +334,3 @@ class MailMessageOption(models.Model):
permissions = ( permissions = (
("view_mailmessageoption", "Peut voir les options de mail"), ("view_mailmessageoption", "Peut voir les options de mail"),
) )
def get_instance(*args, **kwargs):
return MailMessageOption.objects.get_or_create()
def can_create(user_request, *args, **kwargs):
"""Check if an user can create a MailMessageOption object.
:param user_request: The user who wants to create an object.
:return: a message and a boolean which is True if the user can create.
"""
return user_request.has_perm('preferences.add_mailmessageoption'), u"Vous n'avez pas le droit\
d'éditer les préférences concernant les mails"
def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit a MailMessageOption object.
:param self: The MailMessageOption which is to be edited.
:param user_request: The user who requests to edit self.
:return: a message and a boolean which is True if edition is granted.
"""
return user_request.has_perm('preferences.change_mailmessageoption'), u"Vous n'avez pas le droit\
d'éditer les préférences concernant les mails"
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete a AssoOption object.
:param self: The AssoOption which is to be deleted.
:param user_request: The user who requests deletion.
:return: True if deletion is granted, and a message.
"""
return user_request.has_perm('preferences.delete_mailmessageoption'), u"Vous n'avez pas le droit\
d'éditer les préférences concernant les mails"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every AssoOption objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('preferences.view_mailmessageoption'), u"Vous n'avez pas le droit\
de voir les préférences concernant les mails"
def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view a AssoOption object.
:param self: The targeted AssoOption.
:param user_request: The user who ask for viewing the target.
:return: A boolean telling if the acces is granted and an explanation
text
"""
return user_request.has_perm('preferences.view_mailmessageoption'), u"Vous n'avez pas le droit\
de voir les préférences concernant les mails"

88
re2o/mixins.py Normal file
View file

@ -0,0 +1,88 @@
# -*- mode: python; coding: utf-8 -*-
# Re2o est un logiciel d'administration développé initiallement au rezometz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
# Copyright © 2018 Gabriel Détraz
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
class AclMixin(object):
"""This mixin is used in nearly every class/models defined in re2o apps.
It is used by acl, in models (decorators can_...) and in templates tags
:get_instance: Applied on a class, take an id argument, return an instance
:can_create: Applied on a class, take the requested user, return if the user
can do the creation
:can_edit: Applied on an instance, return if the user can edit the instance
:can_delete: Applied on an instance, return if the user can delete the instance
:can_view: Applied on an instance, return if the user can view the instance
:can_view_all: Applied on a class, return if the user can view all instances"""
@classmethod
def get_classname(cls):
return str(cls.__name__).lower()
@classmethod
def get_modulename(cls):
return str(cls.__module__).split('.')[0].lower()
@classmethod
def get_instance(cls, *args, **kwargs):
"""Récupère une instance
:param objectid: Instance id à trouver
:return: Une instance de la classe évidemment"""
object_id = kwargs.get(cls.get_classname() + 'id')
return cls.objects.get(pk=object_id)
@classmethod
def can_create(cls, user_request, *args, **kwargs):
"""Verifie que l'user a les bons droits pour créer
un object
:param user_request: instance utilisateur qui fait la requête
:return: soit True, soit False avec la raison de l'échec"""
return user_request.has_perm(cls.get_modulename() + '.add_' + cls.get_classname()), u"Vous n'avez pas le droit\
de créer un " + cls.get_classname()
def can_edit(self, user_request, *args, **kwargs):
"""Verifie que l'user a les bons droits pour editer
cette instance
:param self: Instance à editer
:param user_request: Utilisateur qui fait la requête
:return: soit True, soit False avec la raison de l'échec"""
return user_request.has_perm(self.get_modulename() + '.change_' + self.get_classname()), u"Vous n'avez pas le droit d'éditer des " + self.get_classname()
def can_delete(self, user_request, *args, **kwargs):
"""Verifie que l'user a les bons droits pour delete
cette instance
:param self: Instance à delete
:param user_request: Utilisateur qui fait la requête
:return: soit True, soit False avec la raison de l'échec"""
return user_request.has_perm(self.get_modulename() + '.delete_' + self.get_classname()), u"Vous n'avez pas le droit d'éditer des " + self.get_classname()
@classmethod
def can_view_all(cls, user_request, *args, **kwargs):
"""Vérifie qu'on peut bien afficher l'ensemble des objets,
droit particulier view objet correspondant
:param user_request: instance user qui fait l'edition
:return: True ou False avec la raison de l'échec le cas échéant"""
return user_request.has_perm(cls.get_modulename() + '.view_' + cls.get_classname()), u"Vous n'avez pas le droit de voir des " + cls.get_classname()
def can_view(self, user_request, *args, **kwargs):
"""Vérifie qu'on peut bien voir cette instance particulière avec
droit view objet
:param self: instance à voir
:param user_request: instance user qui fait l'edition
:return: True ou False avec la raison de l'échec le cas échéant"""
return user_request.has_perm(self.get_modulename() + '.view_' + self.get_classname()), u"Vous n'avez pas le droit de voir des " + self.get_classname()

View file

@ -190,6 +190,10 @@ class SortTable:
'white_end': ['date_end'], 'white_end': ['date_end'],
'default': ['-date_end'] 'default': ['-date_end']
} }
USERS_INDEX_SCHOOL = {
'school_name': ['name'],
'default': ['name']
}
MACHINES_INDEX = { MACHINES_INDEX = {
'machine_name': ['name'], 'machine_name': ['name'],
'default': ['pk'] 'default': ['pk']

View file

@ -65,7 +65,7 @@ HISTORY_BIND = {
'school' : users.models.School, 'school' : users.models.School,
'listright' : users.models.ListRight, 'listright' : users.models.ListRight,
'serviceuser' : users.models.ServiceUser, 'serviceuser' : users.models.ServiceUser,
'shell' : users.models.ListShell, 'listshell' : users.models.ListShell,
}, },
'preferences' : { 'preferences' : {
'service' : preferences.models.Service, 'service' : preferences.models.Service,
@ -81,9 +81,9 @@ HISTORY_BIND = {
'port' : topologie.models.Port, 'port' : topologie.models.Port,
'room' : topologie.models.Room, 'room' : topologie.models.Room,
'stack' : topologie.models.Stack, 'stack' : topologie.models.Stack,
'model_switch' : topologie.models.ModelSwitch, 'modelswitch' : topologie.models.ModelSwitch,
'constructor_switch' : topologie.models.ConstructorSwitch, 'constructorswitch' : topologie.models.ConstructorSwitch,
'ap' : topologie.models.AccessPoint, 'accesspoint' : topologie.models.AccessPoint,
}, },
'machines' : { 'machines' : {
'machine' : machines.models.Machine, 'machine' : machines.models.Machine,
@ -99,7 +99,7 @@ HISTORY_BIND = {
'ns' : machines.models.Ns, 'ns' : machines.models.Ns,
'service' : machines.models.Service, 'service' : machines.models.Service,
'vlan' : machines.models.Vlan, 'vlan' : machines.models.Vlan,
'nas' : machines.models.Vlan, 'nas' : machines.models.Nas,
'ipv6list' : machines.models.Ipv6List, 'ipv6list' : machines.models.Ipv6List,
}, },
} }
@ -128,8 +128,10 @@ def history(request, application, object_name, object_id):
model = HISTORY_BIND[application][object_name] model = HISTORY_BIND[application][object_name]
except KeyError as e: except KeyError as e:
raise Http404(u"Il n'existe pas d'historique pour ce modèle.") raise Http404(u"Il n'existe pas d'historique pour ce modèle.")
object_name_id = object_name + 'id'
kwargs = {object_name_id: object_id}
try: try:
instance = model.get_instance(object_id) instance = model.get_instance(**kwargs)
except model.DoesNotExist: except model.DoesNotExist:
messages.error(request, u"Entrée inexistante") messages.error(request, u"Entrée inexistante")
return redirect(reverse('users:profil', return redirect(reverse('users:profil',

View file

@ -83,7 +83,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><i class="fa fa-users"></i> Adhérents<span class="caret"></span></a> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><i class="fa fa-users"></i> Adhérents<span class="caret"></span></a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
{% can_view_app users %} {% can_view_app users %}
<li><a href="{% url 'users:index' %}"><i class="fa fa-users"></i> Gérer les adhérents</a></li> <li><a href="{% url 'users:index' %}"><i class="fa fa-user"></i> Gérer les adhérents</a></li>
<li><a href="{% url 'users:index-clubs' %}"><i class="fa fa-users"></i> Gérer les clubs</a></li>
{% acl_end %} {% acl_end %}
{% can_view_app machines %} {% can_view_app machines %}
<li><a href="{% url 'machines:index' %}"><i class="fa fa-desktop"></i> Gérer les machines</a></li> <li><a href="{% url 'machines:index' %}"><i class="fa fa-desktop"></i> Gérer les machines</a></li>
@ -95,7 +96,14 @@ with this program; if not, write to the Free Software Foundation, Inc.,
</li> </li>
{% acl_end %} {% acl_end %}
{% can_view_app topologie %} {% can_view_app topologie %}
<li><a href="{% url "topologie:index" %}"><i class="fa fa-sitemap"></i> Topologie</a></li> <li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><i class="fa fa-sitemap"></i> Topologie<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="{% url "topologie:index" %}"><i class="fa fa-microchip"></i> Switchs</a></li>
<li><a href="{% url "topologie:index-ap" %}"><i class="fa fa-wifi"></i> Bornes WiFi</a></li>
<li><a href="{% url "topologie:index-room" %}"><i class="fa fa-home"></i> Chambres et locaux</a></li>
</ul>
</li>
{% acl_end %} {% acl_end %}
{% can_view_app logs %} {% can_view_app logs %}
<li><a href="{% url "logs:index" %}"><i class="fa fa-chart-area"></i> Statistiques</a></li> <li><a href="{% url "logs:index" %}"><i class="fa fa-chart-area"></i> Statistiques</a></li>

View file

@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2018-03-29 02:31
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('topologie', '0054_auto_20180326_1742'),
]
operations = [
migrations.AlterModelOptions(
name='accesspoint',
options={'permissions': (('view_accesspoint', 'Peut voir une borne'),)},
),
]

View file

@ -47,9 +47,10 @@ from django.db import IntegrityError
from django.db import transaction from django.db import transaction
from reversion import revisions as reversion from reversion import revisions as reversion
from machines.models import Machine, Interface from machines.models import Machine, Interface, regen
from re2o.mixins import AclMixin
class Stack(models.Model): class Stack(AclMixin, models.Model):
"""Un objet stack. Regrouppe des switchs en foreign key """Un objet stack. Regrouppe des switchs en foreign key
,contient une id de stack, un switch id min et max dans ,contient une id de stack, un switch id min et max dans
le stack""" le stack"""
@ -66,33 +67,6 @@ class Stack(models.Model):
("view_stack", "Peut voir un objet stack"), ("view_stack", "Peut voir un objet stack"),
) )
def get_instance(stack_id, *args, **kwargs):
return Stack.objects.get(pk=stack_id)
def can_create(user_request, *args, **kwargs):
return user_request.has_perm('topologie.add_stack') , u"Vous n'avez pas le droit\
de créer un stack"
def can_edit(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.change_stack'):
return False, u"Vous n'avez pas le droit d'éditer des stack"
return True, None
def can_delete(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.delete_stack'):
return False, u"Vous n'avez pas le droit de supprimer une stack"
return True, None
def can_view_all(user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_stack'):
return False, u"Vous n'avez pas le droit de voir une stack"
return True, None
def can_view(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_stack'):
return False, u"Vous n'avez pas le droit de voir une stack"
return True, None
def __str__(self): def __str__(self):
return " ".join([self.name, self.stack_id]) return " ".join([self.name, self.stack_id])
@ -109,7 +83,7 @@ class Stack(models.Model):
inférieure à l'id minimale"}) inférieure à l'id minimale"})
class AccessPoint(Machine): class AccessPoint(AclMixin, Machine):
"""Define a wireless AP. Inherit from machines.interfaces """Define a wireless AP. Inherit from machines.interfaces
Definition pour une borne wifi , hérite de machines.interfaces Definition pour une borne wifi , hérite de machines.interfaces
@ -125,38 +99,11 @@ class AccessPoint(Machine):
class Meta: class Meta:
permissions = ( permissions = (
("view_ap", "Peut voir une borne"), ("view_accesspoint", "Peut voir une borne"),
) )
def get_instance(ap_id, *args, **kwargs):
return AccessPoint.objects.get(pk=ap_id)
def can_create(user_request, *args, **kwargs): class Switch(AclMixin, Machine):
return user_request.has_perm('topologie.add_ap') , u"Vous n'avez pas le droit\
de créer une borne"
def can_edit(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.change_ap'):
return False, u"Vous n'avez pas le droit d'éditer des bornes"
return True, None
def can_delete(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.delete_ap'):
return False, u"Vous n'avez pas le droit de supprimer une borne"
return True, None
def can_view_all(user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_ap'):
return False, u"Vous n'avez pas le droit de voir les bornes"
return True, None
def can_view(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_ap'):
return False, u"Vous n'avez pas le droit de voir les bornes"
return True, None
class Switch(Machine):
""" Definition d'un switch. Contient un nombre de ports (number), """ Definition d'un switch. Contient un nombre de ports (number),
un emplacement (location), un stack parent (optionnel, stack) un emplacement (location), un stack parent (optionnel, stack)
et un id de membre dans le stack (stack_member_id) et un id de membre dans le stack (stack_member_id)
@ -193,33 +140,6 @@ class Switch(Machine):
("view_switch", "Peut voir un objet switch"), ("view_switch", "Peut voir un objet switch"),
) )
def get_instance(switch_id, *args, **kwargs):
return Switch.objects.get(pk=switch_id)
def can_create(user_request, *args, **kwargs):
return user_request.has_perm('topologie.add_switch') , u"Vous n'avez pas le droit\
de créer un switch"
def can_edit(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.change_switch'):
return False, u"Vous n'avez pas le droit d'éditer des switch"
return True, None
def can_delete(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.delete_switch'):
return False, u"Vous n'avez pas le droit de supprimer un switch"
return True, None
def can_view_all(user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_switch'):
return False, u"Vous n'avez pas le droit de voir les switch"
return True, None
def can_view(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_switch'):
return False, u"Vous n'avez pas le droit de voir les switch"
return True, None
def clean(self): def clean(self):
""" Verifie que l'id stack est dans le bon range """ Verifie que l'id stack est dans le bon range
Appelle également le clean de la classe parente""" Appelle également le clean de la classe parente"""
@ -267,7 +187,7 @@ class Switch(Machine):
return str(self.interface_set.first()) return str(self.interface_set.first())
class ModelSwitch(models.Model): class ModelSwitch(AclMixin, models.Model):
"""Un modèle (au sens constructeur) de switch""" """Un modèle (au sens constructeur) de switch"""
PRETTY_NAME = "Modèle de switch" PRETTY_NAME = "Modèle de switch"
reference = models.CharField(max_length=255) reference = models.CharField(max_length=255)
@ -281,38 +201,11 @@ class ModelSwitch(models.Model):
("view_modelswitch", "Peut voir un objet modelswitch"), ("view_modelswitch", "Peut voir un objet modelswitch"),
) )
def get_instance(model_switch_id, *args, **kwargs):
return ModelSwitch.objects.get(pk=model_switch_id)
def can_create(user_request, *args, **kwargs):
return user_request.has_perm('topologie.add_modelswitch') , u"Vous n'avez pas le droit\
de créer un modèle de switch"
def can_edit(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.change_modelswitch'):
return False, u"Vous n'avez pas le droit d'éditer des modèle de switchs"
return True, None
def can_delete(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.delete_modelswitch'):
return False, u"Vous n'avez pas le droit de supprimer un modèle switch"
return True, None
def can_view(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_modelswitch'):
return False, u"Vous n'avez pas le droit de voir un modèle switch"
return True, None
def can_view_all(user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_modelswitch'):
return False, u"Vous n'avez pas le droit de voir un modèle switch"
return True, None
def __str__(self): def __str__(self):
return str(self.constructor) + ' ' + self.reference return str(self.constructor) + ' ' + self.reference
class ConstructorSwitch(models.Model): class ConstructorSwitch(AclMixin, models.Model):
"""Un constructeur de switch""" """Un constructeur de switch"""
PRETTY_NAME = "Constructeur de switch" PRETTY_NAME = "Constructeur de switch"
name = models.CharField(max_length=255) name = models.CharField(max_length=255)
@ -322,39 +215,11 @@ class ConstructorSwitch(models.Model):
("view_constructorswitch", "Peut voir un objet constructorswitch"), ("view_constructorswitch", "Peut voir un objet constructorswitch"),
) )
def get_instance(constructor_switch_id, *args, **kwargs):
return ConstructorSwitch.objects.get(pk=constructor_switch_id)
def can_create(user_request, *args, **kwargs):
return user_request.has_perm('topologie.add_constructorswitch') , u"Vous n'avez pas le droit\
de créer un constructeur de switch"
def can_edit(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.change_constructorswitch'):
return False, u"Vous n'avez pas le droit d'éditer des\
constructeurs de switchs"
return True, None
def can_delete(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.delete_constructorswitch'):
return False, u"Vous n'avez pas le droit de supprimer un constructeur"
return True, None
def can_view_all(user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_constructorswitch'):
return False, u"Vous n'avez pas le droit de voir un constructeur"
return True, None
def can_view(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_constructorswitch'):
return False, u"Vous n'avez pas le droit de voir un constructeur"
return True, None
def __str__(self): def __str__(self):
return self.name return self.name
class Port(models.Model): class Port(AclMixin, models.Model):
""" Definition d'un port. Relié à un switch(foreign_key), """ Definition d'un port. Relié à un switch(foreign_key),
un port peut etre relié de manière exclusive à : un port peut etre relié de manière exclusive à :
- une chambre (room) - une chambre (room)
@ -417,38 +282,14 @@ class Port(models.Model):
("view_port", "Peut voir un objet port"), ("view_port", "Peut voir un objet port"),
) )
def get_instance(port_id, *args, **kwargs): def get_instance(portid, *args, **kwargs):
return Port.objects\ return Port.objects\
.select_related('machine_interface__domain__extension')\ .select_related('machine_interface__domain__extension')\
.select_related('machine_interface__machine__switch')\ .select_related('machine_interface__machine__switch')\
.select_related('room')\ .select_related('room')\
.select_related('related')\ .select_related('related')\
.prefetch_related('switch__interface_set__domain__extension')\ .prefetch_related('switch__interface_set__domain__extension')\
.get(pk=port_id) .get(pk=portid)
def can_create(user_request, *args, **kwargs):
return user_request.has_perm('topologie.add_port') , u"Vous n'avez pas le droit\
de créer un port"
def can_edit(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.change_port'):
return False, u"Vous n'avez pas le droit d'éditer des ports"
return True, None
def can_delete(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.delete_port'):
return False, u"Vous n'avez pas le droit de supprimer un port"
return True, None
def can_view_all(user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_port'):
return False, u"Vous n'avez pas le droit de voir les ports"
return True, None
def can_view(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_port'):
return False, u"Vous n'avez pas le droit de voir les ports"
return True, None
def make_port_related(self): def make_port_related(self):
""" Synchronise le port distant sur self""" """ Synchronise le port distant sur self"""
@ -494,7 +335,7 @@ class Port(models.Model):
return str(self.switch) + " - " + str(self.port) return str(self.switch) + " - " + str(self.port)
class Room(models.Model): class Room(AclMixin, models.Model):
"""Une chambre/local contenant une prise murale""" """Une chambre/local contenant une prise murale"""
PRETTY_NAME = "Chambre/ Prise murale" PRETTY_NAME = "Chambre/ Prise murale"
@ -507,33 +348,6 @@ class Room(models.Model):
("view_room", "Peut voir un objet chambre"), ("view_room", "Peut voir un objet chambre"),
) )
def get_instance(room_id, *args, **kwargs):
return Room.objects.get(pk=room_id)
def can_create(user_request, *args, **kwargs):
return user_request.has_perm('topologie.add_room') , u"Vous n'avez pas le droit\
de créer une chambre"
def can_edit(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.change_room'):
return False, u"Vous n'avez pas le droit d'éditer une chambre"
return True, None
def can_delete(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.delete_room'):
return False, u"Vous n'avez pas le droit de supprimer une chambre"
return True, None
def can_view_all(user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_room'):
return False, u"Vous n'avez pas le droit de voir les chambres"
return True, None
def can_view(self, user_request, *args, **kwargs):
if not user_request.has_perm('topologie.view_room'):
return False, u"Vous n'avez pas le droit de voir les chambres"
return True, None
def __str__(self): def __str__(self):
return self.name return self.name

View file

@ -49,7 +49,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
<td>{{ap.interface_set.first.details}}</td> <td>{{ap.interface_set.first.details}}</td>
<td>{{ap.location}}</td> <td>{{ap.location}}</td>
<td class="text-right"> <td class="text-right">
<a class="btn btn-info btn-sm" role="button" title="Historique" href="{% url 'topologie:history' 'ap' ap.pk %}"> <a class="btn btn-info btn-sm" role="button" title="Historique" href="{% url 'topologie:history' 'accesspoint' ap.pk %}">
<i class="fa fa-history"></i> <i class="fa fa-history"></i>
</a> </a>
{% can_edit ap %} {% can_edit ap %}

View file

@ -39,7 +39,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
<tr> <tr>
<td>{{constructor_switch}}</td> <td>{{constructor_switch}}</td>
<td class="text-right"> <td class="text-right">
<a class="btn btn-info btn-sm" role="button" title="Historique" href="{% url 'topologie:history' 'constructor_switch' constructor_switch.pk %}"> <a class="btn btn-info btn-sm" role="button" title="Historique" href="{% url 'topologie:history' 'constructorswitch' constructor_switch.pk %}">
<i class="fa fa-history"></i> <i class="fa fa-history"></i>
</a> </a>
{% can_edit constructor_switch %} {% can_edit constructor_switch %}

View file

@ -41,7 +41,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
<td>{{model_switch.reference}}</td> <td>{{model_switch.reference}}</td>
<td>{{model_switch.constructor}}</td> <td>{{model_switch.constructor}}</td>
<td class="text-right"> <td class="text-right">
<a class="btn btn-info btn-sm" role="button" title="Historique" href="{% url 'topologie:history' 'model_switch' model_switch.pk %}"> <a class="btn btn-info btn-sm" role="button" title="Historique" href="{% url 'topologie:history' 'modelswitch' model_switch.pk %}">
<i class="fa fa-history"></i> <i class="fa fa-history"></i>
</a> </a>
{% can_edit model_switch %} {% can_edit model_switch %}

View file

@ -52,7 +52,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
</td> </td>
<td> <td>
{% if port.related %} {% if port.related %}
<a href="{% url 'topologie:index-port' switch_id=port.related.switch.id %}">{{ port.related }}</a> <a href="{% url 'topologie:index-port' switchid=port.related.switch.id %}">{{ port.related }}</a>
{% endif %} {% endif %}
</td> </td>
<td>{{ port.radius }}</td> <td>{{ port.radius }}</td>

View file

@ -33,8 +33,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
<a class="btn btn-primary btn-sm" role="button" href="{% url 'topologie:edit-switch' id_switch %}"><i class="fa fa-edit"></i> Editer</a> <a class="btn btn-primary btn-sm" role="button" href="{% url 'topologie:edit-switch' id_switch %}"><i class="fa fa-edit"></i> Editer</a>
{% can_create Port %} {% can_create Port %}
<a class="btn btn-primary btn-sm" role="button" href="{% url 'topologie:new-port' id_switch %}"><i class="fa fa-plus"></i> Ajouter un port</a> <a class="btn btn-primary btn-sm" role="button" href="{% url 'topologie:new-port' id_switch %}"><i class="fa fa-plus"></i> Ajouter un port</a>
{% acl_end %}
<a class="btn btn-primary btn-sm" role="button" href="{% url 'topologie:create-ports' id_switch %}"><i class="fa fa-plus"></i> Ajouter des ports</a> <a class="btn btn-primary btn-sm" role="button" href="{% url 'topologie:create-ports' id_switch %}"><i class="fa fa-plus"></i> Ajouter des ports</a>
{% acl_end %}
{% include "topologie/aff_port.html" with port_list=port_list %} {% include "topologie/aff_port.html" with port_list=port_list %}
<br /> <br />
<br /> <br />

View file

@ -37,18 +37,18 @@ urlpatterns = [
url(r'^$', views.index, name='index'), url(r'^$', views.index, name='index'),
url(r'^index_ap/$', views.index_ap, name='index-ap'), url(r'^index_ap/$', views.index_ap, name='index-ap'),
url(r'^new_ap/$', views.new_ap, name='new-ap'), url(r'^new_ap/$', views.new_ap, name='new-ap'),
url(r'^edit_ap/(?P<ap_id>[0-9]+)$', url(r'^edit_ap/(?P<accesspointid>[0-9]+)$',
views.edit_ap, views.edit_ap,
name='edit-ap'), name='edit-ap'),
url(r'^create_ports/(?P<switch_id>[0-9]+)$', url(r'^create_ports/(?P<switchid>[0-9]+)$',
views.create_ports, views.create_ports,
name='create-ports'), name='create-ports'),
url(r'^index_room/$', views.index_room, name='index-room'), url(r'^index_room/$', views.index_room, name='index-room'),
url(r'^new_room/$', views.new_room, name='new-room'), url(r'^new_room/$', views.new_room, name='new-room'),
url(r'^edit_room/(?P<room_id>[0-9]+)$', views.edit_room, name='edit-room'), url(r'^edit_room/(?P<roomid>[0-9]+)$', views.edit_room, name='edit-room'),
url(r'^del_room/(?P<room_id>[0-9]+)$', views.del_room, name='del-room'), url(r'^del_room/(?P<roomid>[0-9]+)$', views.del_room, name='del-room'),
url(r'^new_switch/$', views.new_switch, name='new-switch'), url(r'^new_switch/$', views.new_switch, name='new-switch'),
url(r'^switch/(?P<switch_id>[0-9]+)$', url(r'^switch/(?P<switchid>[0-9]+)$',
views.index_port, views.index_port,
name='index-port'), name='index-port'),
url( url(
@ -57,18 +57,18 @@ urlpatterns = [
name='history', name='history',
kwargs={'application':'topologie'}, kwargs={'application':'topologie'},
), ),
url(r'^edit_port/(?P<port_id>[0-9]+)$', views.edit_port, name='edit-port'), url(r'^edit_port/(?P<portid>[0-9]+)$', views.edit_port, name='edit-port'),
url(r'^new_port/(?P<switch_id>[0-9]+)$', views.new_port, name='new-port'), url(r'^new_port/(?P<switchid>[0-9]+)$', views.new_port, name='new-port'),
url(r'^del_port/(?P<port_id>[0-9]+)$', views.del_port, name='del-port'), url(r'^del_port/(?P<portid>[0-9]+)$', views.del_port, name='del-port'),
url(r'^edit_switch/(?P<switch_id>[0-9]+)$', url(r'^edit_switch/(?P<switchid>[0-9]+)$',
views.edit_switch, views.edit_switch,
name='edit-switch'), name='edit-switch'),
url(r'^new_stack/$', views.new_stack, name='new-stack'), url(r'^new_stack/$', views.new_stack, name='new-stack'),
url(r'^index_stack/$', views.index_stack, name='index-stack'), url(r'^index_stack/$', views.index_stack, name='index-stack'),
url(r'^edit_stack/(?P<stack_id>[0-9]+)$', url(r'^edit_stack/(?P<stackid>[0-9]+)$',
views.edit_stack, views.edit_stack,
name='edit-stack'), name='edit-stack'),
url(r'^del_stack/(?P<stack_id>[0-9]+)$', url(r'^del_stack/(?P<stackid>[0-9]+)$',
views.del_stack, views.del_stack,
name='del-stack'), name='del-stack'),
url(r'^index_model_switch/$', url(r'^index_model_switch/$',
@ -83,20 +83,20 @@ urlpatterns = [
views.new_model_switch, views.new_model_switch,
name='new-model-switch' name='new-model-switch'
), ),
url(r'^edit_model_switch/(?P<model_switch_id>[0-9]+)$', url(r'^edit_model_switch/(?P<modelswitchid>[0-9]+)$',
views.edit_model_switch, views.edit_model_switch,
name='edit-model-switch'), name='edit-model-switch'),
url(r'^del_model_switch/(?P<model_switch_id>[0-9]+)$', url(r'^del_model_switch/(?P<modelswitchid>[0-9]+)$',
views.del_model_switch, views.del_model_switch,
name='del-model-switch'), name='del-model-switch'),
url(r'^new_constructor_switch/$', url(r'^new_constructor_switch/$',
views.new_constructor_switch, views.new_constructor_switch,
name='new-constructor-switch' name='new-constructor-switch'
), ),
url(r'^edit_constructor_switch/(?P<constructor_switch_id>[0-9]+)$', url(r'^edit_constructor_switch/(?P<constructorswitchid>[0-9]+)$',
views.edit_constructor_switch, views.edit_constructor_switch,
name='edit-constructor-switch'), name='edit-constructor-switch'),
url(r'^del_constructor_switch/(?P<constructor_switch_id>[0-9]+)$', url(r'^del_constructor_switch/(?P<constructorswitchid>[0-9]+)$',
views.del_constructor_switch, views.del_constructor_switch,
name='del-constructor-switch'), name='del-constructor-switch'),
] ]

View file

@ -123,7 +123,7 @@ def index(request):
@login_required @login_required
@can_view_all(Port) @can_view_all(Port)
@can_view(Switch) @can_view(Switch)
def index_port(request, switch, switch_id): def index_port(request, switch, switchid):
""" Affichage de l'ensemble des ports reliés à un switch particulier""" """ Affichage de l'ensemble des ports reliés à un switch particulier"""
port_list = Port.objects.filter(switch=switch)\ port_list = Port.objects.filter(switch=switch)\
.select_related('room')\ .select_related('room')\
@ -143,7 +143,7 @@ def index_port(request, switch, switch_id):
) )
return render(request, 'topologie/index_p.html', { return render(request, 'topologie/index_p.html', {
'port_list': port_list, 'port_list': port_list,
'id_switch': switch_id, 'id_switch': switchid,
'nom_switch': switch 'nom_switch': switch
}) })
@ -250,10 +250,10 @@ def index_model_switch(request):
@login_required @login_required
@can_create(Port) @can_create(Port)
def new_port(request, switch_id): def new_port(request, switchid):
""" Nouveau port""" """ Nouveau port"""
try: try:
switch = Switch.objects.get(pk=switch_id) switch = Switch.objects.get(pk=switchid)
except Switch.DoesNotExist: except Switch.DoesNotExist:
messages.error(request, u"Switch inexistant") messages.error(request, u"Switch inexistant")
return redirect(reverse('topologie:index')) return redirect(reverse('topologie:index'))
@ -271,14 +271,14 @@ def new_port(request, switch_id):
messages.error(request, "Ce port existe déjà") messages.error(request, "Ce port existe déjà")
return redirect(reverse( return redirect(reverse(
'topologie:index-port', 'topologie:index-port',
kwargs={'switch_id':switch_id} kwargs={'switchid':switchid}
)) ))
return form({'id_switch': switch_id,'topoform': port, 'action_name' : 'Ajouter'}, 'topologie/topo.html', request) return form({'id_switch': switchid,'topoform': port, 'action_name' : 'Ajouter'}, 'topologie/topo.html', request)
@login_required @login_required
@can_edit(Port) @can_edit(Port)
def edit_port(request, port_object, port_id): def edit_port(request, port_object, portid):
""" Edition d'un port. Permet de changer le switch parent et """ Edition d'un port. Permet de changer le switch parent et
l'affectation du port""" l'affectation du port"""
@ -293,14 +293,14 @@ def edit_port(request, port_object, port_id):
messages.success(request, "Le port a bien été modifié") messages.success(request, "Le port a bien été modifié")
return redirect(reverse( return redirect(reverse(
'topologie:index-port', 'topologie:index-port',
kwargs={'switch_id': str(port_object.switch.id)} kwargs={'switchid': str(port_object.switch.id)}
)) ))
return form({'id_switch': str(port_object.switch.id), 'topoform': port, 'action_name' : 'Editer'}, 'topologie/topo.html', request) return form({'id_switch': str(port_object.switch.id), 'topoform': port, 'action_name' : 'Editer'}, 'topologie/topo.html', request)
@login_required @login_required
@can_delete(Port) @can_delete(Port)
def del_port(request, port, port_id): def del_port(request, port, portid):
""" Supprime le port""" """ Supprime le port"""
if request.method == "POST": if request.method == "POST":
try: try:
@ -314,7 +314,7 @@ def del_port(request, port, port_id):
impossible de le supprimer" % port) impossible de le supprimer" % port)
return redirect(reverse( return redirect(reverse(
'topologie:index-port', 'topologie:index-port',
kwargs={'switch_id':str(port.switch.id)} kwargs={'switchid':str(port.switch.id)}
)) ))
return form({'objet': port}, 'topologie/delete.html', request) return form({'objet': port}, 'topologie/delete.html', request)
@ -322,7 +322,7 @@ def del_port(request, port, port_id):
@login_required @login_required
@can_create(Stack) @can_create(Stack)
def new_stack(request): def new_stack(request):
"""Ajoute un nouveau stack : stack_id_min, max, et nombre de switches""" """Ajoute un nouveau stack : stackid_min, max, et nombre de switches"""
stack = StackForm(request.POST or None) stack = StackForm(request.POST or None)
if stack.is_valid(): if stack.is_valid():
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
@ -335,7 +335,7 @@ def new_stack(request):
@login_required @login_required
@can_edit(Stack) @can_edit(Stack)
def edit_stack(request, stack, stack_id): def edit_stack(request, stack, stackid):
"""Edition d'un stack (nombre de switches, nom...)""" """Edition d'un stack (nombre de switches, nom...)"""
stack = StackForm(request.POST or None, instance=stack) stack = StackForm(request.POST or None, instance=stack)
@ -354,7 +354,7 @@ def edit_stack(request, stack, stack_id):
@login_required @login_required
@can_delete(Stack) @can_delete(Stack)
def del_stack(request, stack, stack_id): def del_stack(request, stack, stackid):
"""Supprime un stack""" """Supprime un stack"""
if request.method == "POST": if request.method == "POST":
try: try:
@ -372,7 +372,7 @@ def del_stack(request, stack, stack_id):
@login_required @login_required
@can_edit(Stack) @can_edit(Stack)
def edit_switchs_stack(request, stack, stack_id): def edit_switchs_stack(request, stack, stackid):
"""Permet d'éditer la liste des switches dans une stack et l'ajouter""" """Permet d'éditer la liste des switches dans une stack et l'ajouter"""
if request.method == "POST": if request.method == "POST":
@ -440,10 +440,10 @@ def new_switch(request):
@login_required @login_required
@can_create(Port) @can_create(Port)
def create_ports(request, switch_id): def create_ports(request, switchid):
""" Création d'une liste de ports pour un switch.""" """ Création d'une liste de ports pour un switch."""
try: try:
switch = Switch.objects.get(pk=switch_id) switch = Switch.objects.get(pk=switchid)
except Switch.DoesNotExist: except Switch.DoesNotExist:
messages.error(request, u"Switch inexistant") messages.error(request, u"Switch inexistant")
return redirect(reverse('topologie:index')) return redirect(reverse('topologie:index'))
@ -471,14 +471,14 @@ def create_ports(request, switch_id):
return redirect(reverse( return redirect(reverse(
'topologie:index-port', 'topologie:index-port',
kwargs={'switch_id':switch_id} kwargs={'switchid':switchid}
)) ))
return form({'id_switch': switch_id, 'topoform': port_form}, 'topologie/switch.html', request) return form({'id_switch': switchid, 'topoform': port_form}, 'topologie/switch.html', request)
@login_required @login_required
@can_edit(Switch) @can_edit(Switch)
def edit_switch(request, switch, switch_id): def edit_switch(request, switch, switchid):
""" Edition d'un switch. Permet de chambre nombre de ports, """ Edition d'un switch. Permet de chambre nombre de ports,
place dans le stack, interface et machine associée""" place dans le stack, interface et machine associée"""
@ -524,7 +524,7 @@ def edit_switch(request, switch, switch_id):
return redirect(reverse('topologie:index')) return redirect(reverse('topologie:index'))
i_mbf_param = generate_ipv4_mbf_param(interface_form, False ) i_mbf_param = generate_ipv4_mbf_param(interface_form, False )
return form({ return form({
'id_switch': switch_id, 'id_switch': switchid,
'topoform': interface_form, 'topoform': interface_form,
'machineform': switch_form, 'machineform': switch_form,
'domainform': domain_form, 'domainform': domain_form,
@ -590,7 +590,7 @@ def new_ap(request):
@login_required @login_required
@can_edit(AccessPoint) @can_edit(AccessPoint)
def edit_ap(request, ap, ap_id): def edit_ap(request, ap, accesspointid):
""" Edition d'un switch. Permet de chambre nombre de ports, """ Edition d'un switch. Permet de chambre nombre de ports,
place dans le stack, interface et machine associée""" place dans le stack, interface et machine associée"""
interface_form = EditInterfaceForm( interface_form = EditInterfaceForm(
@ -665,7 +665,7 @@ def new_room(request):
@login_required @login_required
@can_edit(Room) @can_edit(Room)
def edit_room(request, room, room_id): def edit_room(request, room, roomid):
""" Edition numero et details de la chambre""" """ Edition numero et details de la chambre"""
room = EditRoomForm(request.POST or None, instance=room) room = EditRoomForm(request.POST or None, instance=room)
@ -683,7 +683,7 @@ def edit_room(request, room, room_id):
@login_required @login_required
@can_delete(Room) @can_delete(Room)
def del_room(request, room, room_id): def del_room(request, room, roomid):
""" Suppression d'un chambre""" """ Suppression d'un chambre"""
if request.method == "POST": if request.method == "POST":
try: try:
@ -719,7 +719,7 @@ def new_model_switch(request):
@login_required @login_required
@can_edit(ModelSwitch) @can_edit(ModelSwitch)
def edit_model_switch(request, model_switch, model_switch_id): def edit_model_switch(request, model_switch, modelswitchid):
""" Edition d'un modèle de switch""" """ Edition d'un modèle de switch"""
model_switch = EditModelSwitchForm(request.POST or None, instance=model_switch) model_switch = EditModelSwitchForm(request.POST or None, instance=model_switch)
@ -737,7 +737,7 @@ def edit_model_switch(request, model_switch, model_switch_id):
@login_required @login_required
@can_delete(ModelSwitch) @can_delete(ModelSwitch)
def del_model_switch(request, model_switch_id): def del_model_switch(request, model_switch, modelswitchid):
""" Suppression d'un modèle de switch""" """ Suppression d'un modèle de switch"""
if request.method == "POST": if request.method == "POST":
try: try:
@ -773,7 +773,7 @@ def new_constructor_switch(request):
@login_required @login_required
@can_edit(ConstructorSwitch) @can_edit(ConstructorSwitch)
def edit_constructor_switch(request, constructor_switch, constructor_switch_id): def edit_constructor_switch(request, constructor_switch, constructorswitchid):
""" Edition d'un constructeur de switch""" """ Edition d'un constructeur de switch"""
constructor_switch = EditConstructorSwitchForm(request.POST or None, instance=constructor_switch) constructor_switch = EditConstructorSwitchForm(request.POST or None, instance=constructor_switch)
@ -791,7 +791,7 @@ def edit_constructor_switch(request, constructor_switch, constructor_switch_id):
@login_required @login_required
@can_delete(ConstructorSwitch) @can_delete(ConstructorSwitch)
def del_constructor_switch(request, constructor_switch_id): def del_constructor_switch(request, constructor_switch, constructorswitchid):
""" Suppression d'un constructeur de switch""" """ Suppression d'un constructeur de switch"""
if request.method == "POST": if request.method == "POST":
try: try:

View file

@ -76,6 +76,7 @@ import ldapdb.models.fields
from re2o.settings import RIGHTS_LINK, LDAP, GID_RANGES, UID_RANGES from re2o.settings import RIGHTS_LINK, LDAP, GID_RANGES, UID_RANGES
from re2o.login import hashNT from re2o.login import hashNT
from re2o.field_permissions import FieldPermissionModelMixin from re2o.field_permissions import FieldPermissionModelMixin
from re2o.mixins import AclMixin
from cotisations.models import Cotisation, Facture, Paiement, Vente from cotisations.models import Cotisation, Facture, Paiement, Vente
from machines.models import Domain, Interface, Machine, regen from machines.models import Domain, Interface, Machine, regen
@ -170,7 +171,7 @@ class UserManager(BaseUserManager):
""" """
return self._create_user(pseudo, surname, email, password, True) return self._create_user(pseudo, surname, email, password, True)
class User(FieldPermissionModelMixin, AbstractBaseUser, PermissionsMixin): class User(FieldPermissionModelMixin, AbstractBaseUser, PermissionsMixin, AclMixin):
""" Definition de l'utilisateur de base. """ Definition de l'utilisateur de base.
Champs principaux : name, surnname, pseudo, email, room, password Champs principaux : name, surnname, pseudo, email, room, password
Herite du django BaseUser et du système d'auth django""" Herite du django BaseUser et du système d'auth django"""
@ -667,14 +668,6 @@ class User(FieldPermissionModelMixin, AbstractBaseUser, PermissionsMixin):
num += 1 num += 1
return composed_pseudo(num) return composed_pseudo(num)
def get_instance(userid, *args, **kwargs):
"""Get the User instance with userid.
:param userid: The id
:return: The user
"""
return User.objects.get(pk=userid)
def can_edit(self, user_request, *args, **kwargs): def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit an user object. """Check if an user can edit an user object.
@ -745,29 +738,6 @@ class User(FieldPermissionModelMixin, AbstractBaseUser, PermissionsMixin):
def can_change_groups(user_request, *args, **kwargs): def can_change_groups(user_request, *args, **kwargs):
return user_request.has_perm('users.change_user_groups'), "Droit requis pour éditer les groupes de l'user" return user_request.has_perm('users.change_user_groups'), "Droit requis pour éditer les groupes de l'user"
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete an user object.
:param self: The user who is to be deleted.
:param user_request: The user who requests deletion.
:return: True if user_request has the right 'bureau', and a message.
"""
if user_request.has_perm('users.delete_user'):
return True, None
else:
return False, u"Vous ne pouvez pas supprimer cet utilisateur."
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every user objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
if user_request.has_perm('users.view_user'):
return True, None
else:
return False, u"Vous n'avez pas accès à la liste des utilisateurs."
def can_view(self, user_request, *args, **kwargs): def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view an user object. """Check if an user can view an user object.
@ -790,6 +760,23 @@ class User(FieldPermissionModelMixin, AbstractBaseUser, PermissionsMixin):
else: else:
return False, u"Vous ne pouvez voir un autre utilisateur que vous même" return False, u"Vous ne pouvez voir un autre utilisateur que vous même"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every user objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('users.view_user'), u"Vous n'avez pas accès à la liste des utilisateurs."
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete an user object.
:param self: The user who is to be deleted.
:param user_request: The user who requests deletion.
:return: True if user_request has the right 'bureau', and a message.
"""
return user_request.has_perm('users.delete_user'), u"Vous ne pouvez pas supprimer cet utilisateur."
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(User, self).__init__(*args, **kwargs) super(User, self).__init__(*args, **kwargs)
self.field_permissions = { self.field_permissions = {
@ -812,8 +799,6 @@ class Adherent(User):
null=True null=True
) )
def get_instance(adherentid, *args, **kwargs): def get_instance(adherentid, *args, **kwargs):
"""Try to find an instance of `Adherent` with the given id. """Try to find an instance of `Adherent` with the given id.
@ -922,7 +907,7 @@ def user_post_delete(sender, **kwargs):
user.ldap_del() user.ldap_del()
regen('mailing') regen('mailing')
class ServiceUser(AbstractBaseUser): class ServiceUser(AclMixin, AbstractBaseUser):
""" Classe des users daemons, règle leurs accès au ldap""" """ Classe des users daemons, règle leurs accès au ldap"""
readonly = 'readonly' readonly = 'readonly'
ACCESS = ( ACCESS = (
@ -989,61 +974,6 @@ class ServiceUser(AbstractBaseUser):
)]).values_list('dn', flat=True)) )]).values_list('dn', flat=True))
group.save() group.save()
def get_instance(userid, *args, **kwargs):
return ServiceUser.objects.get(pk=userid)
def can_create(user_request, *args, **kwargs):
"""Check if an user can create a ServiceUser object.
:param user_request: The user who wants to create a user object.
:return: a message and a boolean which is True if the user can create
or if the `options.all_can_create` is set.
"""
return user_request.has_perm('users.add_serviceuser'), (
u"Vous n'avez pas le droit de créer un service user"
)
def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit a ServiceUser object.
:param self: The ServiceUser which is to be edited.
:param user_request: The user who requests to edit self.
:return: a message and a boolean which is True if edition is granted.
"""
return user_request.has_perm('users.change_serviceuser'), (
u"Vous n'avez pas le droit d'éditer les services users"
)
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete a ServiceUser object.
:param self: The ServiceUser who is to be deleted.
:param user_request: The user who requests deletion.
:return: True if user_request has the right 'infra', and a message.
"""
return user_request.has_perm('users.delete_serviceuser'), u"Vous n'avez pas le droit de\
supprimer un service user"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every ServiceUser objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('users.view_serviceuser'), u"Vous n'avez pas le droit de\
voir un service user"
def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view a ServiceUser object.
:param self: The targeted ServiceUser.
:param user_request: The user who ask for viewing the target.
:return: A boolean telling if the acces is granted and an explanation
text
"""
return user_request.has_perm('users.view_serviceuser'), u"Vous n'avez pas le droit de\
voir un service user"
def __str__(self): def __str__(self):
return self.pseudo return self.pseudo
@ -1061,7 +991,7 @@ def service_user_post_delete(sender, **kwargs):
service_user.ldap_del() service_user.ldap_del()
class School(models.Model): class School(AclMixin, models.Model):
""" Etablissement d'enseignement""" """ Etablissement d'enseignement"""
PRETTY_NAME = "Établissements enregistrés" PRETTY_NAME = "Établissements enregistrés"
@ -1072,63 +1002,11 @@ class School(models.Model):
("view_school", "Peut voir un objet school"), ("view_school", "Peut voir un objet school"),
) )
def get_instance(schoolid, *args, **kwargs):
return School.objects.get(pk=schoolid)
def can_create(user_request, *args, **kwargs):
"""Check if an user can create a School object.
:param user_request: The user who wants to create a user object.
:return: a message and a boolean which is True if the user can create.
"""
return user_request.has_perm('users.add_school'), u"Vous n'avez pas le\
droit de créer des écoles"
def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit a School object.
:param self: The School which is to be edited.
:param user_request: The user who requests to edit self.
:return: a message and a boolean which is True if edition is granted.
"""
return user_request.has_perm('users.change_school'), u"Vous n'avez pas le\
droit d'éditer des écoles"
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete a School object.
:param self: The School which is to be deleted.
:param user_request: The user who requests deletion.
:return: True if deletion is granted, and a message.
"""
return user_request.has_perm('users.delete_school'), u"Vous n'avez pas le\
droit de supprimer des écoles"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every School objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('users.view_school'), u"Vous n'avez pas le\
droit de voir les écoles"
def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view a School object.
:param self: The targeted School.
:param user_request: The user who ask for viewing the target.
:return: A boolean telling if the acces is granted and an explanation
text
"""
return user_request.has_perm('users.view_school'), u"Vous n'avez pas le\
droit de voir les écoles"
def __str__(self): def __str__(self):
return self.name return self.name
class ListRight(Group): class ListRight(AclMixin, Group):
""" Ensemble des droits existants. Chaque droit crée un groupe """ Ensemble des droits existants. Chaque droit crée un groupe
ldap synchronisé, avec gid. ldap synchronisé, avec gid.
Permet de gérer facilement les accès serveurs et autres Permet de gérer facilement les accès serveurs et autres
@ -1158,58 +1036,6 @@ class ListRight(Group):
("view_listright", "Peut voir un objet Group/ListRight"), ("view_listright", "Peut voir un objet Group/ListRight"),
) )
def get_instance(listrightid, *args, **kwargs):
return ListRight.objects.get(pk=listrightid)
def can_create(user_request, *args, **kwargs):
"""Check if an user can create a ListRight object.
:param user_request: The user who wants to create a ListRight object.
:return: a message and a boolean which is True if the user can create.
"""
return user_request.has_perm('users.add_listright'), u"Vous n'avez pas le droit\
de créer des groupes de droits"
def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit a ListRight object.
:param self: The object which is to be edited.
:param user_request: The user who requests to edit self.
:return: a message and a boolean which is True if edition is granted.
"""
return user_request.has_perm('users.change_listright'), u"Vous n'avez pas le droit\
d'éditer des groupes de droits"
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete a ListRight object.
:param self: The object which is to be deleted.
:param user_request: The user who requests deletion.
:return: True if deletion is granted, and a message.
"""
return user_request.has_perm('users.delete_listright'), u"Vous n'avez pas le droit\
de supprimer des groupes de droits"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every ListRight objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('users.view_listright'), u"Vous n'avez pas le droit\
de voir les groupes de droits"
def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view a ListRight object.
:param self: The targeted object.
:param user_request: The user who ask for viewing the target.
:return: A boolean telling if the acces is granted and an explanation
text
"""
return user_request.has_perm('users.view_listright'), u"Vous n'avez pas le droit\
de voir les groupes de droits"
def __str__(self): def __str__(self):
return self.name return self.name
@ -1247,7 +1073,7 @@ def listright_post_delete(sender, **kwargs):
right.ldap_del() right.ldap_del()
class ListShell(models.Model): class ListShell(AclMixin, models.Model):
"""Un shell possible. Pas de check si ce shell existe, les """Un shell possible. Pas de check si ce shell existe, les
admin sont des grands""" admin sont des grands"""
PRETTY_NAME = "Liste des shells disponibles" PRETTY_NAME = "Liste des shells disponibles"
@ -1259,67 +1085,15 @@ class ListShell(models.Model):
("view_listshell", "Peut voir un objet shell quelqu'il soit"), ("view_listshell", "Peut voir un objet shell quelqu'il soit"),
) )
def get_instance(shellid, *args, **kwargs):
return ListShell.objects.get(pk=shellid)
def get_pretty_name(self): def get_pretty_name(self):
"""Return the canonical name of the shell""" """Return the canonical name of the shell"""
return self.shell.split("/")[-1] return self.shell.split("/")[-1]
def can_create(user_request, *args, **kwargs):
"""Check if an user can create a ListShell object.
:param user_request: The user who wants to create a user object.
:return: a message and a boolean which is True if the user can create.
"""
return user_request.has_perm('users.add_listshell'), u"Vous n'avez pas le\
droit de créer des shells"
def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit a ListShell object.
:param self: The Shell which is to be edited.
:param user_request: The user who requests to edit self.
:return: a message and a boolean which is True if edition is granted.
"""
return user_request.has_perm('users.change_listshell'), u"Vous n'avez pas le\
droit d'éditer des shells"
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete a ListShell object.
:param self: The Shell which is to be deleted.
:param user_request: The user who requests deletion.
:return: True if deletion is granted, and a message.
"""
return user_request.has_perm('users.delete_listshell'), u"Vous n'avez pas le\
droit de supprimer des shells"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every ListShell objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('users.view_listshell'), u"Vous n'avez pas le\
droit de voir les shells"
def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view a ListShell object.
:param self: The targeted ListShell instance.
:param user_request: The user who ask for viewing the target.
:return: A boolean telling if the acces is granted and an explanation
text
"""
return user_request.has_perm('users.view_listshell'), u"Vous n'avez pas le\
droit de voir les shells"
def __str__(self): def __str__(self):
return self.shell return self.shell
class Ban(models.Model): class Ban(AclMixin, models.Model):
""" Bannissement. Actuellement a un effet tout ou rien. """ Bannissement. Actuellement a un effet tout ou rien.
Gagnerait à être granulaire""" Gagnerait à être granulaire"""
PRETTY_NAME = "Liste des bannissements" PRETTY_NAME = "Liste des bannissements"
@ -1369,44 +1143,6 @@ class Ban(models.Model):
def get_instance(banid, *args, **kwargs): def get_instance(banid, *args, **kwargs):
return Ban.objects.get(pk=banid) return Ban.objects.get(pk=banid)
def can_create(user_request, *args, **kwargs):
"""Check if an user can create a Ban object.
:param user_request: The user who wants to create a Ban object.
:return: a message and a boolean which is True if the user can create.
"""
return user_request.has_perm('users.add_ban'), u"Vous n'avez pas le droit de\
créer des bannissements"
def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit a Ban object.
:param self: The object which is to be edited.
:param user_request: The user who requests to edit self.
:return: a message and a boolean which is True if edition is granted.
"""
return user_request.has_perm('users.change_ban'), u"Vous n'avez pas le droit\
d'éditer des bannissements"
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete a Ban object.
:param self: The object which is to be deleted.
:param user_request: The user who requests deletion.
:return: True if deletion is granted, and a message.
"""
return user_request.has_perm('users.delete_ban'), u"Vous n'avez pas le droit\
de supprimer des bannissements"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every Ban objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('users.view_ban'), u"Vous n'avez pas le droit\
de voir tous les bannissements"
def can_view(self, user_request, *args, **kwargs): def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view a Ban object. """Check if an user can view a Ban object.
@ -1453,7 +1189,7 @@ def ban_post_delete(sender, **kwargs):
regen('mac_ip_list') regen('mac_ip_list')
class Whitelist(models.Model): class Whitelist(AclMixin, models.Model):
"""Accès à titre gracieux. L'utilisateur ne paye pas; se voit """Accès à titre gracieux. L'utilisateur ne paye pas; se voit
accorder un accès internet pour une durée défini. Moins accorder un accès internet pour une durée défini. Moins
fort qu'un ban quel qu'il soit""" fort qu'un ban quel qu'il soit"""
@ -1472,47 +1208,6 @@ class Whitelist(models.Model):
def is_active(self): def is_active(self):
return self.date_end > timezone.now() return self.date_end > timezone.now()
def get_instance(whitelistid, *args, **kwargs):
return Whitelist.objects.get(pk=whitelistid)
def can_create(user_request, *args, **kwargs):
"""Check if an user can create a Whitelist object.
:param user_request: The user who wants to create a Whitelist object.
:return: a message and a boolean which is True if the user can create.
"""
return user_request.has_perm('users.add_whitelist'), u"Vous n'avez pas le\
droit de créer des accès gracieux"
def can_edit(self, user_request, *args, **kwargs):
"""Check if an user can edit a Whitelist object.
:param self: The object which is to be edited.
:param user_request: The user who requests to edit self.
:return: a message and a boolean which is True if edition is granted.
"""
return user_request.has_perm('users.change_whitelist'), u"Vous n'avez pas le\
droit d'éditer des accès gracieux"
def can_delete(self, user_request, *args, **kwargs):
"""Check if an user can delete a Whitelist object.
:param self: The object which is to be deleted.
:param user_request: The user who requests deletion.
:return: True if deletion is granted, and a message.
"""
return user_request.has_perm('users.delete_whitelist'), u"Vous n'avez pas le\
droit de supprimer des accès gracieux"
def can_view_all(user_request, *args, **kwargs):
"""Check if an user can access to the list of every Whitelist objects
:param user_request: The user who wants to view the list.
:return: True if the user can view the list and an explanation message.
"""
return user_request.has_perm('users.view_whitelist'), u"Vous n'avez pas le\
droit de voir les accès gracieux"
def can_view(self, user_request, *args, **kwargs): def can_view(self, user_request, *args, **kwargs):
"""Check if an user can view a Whitelist object. """Check if an user can view a Whitelist object.

View file

@ -22,10 +22,18 @@ with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
{% endcomment %} {% endcomment %}
{% load acl %} {% load acl %}
<div class="table-responsive">
{% if school_list.paginator %}
{% include "pagination.html" with list=school_list %}
{% endif %}
<table class="table table-striped"> <table class="table table-striped">
<thead> <thead>
<tr> <tr>
<th>Etablissement</th> <th>{% include "buttons/sort.html" with prefix='school' col='name' text='Etablissement' %}</th>
<th></th> <th></th>
</tr> </tr>
</thead> </thead>
@ -42,3 +50,8 @@ with this program; if not, write to the Free Software Foundation, Inc.,
{% endfor %} {% endfor %}
</table> </table>
{% if school_list.paginator %}
{% include "pagination.html" with list=school_list %}
{% endif %}
</div>

View file

@ -35,6 +35,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
<a class="btn btn-primary btn-sm" role="button" href="{% url 'users:add-school' %}"><i class="fa fa-plus"></i> Ajouter un établissement</a> <a class="btn btn-primary btn-sm" role="button" href="{% url 'users:add-school' %}"><i class="fa fa-plus"></i> Ajouter un établissement</a>
{% acl_end %} {% acl_end %}
<a class="btn btn-danger btn-sm" role="button" href="{% url 'users:del-school' %}"><i class="fa fa-trash"></i> Supprimer un ou plusieurs établissements</a> <a class="btn btn-danger btn-sm" role="button" href="{% url 'users:del-school' %}"><i class="fa fa-trash"></i> Supprimer un ou plusieurs établissements</a>
<hr>
{% include "users/aff_schools.html" with school_list=school_list %} {% include "users/aff_schools.html" with school_list=school_list %}
<br /> <br />
<br /> <br />

View file

@ -82,12 +82,12 @@ urlpatterns = [
url(r'^del_listright/$', views.del_listright, name='del-listright'), url(r'^del_listright/$', views.del_listright, name='del-listright'),
url(r'^add_shell/$', views.add_shell, name='add-shell'), url(r'^add_shell/$', views.add_shell, name='add-shell'),
url( url(
r'^edit_shell/(?P<shellid>[0-9]+)$', r'^edit_shell/(?P<listshellid>[0-9]+)$',
views.edit_shell, views.edit_shell,
name='edit-shell' name='edit-shell'
), ),
url( url(
r'^del_shell/(?P<shellid>[0-9]+)$', r'^del_shell/(?P<listshellid>[0-9]+)$',
views.del_shell, views.del_shell,
name='del-shell' name='del-shell'
), ),

View file

@ -515,8 +515,8 @@ def add_shell(request):
@login_required @login_required
@can_edit(ListShell) @can_edit(ListShell)
def edit_shell(request, shell_instance, shellid): def edit_shell(request, shell_instance, listshellid):
""" Editer un shell à partir du shellid""" """ Editer un shell à partir du listshellid"""
shell = ShellForm(request.POST or None, instance=shell_instance) shell = ShellForm(request.POST or None, instance=shell_instance)
if shell.is_valid(): if shell.is_valid():
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
@ -532,7 +532,7 @@ def edit_shell(request, shell_instance, shellid):
@login_required @login_required
@can_delete(ListShell) @can_delete(ListShell)
def del_shell(request, shell, shellid): def del_shell(request, shell, listshellid):
"""Destruction d'un shell""" """Destruction d'un shell"""
if request.method == "POST": if request.method == "POST":
with transaction.atomic(), reversion.create_revision(): with transaction.atomic(), reversion.create_revision():
@ -747,6 +747,23 @@ def index_white(request):
def index_school(request): def index_school(request):
""" Affiche l'ensemble des établissement""" """ Affiche l'ensemble des établissement"""
school_list = School.objects.order_by('name') school_list = School.objects.order_by('name')
pagination_number = GeneralOption.get_cached_value('pagination_number')
school_list = SortTable.sort(
school_list,
request.GET.get('col'),
request.GET.get('order'),
SortTable.USERS_INDEX_SCHOOL
)
paginator = Paginator(school_list, pagination_number)
page = request.GET.get('page')
try:
school_list = paginator.page(page)
except PageNotAnInteger:
# If page isn't an integer, deliver first page
school_list = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
school_list = paginator.page(paginator.num_pages)
return render( return render(
request, request,
'users/index_schools.html', 'users/index_schools.html',