From b22b15eef620e14129efd848a56fff26e27a16be Mon Sep 17 00:00:00 2001 From: LEVY-FALK Hugo Date: Tue, 28 Nov 2017 19:41:14 +0100 Subject: [PATCH 001/114] =?UTF-8?q?d=C3=A9corateur=20can=5Fcreate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- users/models.py | 7 +++---- users/views.py | 25 ++++++++++++++++--------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/users/models.py b/users/models.py index 614f15fd..54ec1f67 100644 --- a/users/models.py +++ b/users/models.py @@ -762,17 +762,17 @@ class User(AbstractBaseUser): num += 1 return composed_pseudo(num) - def can_create(user): + def can_create(user, perms=('cableur',)): options, _created = OptionalUser.objects.get_or_create() if options.all_can_create: return True else: - return user.has_perms(('cableur',)) + return user.has_perms(perms) def can_edit(self, user): if self.is_class_club and user.is_class_adherent: return self == user or user.has_perms(('cableur',)) or\ - user.adherent in self.club.administrators.all() + user.adherent in self.club.administrators.all() else: return self == user or user.has_perms(('cableur',)) @@ -846,7 +846,6 @@ def user_post_delete(sender, **kwargs): user.ldap_del() regen('mailing') - class ServiceUser(AbstractBaseUser): """ Classe des users daemons, règle leurs accès au ldap""" readonly = 'readonly' diff --git a/users/views.py b/users/views.py index e0c71157..7b434fbe 100644 --- a/users/views.py +++ b/users/views.py @@ -63,7 +63,7 @@ from users.models import ( Request, ServiceUser, Adherent, - Club + Club, ) from users.forms import ( DelRightForm, @@ -109,17 +109,24 @@ def password_change_action(u_form, user, request, req=False): kwargs={'userid':str(user.id)} )) +def can_create(perms=('cableur',)): + """Décorateur qui vérifie si l'utilisateur peut créer un objet.""" + def decorator(view): + def wrapper(request,*args, **kwargs): + if not request.user.can_create(perms=perms): + messages.error(request, "Vous ne pouvez pas accéder à ce menu") + return redirect(reverse('users:profil', + kwargs={'userid':str(request.user.id)} + )) + return view(request, *args, **kwargs) + return wrapper + return decorator @login_required +@can_create() def new_user(request): """ Vue de création d'un nouvel utilisateur, envoie un mail pour le mot de passe""" - if not User.can_create(request.user): - messages.error(request, "Vous ne pouvez pas accéder à ce menu") - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) user = AdherentForm(request.POST or None) if user.is_valid(): user = user.save(commit=False) @@ -138,7 +145,7 @@ def new_user(request): @login_required -@permission_required('cableur') +@can_create() def new_club(request): """ Vue de création d'un nouveau club, envoie un mail pour le mot de passe""" @@ -303,7 +310,7 @@ def password(request, userid): @login_required -@permission_required('infra') +@can_create(('infra',)) def new_serviceuser(request): """ Vue de création d'un nouvel utilisateur service""" user = ServiceUserForm(request.POST or None) From e837975fa8fdf624a3b1471f17a23e01b3e186b6 Mon Sep 17 00:00:00 2001 From: LEVY-FALK Hugo Date: Tue, 28 Nov 2017 22:54:13 +0100 Subject: [PATCH 002/114] can_create avec choix du model --- users/models.py | 11 +++++++++-- users/views.py | 12 ++++++------ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/users/models.py b/users/models.py index 54ec1f67..1c2a98e0 100644 --- a/users/models.py +++ b/users/models.py @@ -762,12 +762,12 @@ class User(AbstractBaseUser): num += 1 return composed_pseudo(num) - def can_create(user, perms=('cableur',)): + def can_create(user): options, _created = OptionalUser.objects.get_or_create() if options.all_can_create: return True else: - return user.has_perms(perms) + return user.has_perms(('cableur',)) def can_edit(self, user): if self.is_class_club and user.is_class_adherent: @@ -911,6 +911,13 @@ class ServiceUser(AbstractBaseUser): def __str__(self): return self.pseudo + def can_create(user): + options, _created = OptionalUser.objects.get_or_create() + if options.all_can_create: + return True + else: + return user.has_perms(('infra',)) + @receiver(post_save, sender=ServiceUser) def service_user_post_save(sender, **kwargs): diff --git a/users/views.py b/users/views.py index 7b434fbe..0781c374 100644 --- a/users/views.py +++ b/users/views.py @@ -109,11 +109,11 @@ def password_change_action(u_form, user, request, req=False): kwargs={'userid':str(user.id)} )) -def can_create(perms=('cableur',)): - """Décorateur qui vérifie si l'utilisateur peut créer un objet.""" +def can_create(model): + """Decorator to check if an user can create a model. """ def decorator(view): def wrapper(request,*args, **kwargs): - if not request.user.can_create(perms=perms): + if not model.can_create(request.user): messages.error(request, "Vous ne pouvez pas accéder à ce menu") return redirect(reverse('users:profil', kwargs={'userid':str(request.user.id)} @@ -123,7 +123,7 @@ def can_create(perms=('cableur',)): return decorator @login_required -@can_create() +@can_create(Adherent) def new_user(request): """ Vue de création d'un nouvel utilisateur, envoie un mail pour le mot de passe""" @@ -145,7 +145,7 @@ def new_user(request): @login_required -@can_create() +@can_create(Club) def new_club(request): """ Vue de création d'un nouveau club, envoie un mail pour le mot de passe""" @@ -310,7 +310,7 @@ def password(request, userid): @login_required -@can_create(('infra',)) +@can_create(ServiceUser) def new_serviceuser(request): """ Vue de création d'un nouvel utilisateur service""" user = ServiceUserForm(request.POST or None) From d4d3ec31318d0e25c3ab5ae2a99d68b1d03ff011 Mon Sep 17 00:00:00 2001 From: LEVY-FALK Hugo Date: Tue, 28 Nov 2017 23:13:13 +0100 Subject: [PATCH 003/114] Documentation. --- users/views.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/users/views.py b/users/views.py index 0781c374..1ccdd980 100644 --- a/users/views.py +++ b/users/views.py @@ -110,7 +110,11 @@ def password_change_action(u_form, user, request, req=False): )) def can_create(model): - """Decorator to check if an user can create a model. """ + """Decorator to check if an user can create a model. + It assumes that a valid user exists in the request and that the model has a + method can_create(user) which returns true if the user can create this kind + of models. + """ def decorator(view): def wrapper(request,*args, **kwargs): if not model.can_create(request.user): From 4a57a604d9233674ad31c4299f66ef2e9def0403 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Kervella?= Date: Tue, 28 Nov 2017 22:33:47 +0000 Subject: [PATCH 004/114] can_create for Machine --- machines/models.py | 20 ++++++++++++++++ machines/views.py | 53 ++++++++++++++++++++++--------------------- preferences/models.py | 4 ++-- 3 files changed, 49 insertions(+), 28 deletions(-) diff --git a/machines/models.py b/machines/models.py index 9bfb4b55..ff94f3b1 100644 --- a/machines/models.py +++ b/machines/models.py @@ -37,6 +37,9 @@ from django.core.validators import MaxValueValidator from macaddress.fields import MACAddressField +import users.models +import preferences.models + class Machine(models.Model): """ Class définissant une machine, object parent user, objets fils @@ -52,6 +55,23 @@ class Machine(models.Model): ) active = models.BooleanField(default=True) + def can_create(user_request, userid_dest): + try: + user = users.models.User.objects.get(pk=userid_dest) + except users.models.User.DoesNotExist: + return False, u"Utilisateur inexistant" + options, created = preferences.models.OptionalMachine.objects.get_or_create() + max_lambdauser_interfaces = options.max_lambdauser_interfaces + if not user_request.has_perms(('cableur',)): + if user != user_request: + return False, u"Vous ne pouvez pas ajouter une machine à un\ + autre user que vous sans droit" + if user.user_interfaces().count() >= max_lambdauser_interfaces: + return False, u"Vous avez atteint le maximum d'interfaces\ + autorisées que vous pouvez créer vous même (%s) "\ + % max_lambdauser_interfaces + return True, None + def __str__(self): return str(self.user) + ' - ' + str(self.id) + ' - ' + str(self.name) diff --git a/machines/views.py b/machines/views.py index a59e493c..129b586f 100644 --- a/machines/views.py +++ b/machines/views.py @@ -214,30 +214,22 @@ def new_machine(request, userid): """ Fonction de creation d'une machine. Cree l'objet machine, le sous objet interface et l'objet domain à partir de model forms. Trop complexe, devrait être simplifié""" - try: - user = User.objects.get(pk=userid) - except User.DoesNotExist: - messages.error(request, u"Utilisateur inexistant" ) - return redirect(reverse('machines:index')) - options, created = OptionalMachine.objects.get_or_create() - max_lambdauser_interfaces = options.max_lambdauser_interfaces - if not request.user.has_perms(('cableur',)): - if user != request.user: - messages.error( - request, - "Vous ne pouvez pas ajouter une machine à un autre user que vous sans droit") - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - if user.user_interfaces().count() >= max_lambdauser_interfaces: - messages.error(request, "Vous avez atteint le maximum d'interfaces autorisées que vous pouvez créer vous même (%s) " % max_lambdauser_interfaces) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) + + can, reason = Machine.can_create(request.user, userid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + # No need to check if userid exist, already done in can_create + user = User.objects.get(pk=userid) machine = NewMachineForm(request.POST or None) - interface = AddInterfaceForm(request.POST or None, infra=request.user.has_perms(('infra',))) + interface = AddInterfaceForm( + request.POST or None, + infra=request.user.has_perms(('infra',)) + ) domain = DomainForm(request.POST or None, user=user) if machine.is_valid() and interface.is_valid(): new_machine = machine.save(commit=False) @@ -264,9 +256,18 @@ def new_machine(request, userid): return redirect(reverse( 'users:profil', kwargs={'userid':str(user.id)} - )) - i_mbf_param = generate_ipv4_mbf_param( interface, False ) - return form({'machineform': machine, 'interfaceform': interface, 'domainform': domain, 'i_mbf_param': i_mbf_param}, 'machines/machine.html', request) + )) + i_mbf_param = generate_ipv4_mbf_param(interface, False) + return form( + { + 'machineform': machine, + 'interfaceform': interface, + 'domainform': domain, + 'i_mbf_param': i_mbf_param + }, + 'machines/machine.html', + request + ) @login_required def edit_interface(request, interfaceid): diff --git a/preferences/models.py b/preferences/models.py index 2e803b66..3124683d 100644 --- a/preferences/models.py +++ b/preferences/models.py @@ -26,7 +26,7 @@ Reglages généraux, machines, utilisateurs, mail, general pour l'application. from __future__ import unicode_literals from django.db import models -from cotisations.models import Paiement +import cotisations.models class OptionalUser(models.Model): @@ -50,7 +50,7 @@ class OptionalUser(models.Model): def clean(self): """Creation du mode de paiement par solde""" if self.user_solde: - Paiement.objects.get_or_create(moyen="Solde") + cotisations.models.Paiement.objects.get_or_create(moyen="Solde") class OptionalMachine(models.Model): From 90d45b73c40214be50f02e712f543ad64fec1a97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Kervella?= Date: Wed, 29 Nov 2017 00:53:32 +0000 Subject: [PATCH 005/114] Add can_create to machines.models --- machines/models.py | 95 +++++++++++++++++++++++ machines/views.py | 184 ++++++++++++++++++++++++++++++++------------- 2 files changed, 226 insertions(+), 53 deletions(-) diff --git a/machines/models.py b/machines/models.py index ff94f3b1..f7b67b26 100644 --- a/machines/models.py +++ b/machines/models.py @@ -93,6 +93,10 @@ class MachineType(models.Model): machinetype""" return Interface.objects.filter(type=self) + def can_create(user_request): + return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ + de créer un type de machine" + def __str__(self): return self.type @@ -203,6 +207,10 @@ class IpType(models.Model): self.clean() super(IpType, self).save(*args, **kwargs) + def can_create(user_request): + return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ + de créer un type d'ip" + def __str__(self): return self.type @@ -216,6 +224,10 @@ class Vlan(models.Model): name = models.CharField(max_length=256) comment = models.CharField(max_length=256, blank=True) + def can_create(user_request): + return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ + de créer un vlan" + def __str__(self): return self.name @@ -250,6 +262,10 @@ class Nas(models.Model): ) autocapture_mac = models.BooleanField(default=False) + def can_create(user_request): + return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ + de créer un nas" + def __str__(self): return self.name @@ -286,6 +302,10 @@ class SOA(models.Model): help_text='Time To Live' ) + def can_create(user_request): + return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ + de créer un enregistrement SOA" + def __str__(self): return str(self.name) @@ -368,6 +388,10 @@ class Extension(models.Model): entry += "@ IN AAAA " + str(self.origin_v6) return entry + def can_create(user_request): + return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ + de créer une extension" + def __str__(self): return self.name @@ -393,6 +417,10 @@ class Mx(models.Model): fichiers de zones""" return "@ IN MX " + str(self.priority).ljust(3) + " " + str(self.name) + def can_create(user_request): + return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ + de créer un enregistrement MX" + def __str__(self): return str(self.zone) + ' ' + str(self.priority) + ' ' + str(self.name) @@ -409,6 +437,10 @@ class Ns(models.Model): """Renvoie un enregistrement NS complet pour les filezones""" return "@ IN NS " + str(self.ns) + def can_create(user_request): + return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ + de créer un enregistrement NS" + def __str__(self): return str(self.zone) + ' ' + str(self.ns) @@ -421,6 +453,10 @@ class Txt(models.Model): field1 = models.CharField(max_length=255) field2 = models.TextField(max_length=2047) + def can_create(user_request): + return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ + de créer un enregistrement TXT" + def __str__(self): return str(self.zone) + " : " + str(self.field1) + " " +\ str(self.field2) @@ -474,6 +510,10 @@ class Srv(models.Model): help_text="Serveur cible" ) + def can_create(user_request): + return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ + de créer un enregistrement SRV" + def __str__(self): return str(self.service) + ' ' + str(self.protocole) + ' ' +\ str(self.extension) + ' ' + str(self.priority) +\ @@ -591,6 +631,23 @@ class Interface(models.Model): correspondent pas") super(Interface, self).save(*args, **kwargs) + def can_create(user_request, machineid_dest): + try: + machine = Machine.objects.get(pk=machineid_dest) + except Machine.DoesNotExist: + return False, u"Machine inexistante" + if not user_request.has_perms(('cableur',)): + options, created = preferences.models.OptionalMachine.objects.get_or_create() + max_lambdauser_interfaces = options.max_lambdauser_interfaces + if machine.user != user_request: + return False, u"Vous ne pouvez pas ajouter une interface à une\ + machine d'un autre user que vous sans droit" + if machine.user.user_interfaces().count() >= max_lambdauser_interfaces: + return False, u"Vous avez atteint le maximum d'interfaces\ + autorisées que vous pouvez créer vous même (%s) "\ + % max_lambdauser_interfaces + return True, None + def __str__(self): try: domain = self.domain @@ -690,6 +747,27 @@ class Domain(models.Model): self.full_clean() super(Domain, self).save(*args, **kwargs) + def can_create(user_request, interfaceid_dest): + try: + interface = Interface.objects.get(pk=interfaceid_dest) + except Interface.DoesNotExist: + return False, u"Interface inexistante" + if not user_request.has_perms(('cableur',)): + options, created = preferences.models.OptionalMachine.objects.get_or_create() + max_lambdauser_aliases = options.max_lambdauser_aliases + if interface.machine.user != user_request: + return False, u"Vous ne pouvez pas ajouter un alias à une\ + machine d'un autre user que vous sans droit" + if Domain.objects.filter( + cname__in=Domain.objects.filter( + interface_parent__in=interface.machine.user.user_interfaces() + ) + ).count() >= max_lambdauser_aliases: + return False, u"Vous avez atteint le maximum d'alias\ + autorisés que vous pouvez créer vous même (%s) "\ + % max_lambdauser_aliases + return True, None + def __str__(self): return str(self.name) + str(self.extension) @@ -717,6 +795,9 @@ class IpList(models.Model): self.clean() super(IpList, self).save(*args, **kwargs) + def can_create(user_request): + return True, None + def __str__(self): return self.ipv4 @@ -757,6 +838,10 @@ class Service(models.Model): def save(self, *args, **kwargs): super(Service, self).save(*args, **kwargs) + def can_create(user_request): + return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ + de créer un service" + def __str__(self): return str(self.service_type) @@ -797,6 +882,9 @@ class Service_link(models.Model): ) < timezone.now() ) + def can_create(user_request): + return True, None + def __str__(self): return str(self.server) + " " + str(self.service) @@ -810,6 +898,9 @@ class OuverturePortList(models.Model): max_length=255 ) + def can_create(user_request): + return True, None + def __str__(self): return self.name @@ -880,6 +971,10 @@ class OuverturePort(models.Model): default=OUT, ) + def can_create(user_request): + return user_request.has_perms(('bureau',)) , u"Vous n'avez pas le droit\ + d'ouvrir un port" + def __str__(self): if self.begin == self.end: return str(self.begin) diff --git a/machines/views.py b/machines/views.py index 129b586f..3536b008 100644 --- a/machines/views.py +++ b/machines/views.py @@ -221,7 +221,7 @@ def new_machine(request, userid): return redirect(reverse( 'users:profil', kwargs={'userid':str(request.user.id)} - )) + )) # No need to check if userid exist, already done in can_create user = User.objects.get(pk=userid) @@ -344,26 +344,17 @@ def del_machine(request, machineid): @login_required def new_interface(request, machineid): """ Ajoute une interface et son domain associé à une machine existante""" - try: - machine = Machine.objects.get(pk=machineid) - except Machine.DoesNotExist: - messages.error(request, u"Machine inexistante" ) - return redirect(reverse('machines:index')) - if not request.user.has_perms(('cableur',)): - options, created = OptionalMachine.objects.get_or_create() - max_lambdauser_interfaces = options.max_lambdauser_interfaces - if machine.user != request.user: - messages.error(request, "Vous ne pouvez pas ajouter une interface à une machine d'un autre user que vous sans droit") - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - if machine.user.user_interfaces().count() >= max_lambdauser_interfaces: - messages.error(request, "Vous avez atteint le maximum d'interfaces autorisées que vous pouvez créer vous même (%s) " % max_lambdauser_interfaces) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) + + can, reason = Interface.can_create(request.user, machineid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + # No need to check if machineid exist, already done in can_create + machine = Machine.objects.get(pk=machineid) interface_form = AddInterfaceForm(request.POST or None, infra=request.user.has_perms(('infra',))) domain_form = DomainForm(request.POST or None) if interface_form.is_valid(): @@ -419,9 +410,17 @@ def del_interface(request, interfaceid): return form({'objet': interface, 'objet_name': 'interface'}, 'machines/delete.html', request) @login_required -@permission_required('infra') def add_iptype(request): """ Ajoute un range d'ip. Intelligence dans le models, fonction views minimaliste""" + + can, reason = IpType.can_create(request.user) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + iptype = IpTypeForm(request.POST or None) if iptype.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -470,8 +469,16 @@ def del_iptype(request): return form({'iptypeform': iptype}, 'machines/machine.html', request) @login_required -@permission_required('infra') def add_machinetype(request): + + can, reason = MachineType.can_create(request.user) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + machinetype = MachineTypeForm(request.POST or None) if machinetype.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -518,8 +525,16 @@ def del_machinetype(request): return form({'machinetypeform': machinetype}, 'machines/machine.html', request) @login_required -@permission_required('infra') def add_extension(request): + + can, reason = Extension.can_create(request.user) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + extension = ExtensionForm(request.POST or None) if extension.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -566,8 +581,16 @@ def del_extension(request): return form({'extensionform': extension}, 'machines/machine.html', request) @login_required -@permission_required('infra') def add_soa(request): + + can, reason = SOA.can_create(request.user) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + soa = SOAForm(request.POST or None) if soa.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -614,8 +637,16 @@ def del_soa(request): return form({'soaform': soa}, 'machines/machine.html', request) @login_required -@permission_required('infra') def add_mx(request): + + can, reason = Mx.can_create(request.user) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + mx = MxForm(request.POST or None) if mx.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -662,8 +693,16 @@ def del_mx(request): return form({'mxform': mx}, 'machines/machine.html', request) @login_required -@permission_required('infra') def add_ns(request): + + can, reason = Ns.can_create(request.user) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + ns = NsForm(request.POST or None) if ns.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -710,8 +749,16 @@ def del_ns(request): return form({'nsform': ns}, 'machines/machine.html', request) @login_required -@permission_required('infra') def add_txt(request): + + can, reason = Txt.can_create(request.user) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + txt = TxtForm(request.POST or None) if txt.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -758,8 +805,16 @@ def del_txt(request): return form({'txtform': txt}, 'machines/machine.html', request) @login_required -@permission_required('infra') def add_srv(request): + + can, reason = Srv.can_create(request.user) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + srv = SrvForm(request.POST or None) if srv.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -807,26 +862,17 @@ def del_srv(request): @login_required def add_alias(request, interfaceid): - try: - interface = Interface.objects.get(pk=interfaceid) - except Interface.DoesNotExist: - messages.error(request, u"Interface inexistante" ) - return redirect(reverse('machines:index')) - if not request.user.has_perms(('cableur',)): - options, created = OptionalMachine.objects.get_or_create() - max_lambdauser_aliases = options.max_lambdauser_aliases - if interface.machine.user != request.user: - messages.error(request, "Vous ne pouvez pas ajouter un alias à une machine d'un autre user que vous sans droit") - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - if Domain.objects.filter(cname__in=Domain.objects.filter(interface_parent__in=interface.machine.user.user_interfaces())).count() >= max_lambdauser_aliases: - messages.error(request, "Vous avez atteint le maximum d'alias autorisées que vous pouvez créer vous même (%s) " % max_lambdauser_aliases) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) + + can, reason = Domain.can_create(request.user, interfaceid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + # No need to check if interfaceid exist, already done in can_create + interface = Interface.objects.get(pk=interfaceid) alias = AliasForm(request.POST or None, infra=request.user.has_perms(('infra',))) if alias.is_valid(): alias = alias.save(commit=False) @@ -900,8 +946,16 @@ def del_alias(request, interfaceid): @login_required -@permission_required('infra') def add_service(request): + + can, reason = Service.can_create(request.user) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + service = ServiceForm(request.POST or None) if service.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -948,8 +1002,16 @@ def del_service(request): return form({'serviceform': service}, 'machines/machine.html', request) @login_required -@permission_required('infra') def add_vlan(request): + + can, reason = Vlan.can_create(request.user) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + vlan = VlanForm(request.POST or None) if vlan.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -996,8 +1058,16 @@ def del_vlan(request): return form({'vlanform': vlan}, 'machines/machine.html', request) @login_required -@permission_required('infra') def add_nas(request): + + can, reason = Nas.can_create(request.user) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + nas = NasForm(request.POST or None) if nas.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -1301,8 +1371,16 @@ def del_portlist(request, pk): return redirect(reverse('machines:index-portlist')) @login_required -@permission_required('bureau') def add_portlist(request): + + can, reason = OuverturePort.can_create(request.user) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + port_list = EditOuverturePortListForm(request.POST or None) port_formset = modelformset_factory( OuverturePort, From aceb6a9e4af0a3f36c9cae0057604c219e3fc7f5 Mon Sep 17 00:00:00 2001 From: LEVY-FALK Hugo Date: Wed, 29 Nov 2017 11:00:05 +0100 Subject: [PATCH 006/114] =?UTF-8?q?D=C3=A9placement=20du=20d=C3=A9corateur?= =?UTF-8?q?=20can=5Fcreate=20dans=20re2o/utils.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- re2o/utils.py | 19 +++++++++++++++++++ users/views.py | 19 +------------------ 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/re2o/utils.py b/re2o/utils.py index a6e5c851..71f87462 100644 --- a/re2o/utils.py +++ b/re2o/utils.py @@ -39,6 +39,8 @@ from __future__ import unicode_literals from django.utils import timezone from django.db.models import Q +from django.contrib import messages +from django.shortcuts import redirect from cotisations.models import Cotisation, Facture, Paiement, Vente from machines.models import Domain, Interface, Machine @@ -47,6 +49,23 @@ from preferences.models import Service DT_NOW = timezone.now() +def can_create(model): + """Decorator to check if an user can create a model. + It assumes that a valid user exists in the request and that the model has a + method can_create(user) which returns true if the user can create this kind + of models. + """ + def decorator(view): + def wrapper(request,*args, **kwargs): + if not model.can_create(request.user): + messages.error(request, "Vous ne pouvez pas accéder à ce menu") + return redirect(reverse('users:profil', + kwargs={'userid':str(request.user.id)} + )) + return view(request, *args, **kwargs) + return wrapper + return decorator + def all_adherent(search_time=DT_NOW): """ Fonction renvoyant tous les users adherents. Optimisee pour n'est diff --git a/users/views.py b/users/views.py index 1ccdd980..def886d1 100644 --- a/users/views.py +++ b/users/views.py @@ -92,7 +92,7 @@ from machines.models import Machine from preferences.models import OptionalUser, GeneralOption from re2o.views import form -from re2o.utils import all_has_access, SortTable +from re2o.utils import all_has_access, SortTable, can_create def password_change_action(u_form, user, request, req=False): """ Fonction qui effectue le changeemnt de mdp bdd""" @@ -109,23 +109,6 @@ def password_change_action(u_form, user, request, req=False): kwargs={'userid':str(user.id)} )) -def can_create(model): - """Decorator to check if an user can create a model. - It assumes that a valid user exists in the request and that the model has a - method can_create(user) which returns true if the user can create this kind - of models. - """ - def decorator(view): - def wrapper(request,*args, **kwargs): - if not model.can_create(request.user): - messages.error(request, "Vous ne pouvez pas accéder à ce menu") - return redirect(reverse('users:profil', - kwargs={'userid':str(request.user.id)} - )) - return view(request, *args, **kwargs) - return wrapper - return decorator - @login_required @can_create(Adherent) def new_user(request): From 50ea71d8e9460ac5f77fe4fbddd6df5222a88639 Mon Sep 17 00:00:00 2001 From: LEVY-FALK Hugo Date: Thu, 30 Nov 2017 00:28:33 +0100 Subject: [PATCH 007/114] =?UTF-8?q?Premier=20jet=20de=20d=C3=A9corateur=20?= =?UTF-8?q?can=5Fedit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- re2o/utils.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/re2o/utils.py b/re2o/utils.py index 71f87462..c7d61ef6 100644 --- a/re2o/utils.py +++ b/re2o/utils.py @@ -41,6 +41,7 @@ from django.utils import timezone from django.db.models import Q from django.contrib import messages from django.shortcuts import redirect +from django.urls import reverse from cotisations.models import Cotisation, Facture, Paiement, Vente from machines.models import Domain, Interface, Machine @@ -67,6 +68,34 @@ def can_create(model): return decorator +def can_edit(model, *instance_id): + """Decorator to check if an user can edit a model. + It assumes that a valid user exists in the request and that the model has a + method can_create(user) which returns true if the user can create this kind + of models. + """ + def decorator(view): + def wrapper(request, *args, **kwargs): + instances = {} + for i in instance_id: + try: + instances[i] = model.objects.get(pk=i) + except model.DoesNotExist: + messages.error(request, u"Entrée inexistante") + return redirect(reverse('users:index')) + kwargs['instances'] = instances + can = all(model.can_edit(request, instances[i]) for i in instances) + if not can: + messages.error(request, "Vous ne pouvez pas accéder à ce menu") + return redirect(reverse('users:profil', + kwargs={'userid':str(request.user.id)} + )) + return view(request, *args, **kwargs) + return wrapper + return decorator + + + def all_adherent(search_time=DT_NOW): """ Fonction renvoyant tous les users adherents. Optimisee pour n'est qu'une seule requete sql From f37958fdd0905cf0c5d15f23c9570f6737723a30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Kervella?= Date: Wed, 29 Nov 2017 23:45:53 +0000 Subject: [PATCH 008/114] can_edit pour machines.models --- machines/models.py | 145 +++++++++++++++++++++++++++- machines/views.py | 232 +++++++++++++++++++++++++++------------------ 2 files changed, 282 insertions(+), 95 deletions(-) diff --git a/machines/models.py b/machines/models.py index f7b67b26..a7e2cd8f 100644 --- a/machines/models.py +++ b/machines/models.py @@ -72,6 +72,9 @@ class Machine(models.Model): % max_lambdauser_interfaces return True, None + def can_edit(user_request, machineid): + return True, None + def __str__(self): return str(self.user) + ' - ' + str(self.id) + ' - ' + str(self.name) @@ -97,6 +100,15 @@ class MachineType(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un type de machine" + def can_edit(user_request, machinetypeid): + if not user_request.has_perms(('infra',)): + return False, u"Vous n'avez pas le droit d'éditer des types de machine" + try: + machinetype_instance = MachineType.objects.get(pk=machinetypeid) + except MachineType.DoesNotExist: + return False, u"Type de machine inexistant" + return True, None + def __str__(self): return self.type @@ -211,6 +223,15 @@ class IpType(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un type d'ip" + def can_edit(user_request, iptypeid): + if not user_request.has_perms(('infra',)): + return False, u"Vous n'avez pas le droit d'éditer des types d'ip" + try: + iptype_instance = IpType.objects.get(pk=iptypeid) + except IpType.DoesNotExist: + return False, u"Type d'ip inexistant" + return True, None + def __str__(self): return self.type @@ -228,6 +249,15 @@ class Vlan(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un vlan" + def can_edit(user_request, vlanid): + if not user_request.has_perms(('infra',)): + return False, u"Vous n'avez pas le droit d'éditer des vlans" + try: + vlan_instance = Vlan.objects.get(pk=vlanid) + except Vlan.DoesNotExist: + return False, u"Vlan inexistant" + return True, None + def __str__(self): return self.name @@ -266,6 +296,15 @@ class Nas(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un nas" + def can_edit(user_request, nasid): + if not user_request.has_perms(('infra',)): + return False, u"Vous n'avez pas le droit d'éditer des nas" + try: + nas_instance = Nas.objects.get(pk=nasid) + except Nas.DoesNotExist: + return False, u"Nas inexistant" + return True, None + def __str__(self): return self.name @@ -306,6 +345,15 @@ class SOA(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement SOA" + def can_edit(user_request, soaid): + if not user_request.has_perms(('infra',)): + return False, u"Vous n'avez pas le droit d'éditer des enregistrements SOA" + try: + soa_instance = SOA.objects.get(pk=soaid) + except SOA.DoesNotExist: + return False, u"Enregistrement SOA inexistant" + return True, None + def __str__(self): return str(self.name) @@ -392,6 +440,15 @@ class Extension(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer une extension" + def can_edit(user_request, extensionid): + if not user_request.has_perms(('infra',)): + return False, u"Vous n'avez pas le droit d'éditer des extensions" + try: + extension_instance = Extension.objects.get(pk=extensionid) + except Extension.DoesNotExist: + return False, u"Extension inexistante" + return True, None + def __str__(self): return self.name @@ -421,6 +478,15 @@ class Mx(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement MX" + def can_edit(user_request, mxid): + if not user_request.has_perms(('infra',)): + return False, u"Vous n'avez pas le droit d'éditer des enregstrements MX" + try: + mx_instance = Mx.objects.get(pk=mxid) + except Mx.DoesNotExist: + return False, u"Enregistremet MX inexistant" + return True, None + def __str__(self): return str(self.zone) + ' ' + str(self.priority) + ' ' + str(self.name) @@ -441,6 +507,15 @@ class Ns(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement NS" + def can_edit(user_request, nsid): + if not user_request.has_perms(('infra',)): + return False, u"Vous n'avez pas le droit d'éditer des enregistrements NS" + try: + ns_instance = Ns.objects.get(pk=nsid) + except Ns.DoesNotExist: + return False, u"Enregistrement NS inexistant" + return True, None + def __str__(self): return str(self.zone) + ' ' + str(self.ns) @@ -457,6 +532,15 @@ class Txt(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement TXT" + def can_edit(user_request, txtid): + if not user_request.has_perms(('infra',)): + return False, u"Vous n'avez pas le droit d'éditer des enregistrement TXT" + try: + txt_instance = Txt.objects.get(pk=txtid) + except Txt.DoesNotExist: + return False, u"Enregistrement TXT inexistant" + return True, None + def __str__(self): return str(self.zone) + " : " + str(self.field1) + " " +\ str(self.field2) @@ -514,6 +598,15 @@ class Srv(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement SRV" + def can_edit(user_request, srvid): + if not user_request.has_perms(('infra',)): + return False, u"Vous n'avez pas le droit d'éditer des enregistrements SRV" + try: + srv_instance = Srv.objects.get(pk=srvid) + except Srv.DoesNotExist: + return False, u"Enregistrement SRV inexistant" + return True, None + def __str__(self): return str(self.service) + ' ' + str(self.protocole) + ' ' +\ str(self.extension) + ' ' + str(self.priority) +\ @@ -648,6 +741,17 @@ class Interface(models.Model): % max_lambdauser_interfaces return True, None + def can_edit(user_request, interfaceid): + try: + interface = Interface.objects.get(pk=interfaceid) + except Interface.DoesNotExist: + return False, u"Interface inexistante" + if not user_request.has_perms(('infra',)): + if not user_request.has_perms(('cableur',)) and interface.machine.user != user_request: + return False, u"Vous ne pouvez pas éditer une machine\ + d'un autre user que vous sans droit" + return True, None + def __str__(self): try: domain = self.domain @@ -768,6 +872,16 @@ class Domain(models.Model): % max_lambdauser_aliases return True, None + def can_edit(user_request, domainid): + try: + alias_instance = Domain.objects.get(pk=domainid) + except Domain.DoesNotExist: + return False, u"Alias inexistant" + if not user_request.has_perms(('cableur',)) and (alias_instance.cname is None or alias_instance.cname.interface_parent.machine.user != user_request): + return False, u"Vous ne pouvez pas ajouter un alias à une machine\ + d'un autre user que vous sans droit" + return True, None + def __str__(self): return str(self.name) + str(self.extension) @@ -798,6 +912,9 @@ class IpList(models.Model): def can_create(user_request): return True, None + def can_edit(user_request, iplistid): + return True, None + def __str__(self): return self.ipv4 @@ -842,6 +959,15 @@ class Service(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un service" + def can_edit(user_request, serviceid): + if not user_request.has_perms(('infra',)): + return False, u"Vous n'avez pas le droit d'éditer des services" + try: + service_instance = Service.objects.get(pk=serviceid) + except Service.DoesNotExist: + return False, u"Service inexistant" + return True, None + def __str__(self): return str(self.service_type) @@ -885,6 +1011,9 @@ class Service_link(models.Model): def can_create(user_request): return True, None + def can_edit(user_request, service_linkid): + return True, None + def __str__(self): return str(self.server) + " " + str(self.service) @@ -899,6 +1028,16 @@ class OuverturePortList(models.Model): ) def can_create(user_request): + return user_request.has_perms(('bureau',)) , u"Vous n'avez pas le droit\ + d'ouvrir un port" + + def can_edit(user_request, ouvertureportlistpk): + if not user_request.has_perms(('bureau',)): + return False, u"Vous n'avez pas le droit d'éditer des ouvertures de port" + try: + port_list_instance = OuverturePortList.objects.get(pk=ouvertureportlistpk) + except OuverturePortList.DoesNotExist: + return False, u"Ouverture de port inexistante" return True, None def __str__(self): @@ -972,8 +1111,10 @@ class OuverturePort(models.Model): ) def can_create(user_request): - return user_request.has_perms(('bureau',)) , u"Vous n'avez pas le droit\ - d'ouvrir un port" + return True, None + + def can_edit(user_request, ouvertureportid): + return True, None def __str__(self): if self.begin == self.end: diff --git a/machines/views.py b/machines/views.py index 3536b008..44c8d066 100644 --- a/machines/views.py +++ b/machines/views.py @@ -273,18 +273,17 @@ def new_machine(request, userid): def edit_interface(request, interfaceid): """ Edition d'une interface. Distingue suivant les droits les valeurs de interfaces et machines que l'user peut modifier infra permet de modifier le propriétaire""" - try: - interface = Interface.objects.get(pk=interfaceid) - except Interface.DoesNotExist: - messages.error(request, u"Interface inexistante" ) - return redirect(reverse('machines:index')) + + can, reason = Interface.can_edit(request.user, interfaceid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + interface = Interface.objects.get(pk=interfaceid) if not request.user.has_perms(('infra',)): - if not request.user.has_perms(('cableur',)) and interface.machine.user != request.user: - messages.error(request, "Vous ne pouvez pas éditer une machine d'un autre user que vous sans droit") - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) machine_form = BaseEditMachineForm(request.POST or None, instance=interface.machine) interface_form = BaseEditInterfaceForm(request.POST or None, instance=interface, infra=False) else: @@ -432,14 +431,18 @@ def add_iptype(request): return form({'iptypeform': iptype}, 'machines/machine.html', request) @login_required -@permission_required('infra') def edit_iptype(request, iptypeid): """ Edition d'un range. Ne permet pas de le redimensionner pour éviter l'incohérence""" - try: - iptype_instance = IpType.objects.get(pk=iptypeid) - except IpType.DoesNotExist: - messages.error(request, u"Entrée inexistante" ) - return redirect(reverse('machines:index-iptype')) + + can, reason = IpType.can_edit(request.user, iptypeid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + iptype_instance = IpType.objects.get(pk=iptypeid) iptype = EditIpTypeForm(request.POST or None, instance=iptype_instance) if iptype.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -490,13 +493,17 @@ def add_machinetype(request): return form({'machinetypeform': machinetype}, 'machines/machine.html', request) @login_required -@permission_required('infra') def edit_machinetype(request, machinetypeid): - try: - machinetype_instance = MachineType.objects.get(pk=machinetypeid) - except MachineType.DoesNotExist: - messages.error(request, u"Entrée inexistante" ) - return redirect(reverse('machines:index-machinetype')) + + can, reason = MachineType.can_edit(request.user, machinetypeid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + machinetype_instance = MachineType.objects.get(pk=machinetypeid) machinetype = MachineTypeForm(request.POST or None, instance=machinetype_instance) if machinetype.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -546,20 +553,24 @@ def add_extension(request): return form({'extensionform': extension}, 'machines/machine.html', request) @login_required -@permission_required('infra') def edit_extension(request, extensionid): - try: - extension_instance = Extension.objects.get(pk=extensionid) - except Extension.DoesNotExist: - messages.error(request, u"Entrée inexistante" ) - return redirect(reverse('machines:index-extension')) + + can, reason = Extension.can_edit(request.user, extensionid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + extension_instance = Extension.objects.get(pk=extensionid) extension = ExtensionForm(request.POST or None, instance=extension_instance) if extension.is_valid(): with transaction.atomic(), reversion.create_revision(): extension.save() reversion.set_user(request.user) reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in extension.changed_data)) - messages.success(request, "Extension modifiée") + mssages.success(request, "Extension modifiée") return redirect(reverse('machines:index-extension')) return form({'extensionform': extension}, 'machines/machine.html', request) @@ -602,13 +613,17 @@ def add_soa(request): return form({'soaform': soa}, 'machines/machine.html', request) @login_required -@permission_required('infra') def edit_soa(request, soaid): - try: - soa_instance = SOA.objects.get(pk=soaid) - except SOA.DoesNotExist: - messages.error(request, u"Entrée inexistante" ) - return redirect(reverse('machines:index-extension')) + + can, reason = SOA.can_edit(request.user, soaid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + soa_instance = SOA.objects.get(pk=soaid) soa = SOAForm(request.POST or None, instance=soa_instance) if soa.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -658,13 +673,17 @@ def add_mx(request): return form({'mxform': mx}, 'machines/machine.html', request) @login_required -@permission_required('infra') def edit_mx(request, mxid): - try: - mx_instance = Mx.objects.get(pk=mxid) - except Mx.DoesNotExist: - messages.error(request, u"Entrée inexistante" ) - return redirect(reverse('machines:index-extension')) + + can, reason = Mx.can_edit(request.user, mxid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + mx_instance = Mx.objects.get(pk=mxid) mx = MxForm(request.POST or None, instance=mx_instance) if mx.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -714,13 +733,17 @@ def add_ns(request): return form({'nsform': ns}, 'machines/machine.html', request) @login_required -@permission_required('infra') def edit_ns(request, nsid): - try: - ns_instance = Ns.objects.get(pk=nsid) - except Ns.DoesNotExist: - messages.error(request, u"Entrée inexistante" ) - return redirect(reverse('machines:index-extension')) + + can, reason = Ns.can_edit(request.user, nsid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + ns_instance = Ns.objects.get(pk=nsid) ns = NsForm(request.POST or None, instance=ns_instance) if ns.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -770,13 +793,17 @@ def add_txt(request): return form({'txtform': txt}, 'machines/machine.html', request) @login_required -@permission_required('infra') def edit_txt(request, txtid): - try: - txt_instance = Txt.objects.get(pk=txtid) - except Txt.DoesNotExist: - messages.error(request, u"Entrée inexistante" ) - return redirect(reverse('machines:index-extension')) + + can, reason = Txt.can_edit(request.user, txtid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + txt_instance = Txt.objects.get(pk=txtid) txt = TxtForm(request.POST or None, instance=txt_instance) if txt.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -826,13 +853,17 @@ def add_srv(request): return form({'srvform': srv}, 'machines/machine.html', request) @login_required -@permission_required('infra') def edit_srv(request, srvid): - try: - srv_instance = Srv.objects.get(pk=srvid) - except Srv.DoesNotExist: - messages.error(request, u"Entrée inexistante" ) - return redirect(reverse('machines:index-extension')) + + can, reason = Srv.can_edit(request.user, srvid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + srv_instance = Srv.objects.get(pk=srvid) srv = SrvForm(request.POST or None, instance=srv_instance) if srv.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -890,17 +921,16 @@ def add_alias(request, interfaceid): @login_required def edit_alias(request, aliasid): - try: - alias_instance = Domain.objects.get(pk=aliasid) - except Domain.DoesNotExist: - messages.error(request, u"Entrée inexistante" ) - return redirect(reverse('machines:index-extension')) - if not request.user.has_perms(('cableur',)) and alias_instance.cname.interface_parent.machine.user != request.user: - messages.error(request, "Vous ne pouvez pas ajouter un alias à une machine d'un autre user que vous sans droit") + + can, reason = Domain.can_edit(request.user, aliasid) + if not can: + messages.error(request, reason) return redirect(reverse( 'users:profil', kwargs={'userid':str(request.user.id)} - )) + )) + + alias_instance = Domain.objects.get(pk=aliasid) alias = AliasForm(request.POST or None, instance=alias_instance, infra=request.user.has_perms(('infra',))) if alias.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -967,13 +997,17 @@ def add_service(request): return form({'serviceform': service}, 'machines/machine.html', request) @login_required -@permission_required('infra') def edit_service(request, serviceid): - try: - service_instance = Service.objects.get(pk=serviceid) - except Ns.DoesNotExist: - messages.error(request, u"Entrée inexistante" ) - return redirect(reverse('machines:index-extension')) + + can, reason = Service.can_edit(request.user, serviceid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + service_instance = Service.objects.get(pk=serviceid) service = ServiceForm(request.POST or None, instance=service_instance) if service.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -1023,13 +1057,17 @@ def add_vlan(request): return form({'vlanform': vlan}, 'machines/machine.html', request) @login_required -@permission_required('infra') def edit_vlan(request, vlanid): - try: - vlan_instance = Vlan.objects.get(pk=vlanid) - except Vlan.DoesNotExist: - messages.error(request, u"Entrée inexistante" ) - return redirect(reverse('machines:index-vlan')) + + can, reason = Vlan.can_edit(request.user, vlanid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + vlan_instance = Vlan.objects.get(pk=vlanid) vlan = VlanForm(request.POST or None, instance=vlan_instance) if vlan.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -1079,13 +1117,17 @@ def add_nas(request): return form({'nasform': nas}, 'machines/machine.html', request) @login_required -@permission_required('infra') def edit_nas(request, nasid): - try: - nas_instance = Nas.objects.get(pk=nasid) - except Nas.DoesNotExist: - messages.error(request, u"Entrée inexistante" ) - return redirect(reverse('machines:index-nas')) + + can, reason = Nas.can_edit(request.user, nasid) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + nas_instance = Nas.objects.get(pk=nasid) nas = NasForm(request.POST or None, instance=nas_instance) if nas.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -1327,13 +1369,17 @@ def index_portlist(request): return render(request, "machines/index_portlist.html", {'port_list':port_list}) @login_required -@permission_required('bureau') def edit_portlist(request, pk): - try: - port_list_instance = OuverturePortList.objects.get(pk=pk) - except OuverturePortList.DoesNotExist: - messages.error(request, "Liste de ports inexistante") - return redirect(reverse('machines:index-portlist')) + + can, reason = OuverturePortList.can_edit(request.user, pk) + if not can: + messages.error(request, reason) + return redirect(reverse( + 'users:profil', + kwargs={'userid':str(request.user.id)} + )) + + port_list_instance = OuverturePortList.objects.get(pk=pk) port_list = EditOuverturePortListForm(request.POST or None, instance=port_list_instance) port_formset = modelformset_factory( OuverturePort, @@ -1373,7 +1419,7 @@ def del_portlist(request, pk): @login_required def add_portlist(request): - can, reason = OuverturePort.can_create(request.user) + can, reason = OuverturePortList.can_create(request.user) if not can: messages.error(request, reason) return redirect(reverse( From 56e93f4d73bb02b21522eb75c0d70f1b7c9ad3a6 Mon Sep 17 00:00:00 2001 From: LEVY-FALK Hugo Date: Thu, 30 Nov 2017 00:46:23 +0100 Subject: [PATCH 009/114] fix de @can_edit --- re2o/utils.py | 4 ++-- users/views.py | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/re2o/utils.py b/re2o/utils.py index c7d61ef6..fa8753a5 100644 --- a/re2o/utils.py +++ b/re2o/utils.py @@ -79,12 +79,12 @@ def can_edit(model, *instance_id): instances = {} for i in instance_id: try: - instances[i] = model.objects.get(pk=i) + instances[i] = model.objects.get(pk=kwargs[i]) except model.DoesNotExist: messages.error(request, u"Entrée inexistante") return redirect(reverse('users:index')) kwargs['instances'] = instances - can = all(model.can_edit(request, instances[i]) for i in instances) + can = all(model.can_edit(instances[i], request.user) for i in instances) if not can: messages.error(request, "Vous ne pouvez pas accéder à ce menu") return redirect(reverse('users:profil', diff --git a/users/views.py b/users/views.py index def886d1..7fbc78a2 100644 --- a/users/views.py +++ b/users/views.py @@ -92,7 +92,7 @@ from machines.models import Machine from preferences.models import OptionalUser, GeneralOption from re2o.views import form -from re2o.utils import all_has_access, SortTable, can_create +from re2o.utils import all_has_access, SortTable, can_create, can_edit def password_change_action(u_form, user, request, req=False): """ Fonction qui effectue le changeemnt de mdp bdd""" @@ -203,7 +203,8 @@ def select_user_edit_form(request, user): @login_required -def edit_info(request, userid): +@can_edit(User, 'userid') +def edit_info(request, userid, **kwargs): """ Edite un utilisateur à partir de son id, si l'id est différent de request.user, vérifie la possession du droit cableur """ From ec62e4568b6f2549e541f31b1de0b09712e7bd6c Mon Sep 17 00:00:00 2001 From: LEVY-FALK Hugo Date: Thu, 30 Nov 2017 13:42:33 +0100 Subject: [PATCH 010/114] =?UTF-8?q?Pas=20de=20requ=C3=AAte=20directement?= =?UTF-8?q?=20dans=20@can=5Fedit.=20On=20r=C3=A9cup=C3=A8re=20l'instance?= =?UTF-8?q?=20dans=20model.get=5Finstance=20et=20on=20la=20transmet=20?= =?UTF-8?q?=C3=A0=20model.can=5Fedit=20et=20=C3=A0=20la=20vue.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- re2o/utils.py | 24 +++++++++++------------- users/models.py | 3 +++ users/views.py | 28 ++++++++++++++-------------- 3 files changed, 28 insertions(+), 27 deletions(-) diff --git a/re2o/utils.py b/re2o/utils.py index fa8753a5..f350b4d1 100644 --- a/re2o/utils.py +++ b/re2o/utils.py @@ -68,28 +68,26 @@ def can_create(model): return decorator -def can_edit(model, *instance_id): +def can_edit(model): """Decorator to check if an user can edit a model. - It assumes that a valid user exists in the request and that the model has a - method can_create(user) which returns true if the user can create this kind + It tries to get an instance of the model, using + `model.get_instance(*args, **kwargs)` and assumes that the model has a method + `can_create(user)` which returns `true` if the user can create this kind of models. """ def decorator(view): def wrapper(request, *args, **kwargs): - instances = {} - for i in instance_id: - try: - instances[i] = model.objects.get(pk=kwargs[i]) - except model.DoesNotExist: - messages.error(request, u"Entrée inexistante") - return redirect(reverse('users:index')) - kwargs['instances'] = instances - can = all(model.can_edit(instances[i], request.user) for i in instances) - if not can: + try: + instance = model.get_instance(*args, **kwargs) + except model.DoesNotExist: + messages.error(request, u"Entrée inexistante") + return redirect(reverse('users:index')) + if not model.can_edit(instance, request.user): messages.error(request, "Vous ne pouvez pas accéder à ce menu") return redirect(reverse('users:profil', kwargs={'userid':str(request.user.id)} )) + kwargs['instance'] = instance return view(request, *args, **kwargs) return wrapper return decorator diff --git a/users/models.py b/users/models.py index 1c2a98e0..4cdbe715 100644 --- a/users/models.py +++ b/users/models.py @@ -784,6 +784,9 @@ class User(AbstractBaseUser): else: return self == user or user.has_perms(('cableur',)) + def get_instance(userid): + return User.objects.get(pk=userid) + def __str__(self): return self.pseudo diff --git a/users/views.py b/users/views.py index 7fbc78a2..3eeefcc1 100644 --- a/users/views.py +++ b/users/views.py @@ -203,23 +203,23 @@ def select_user_edit_form(request, user): @login_required -@can_edit(User, 'userid') -def edit_info(request, userid, **kwargs): +@can_edit(User) +def edit_info(request, userid, instance): """ Edite un utilisateur à partir de son id, si l'id est différent de request.user, vérifie la possession du droit cableur """ - try: - user = User.objects.get(pk=userid) - except User.DoesNotExist: - messages.error(request, "Utilisateur inexistant") - return redirect(reverse('users:index')) - if not user.can_edit(request.user): - messages.error(request, "Vous ne pouvez pas accéder à ce menu") - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - user = select_user_edit_form(request, user) + # try: + # user = User.objects.get(pk=userid) + # except User.DoesNotExist: + # messages.error(request, "Utilisateur inexistant") + # return redirect(reverse('users:index')) + # if not user.can_edit(request.user): + # messages.error(request, "Vous ne pouvez pas accéder à ce menu") + # return redirect(reverse( + # 'users:profil', + # kwargs={'userid':str(request.user.id)} + # )) + user = select_user_edit_form(request, instance) if user.is_valid(): with transaction.atomic(), reversion.create_revision(): user.save() From cf642bad082de528ea32decb1b1abde3feefab76 Mon Sep 17 00:00:00 2001 From: LEVY-FALK Hugo Date: Thu, 30 Nov 2017 13:52:33 +0100 Subject: [PATCH 011/114] =?UTF-8?q?Redirection=20constante=20vers=20la=20p?= =?UTF-8?q?age=20utilisateur=20en=20cas=20d'erreur=20et=20nommage=20consis?= =?UTF-8?q?tant=20des=20param=C3=A8tres?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- re2o/utils.py | 7 ++++--- users/views.py | 15 ++------------- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/re2o/utils.py b/re2o/utils.py index f350b4d1..91145d2a 100644 --- a/re2o/utils.py +++ b/re2o/utils.py @@ -81,14 +81,15 @@ def can_edit(model): instance = model.get_instance(*args, **kwargs) except model.DoesNotExist: messages.error(request, u"Entrée inexistante") - return redirect(reverse('users:index')) + return redirect(reverse('users:profil', + kwargs={'userid':str(request.user.id)} + )) if not model.can_edit(instance, request.user): messages.error(request, "Vous ne pouvez pas accéder à ce menu") return redirect(reverse('users:profil', kwargs={'userid':str(request.user.id)} )) - kwargs['instance'] = instance - return view(request, *args, **kwargs) + return view(request, instance, *args, **kwargs) return wrapper return decorator diff --git a/users/views.py b/users/views.py index 3eeefcc1..9036ab0a 100644 --- a/users/views.py +++ b/users/views.py @@ -204,22 +204,11 @@ def select_user_edit_form(request, user): @login_required @can_edit(User) -def edit_info(request, userid, instance): +def edit_info(request, user, userid): """ Edite un utilisateur à partir de son id, si l'id est différent de request.user, vérifie la possession du droit cableur """ - # try: - # user = User.objects.get(pk=userid) - # except User.DoesNotExist: - # messages.error(request, "Utilisateur inexistant") - # return redirect(reverse('users:index')) - # if not user.can_edit(request.user): - # messages.error(request, "Vous ne pouvez pas accéder à ce menu") - # return redirect(reverse( - # 'users:profil', - # kwargs={'userid':str(request.user.id)} - # )) - user = select_user_edit_form(request, instance) + user = select_user_edit_form(request, user) if user.is_valid(): with transaction.atomic(), reversion.create_revision(): user.save() From 0d78dcadf5501c1788adf71271cbe1b3b0f0e818 Mon Sep 17 00:00:00 2001 From: LEVY-FALK Hugo Date: Thu, 30 Nov 2017 14:41:31 +0100 Subject: [PATCH 012/114] =?UTF-8?q?@can=5Fcreate=20et=20@can=5Fedit=20sur?= =?UTF-8?q?=20l'ajout=20de=20ban,=20l'ajout=20de=20droit,=20l'=C3=A9dition?= =?UTF-8?q?/cr=C3=A9ation=20de=20service,=20l'=C3=A9dition=20de=20password?= =?UTF-8?q?,=20les=20=C3=A9tats=20et=20l'=C3=A9dition=20d'utilisateurs.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- users/models.py | 11 ++++++++++ users/views.py | 56 ++++++++++++------------------------------------- 2 files changed, 24 insertions(+), 43 deletions(-) diff --git a/users/models.py b/users/models.py index 4cdbe715..9df23486 100644 --- a/users/models.py +++ b/users/models.py @@ -921,6 +921,11 @@ class ServiceUser(AbstractBaseUser): else: return user.has_perms(('infra',)) + def can_edit(instance, user): + return user.has_perms(('infra',)) + + def get_instance(userid): + return ServiceUser.objects.get(pk=userid) @receiver(post_save, sender=ServiceUser) def service_user_post_save(sender, **kwargs): @@ -951,6 +956,9 @@ class Right(models.Model): def __str__(self): return str(self.user) + def can_create(user): + return user.has_perms('bureau') + @receiver(post_save, sender=Right) def right_post_save(sender, **kwargs): @@ -1095,6 +1103,9 @@ class Ban(models.Model): def __str__(self): return str(self.user) + ' ' + str(self.raison) + def can_create(user): + return user.has_perms(('bofh',)) + @receiver(post_save, sender=Ban) def ban_post_save(sender, **kwargs): diff --git a/users/views.py b/users/views.py index 9036ab0a..94b4c2fb 100644 --- a/users/views.py +++ b/users/views.py @@ -226,14 +226,10 @@ def edit_info(request, user, userid): @login_required @permission_required('bureau') -def state(request, userid): +@can_edit(User) +def state(request, user, userid): """ Changer l'etat actif/desactivé/archivé d'un user, need droit bureau """ - try: - user = User.objects.get(pk=userid) - except User.DoesNotExist: - messages.error(request, "Utilisateur inexistant") - return redirect(reverse('users:index')) state = StateForm(request.POST or None, instance=user) if state.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -257,21 +253,11 @@ def state(request, userid): @login_required -def password(request, userid): +@can_edit(User) +def password(request, user, userid): """ Reinitialisation d'un mot de passe à partir de l'userid, pour self par défaut, pour tous sans droit si droit cableur, pour tous si droit bureau """ - try: - user = User.objects.get(pk=userid) - except User.DoesNotExist: - messages.error(request, "Utilisateur inexistant") - return redirect(reverse('users')) - if not user.can_edit(request.user): - messages.error(request, "Vous ne pouvez pas accéder à ce menu") - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) if not request.user.has_perms(('bureau',)) and user != request.user\ and Right.objects.filter(user=user): messages.error(request, "Il faut les droits bureau pour modifier le\ @@ -307,16 +293,9 @@ def new_serviceuser(request): @login_required -@permission_required('infra') -def edit_serviceuser(request, userid): - """ Edite un utilisateur à partir de son id, - si l'id est différent de request.user, - vérifie la possession du droit cableur """ - try: - user = ServiceUser.objects.get(pk=userid) - except ServiceUser.DoesNotExist: - messages.error(request, "Utilisateur inexistant") - return redirect(reverse('users:index')) +@can_edit(ServiceUser) +def edit_serviceuser(request, user, userid): + """ Edit a ServiceUser """ user = EditServiceUserForm(request.POST or None, instance=user) if user.is_valid(): user_object = user.save(commit=False) @@ -356,14 +335,10 @@ def del_serviceuser(request, userid): @login_required -@permission_required('bureau') -def add_right(request, userid): +@can_create(Right) +@can_edit(User) +def add_right(request, user, userid): """ Ajout d'un droit à un user, need droit bureau """ - try: - user = User.objects.get(pk=userid) - except User.DoesNotExist: - messages.error(request, "Utilisateur inexistant") - return redirect(reverse('users:index')) right = RightForm(request.POST or None) if right.is_valid(): right = right.save(commit=False) @@ -405,16 +380,12 @@ def del_right(request): @login_required -@permission_required('bofh') -def add_ban(request, userid): +@can_create(Ban) +@can_edit(User) +def add_ban(request, user, userid): """ Ajouter un banissement, nécessite au moins le droit bofh (a fortiori bureau) Syntaxe : JJ/MM/AAAA , heure optionnelle, prend effet immédiatement""" - try: - user = User.objects.get(pk=userid) - except User.DoesNotExist: - messages.error(request, "Utilisateur inexistant") - return redirect(reverse('users:index')) ban_instance = Ban(user=user) ban = BanForm(request.POST or None, instance=ban_instance) if ban.is_valid(): @@ -434,7 +405,6 @@ def add_ban(request, userid): ) return form({'userform': ban}, 'users/user.html', request) - @login_required @permission_required('bofh') def edit_ban(request, banid): From 7d8b61f0c93f5b094bb8c3dd206c8c9a573d4f23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Kervella?= Date: Thu, 30 Nov 2017 19:02:15 +0000 Subject: [PATCH 013/114] Ajoute un message d'erreur si can_xxx renvoie False --- re2o/utils.py | 10 ++++++---- users/models.py | 43 ++++++++++++++++++++++++++++++------------- 2 files changed, 36 insertions(+), 17 deletions(-) diff --git a/re2o/utils.py b/re2o/utils.py index 91145d2a..866af9df 100644 --- a/re2o/utils.py +++ b/re2o/utils.py @@ -58,8 +58,9 @@ def can_create(model): """ def decorator(view): def wrapper(request,*args, **kwargs): - if not model.can_create(request.user): - messages.error(request, "Vous ne pouvez pas accéder à ce menu") + can, msg = model.can_create(request.user) + if not can: + messages.error(request, msg or "Vous ne pouvez pas accéder à ce menu") return redirect(reverse('users:profil', kwargs={'userid':str(request.user.id)} )) @@ -84,8 +85,9 @@ def can_edit(model): return redirect(reverse('users:profil', kwargs={'userid':str(request.user.id)} )) - if not model.can_edit(instance, request.user): - messages.error(request, "Vous ne pouvez pas accéder à ce menu") + can, msg = model.can_edit(instance, request.user) + if not can: + messages.error(request, msg or "Vous ne pouvez pas accéder à ce menu") return redirect(reverse('users:profil', kwargs={'userid':str(request.user.id)} )) diff --git a/users/models.py b/users/models.py index 9df23486..9606482d 100644 --- a/users/models.py +++ b/users/models.py @@ -765,24 +765,37 @@ class User(AbstractBaseUser): def can_create(user): options, _created = OptionalUser.objects.get_or_create() if options.all_can_create: - return True + return True, None else: - return user.has_perms(('cableur',)) + return user.has_perms(('cableur',)), u"Vous n'avez pas le\ + droit de créer un utilisateur" def can_edit(self, user): if self.is_class_club and user.is_class_adherent: - return self == user or user.has_perms(('cableur',)) or\ - user.adherent in self.club.administrators.all() + if self == user or user.has_perms(('cableur',)) or\ + user.adherent in self.club.administrators.all(): + return True, None + else: + return False, u"Vous n'avez pas le droit d'éditer ce club" else: - return self == user or user.has_perms(('cableur',)) + if self == user or user.has_perms(('cableur',)): + return True, None + else: + return False, u"Vous ne pouvez éditer un autre utilisateur que vous même" def can_view(self, user): if self.is_class_club and user.is_class_adherent: - return self == user or user.has_perms(('cableur',)) or\ + if self == user or user.has_perms(('cableur',)) or\ user.adherent in self.club.administrators.all() or\ - user.adherent in self.club.members.all() + user.adherent in self.club.members.all(): + return True, None + else: + return False, u"Vous n'avez pas le droit de voir ce club" else: - return self == user or user.has_perms(('cableur',)) + if self == user or user.has_perms(('cableur',)): + return True, None + else: + return False, u"Vous ne pouvez voir un autre utilisateur que vous même" def get_instance(userid): return User.objects.get(pk=userid) @@ -917,12 +930,14 @@ class ServiceUser(AbstractBaseUser): def can_create(user): options, _created = OptionalUser.objects.get_or_create() if options.all_can_create: - return True + return True, None else: - return user.has_perms(('infra',)) + return user.has_perms(('infra',)), u"Vous n'avez pas le droit de\ + créer un service user" def can_edit(instance, user): - return user.has_perms(('infra',)) + return user.has_perms(('infra',)), u"Vous n'avez pas le droit d'éditer\ + les services users" def get_instance(userid): return ServiceUser.objects.get(pk=userid) @@ -957,7 +972,8 @@ class Right(models.Model): return str(self.user) def can_create(user): - return user.has_perms('bureau') + return user.has_perms('bureau'), u"Vous n'avez pas le droit de\ + créer des droits" @receiver(post_save, sender=Right) @@ -1104,7 +1120,8 @@ class Ban(models.Model): return str(self.user) + ' ' + str(self.raison) def can_create(user): - return user.has_perms(('bofh',)) + return user.has_perms(('bofh',)), u"Vous n'avez pas le droit de\ + créer des bannissement" @receiver(post_save, sender=Ban) From 3d89386bba3d67b200e6aaa00cefe85ac9405304 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Kervella?= Date: Thu, 30 Nov 2017 19:40:12 +0000 Subject: [PATCH 014/114] =?UTF-8?q?R=C3=A9cup=C3=A8re=20l'instance=20dans?= =?UTF-8?q?=20une=20fonction=20=C3=A0=20part=20pour=20chaque=20mod=C3=A8le?= =?UTF-8?q?=20de=20machines.models?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- machines/models.py | 156 +++++++++++++++++++++++---------------------- 1 file changed, 79 insertions(+), 77 deletions(-) diff --git a/machines/models.py b/machines/models.py index a7e2cd8f..f81fc41f 100644 --- a/machines/models.py +++ b/machines/models.py @@ -55,6 +55,9 @@ class Machine(models.Model): ) active = models.BooleanField(default=True) + def get_instance(machineid): + return Machine.objects.get(pk=machineid) + def can_create(user_request, userid_dest): try: user = users.models.User.objects.get(pk=userid_dest) @@ -72,7 +75,7 @@ class Machine(models.Model): % max_lambdauser_interfaces return True, None - def can_edit(user_request, machineid): + def can_edit(user_request, machine): return True, None def __str__(self): @@ -96,17 +99,16 @@ class MachineType(models.Model): machinetype""" return Interface.objects.filter(type=self) + def get_instance(machinetypeid): + return MachineType.objects.get(pk=machinetypeid) + def can_create(user_request): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un type de machine" - def can_edit(user_request, machinetypeid): + def can_edit(user_request, machinetype): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des types de machine" - try: - machinetype_instance = MachineType.objects.get(pk=machinetypeid) - except MachineType.DoesNotExist: - return False, u"Type de machine inexistant" return True, None def __str__(self): @@ -219,17 +221,16 @@ class IpType(models.Model): self.clean() super(IpType, self).save(*args, **kwargs) + def get_instance(iptyeid): + return IpType.objects.get(pk=iptypeid) + def can_create(user_request): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un type d'ip" - def can_edit(user_request, iptypeid): + def can_edit(user_request, iptype): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des types d'ip" - try: - iptype_instance = IpType.objects.get(pk=iptypeid) - except IpType.DoesNotExist: - return False, u"Type d'ip inexistant" return True, None def __str__(self): @@ -245,17 +246,16 @@ class Vlan(models.Model): name = models.CharField(max_length=256) comment = models.CharField(max_length=256, blank=True) + def get_instance(vlanid): + return Vlan.objects.get(pk=vlanid) + def can_create(user_request): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un vlan" - def can_edit(user_request, vlanid): + def can_edit(user_request, vlan): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des vlans" - try: - vlan_instance = Vlan.objects.get(pk=vlanid) - except Vlan.DoesNotExist: - return False, u"Vlan inexistant" return True, None def __str__(self): @@ -292,17 +292,16 @@ class Nas(models.Model): ) autocapture_mac = models.BooleanField(default=False) + def get_instance(nasid): + return Nas.objects.get(pk=nasid) + def can_create(user_request): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un nas" - def can_edit(user_request, nasid): + def can_edit(user_request, nas): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des nas" - try: - nas_instance = Nas.objects.get(pk=nasid) - except Nas.DoesNotExist: - return False, u"Nas inexistant" return True, None def __str__(self): @@ -341,17 +340,16 @@ class SOA(models.Model): help_text='Time To Live' ) + def get_instance(soaid): + return SOA.objects.get(pk=soaid) + def can_create(user_request): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement SOA" - def can_edit(user_request, soaid): + def can_edit(user_request, soa): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregistrements SOA" - try: - soa_instance = SOA.objects.get(pk=soaid) - except SOA.DoesNotExist: - return False, u"Enregistrement SOA inexistant" return True, None def __str__(self): @@ -436,17 +434,16 @@ class Extension(models.Model): entry += "@ IN AAAA " + str(self.origin_v6) return entry + def get_instance(extensionid): + return Extension.objects.get(pk=extensionid) + def can_create(user_request): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer une extension" - def can_edit(user_request, extensionid): + def can_edit(user_request, extension): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des extensions" - try: - extension_instance = Extension.objects.get(pk=extensionid) - except Extension.DoesNotExist: - return False, u"Extension inexistante" return True, None def __str__(self): @@ -474,17 +471,16 @@ class Mx(models.Model): fichiers de zones""" return "@ IN MX " + str(self.priority).ljust(3) + " " + str(self.name) + def get_instance(mxid): + return Mx.objects.get(pk=mxid) + def can_create(user_request): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement MX" - def can_edit(user_request, mxid): + def can_edit(user_request, mx): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregstrements MX" - try: - mx_instance = Mx.objects.get(pk=mxid) - except Mx.DoesNotExist: - return False, u"Enregistremet MX inexistant" return True, None def __str__(self): @@ -503,17 +499,16 @@ class Ns(models.Model): """Renvoie un enregistrement NS complet pour les filezones""" return "@ IN NS " + str(self.ns) + def get_instance(nsid): + return Ns.objects.get(pk=nsid) + def can_create(user_request): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement NS" - def can_edit(user_request, nsid): + def can_edit(user_request, ns): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregistrements NS" - try: - ns_instance = Ns.objects.get(pk=nsid) - except Ns.DoesNotExist: - return False, u"Enregistrement NS inexistant" return True, None def __str__(self): @@ -528,17 +523,16 @@ class Txt(models.Model): field1 = models.CharField(max_length=255) field2 = models.TextField(max_length=2047) + def get_instance(txtid): + return Txt.objects.get(pk=txtid) + def can_create(user_request): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement TXT" - def can_edit(user_request, txtid): + def can_edit(user_request, txt): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregistrement TXT" - try: - txt_instance = Txt.objects.get(pk=txtid) - except Txt.DoesNotExist: - return False, u"Enregistrement TXT inexistant" return True, None def __str__(self): @@ -594,17 +588,16 @@ class Srv(models.Model): help_text="Serveur cible" ) + def get_instance(srvid): + return Srv.objects.get(pk=srvid) + def can_create(user_request): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement SRV" - def can_edit(user_request, srvid): + def can_edit(user_request, srv): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregistrements SRV" - try: - srv_instance = Srv.objects.get(pk=srvid) - except Srv.DoesNotExist: - return False, u"Enregistrement SRV inexistant" return True, None def __str__(self): @@ -724,6 +717,9 @@ class Interface(models.Model): correspondent pas") super(Interface, self).save(*args, **kwargs) + def get_instance(interfaceid): + return Interface.objects.get(pk=interfaceid) + def can_create(user_request, machineid_dest): try: machine = Machine.objects.get(pk=machineid_dest) @@ -741,13 +737,10 @@ class Interface(models.Model): % max_lambdauser_interfaces return True, None - def can_edit(user_request, interfaceid): - try: - interface = Interface.objects.get(pk=interfaceid) - except Interface.DoesNotExist: - return False, u"Interface inexistante" - if not user_request.has_perms(('infra',)): - if not user_request.has_perms(('cableur',)) and interface.machine.user != user_request: + def can_edit(user_request, interface): + if not user_request.has_perms(('infra',)) and \ + not user_request.has_perms(('cableur',)) and \ + interface.machine.user != user_request: return False, u"Vous ne pouvez pas éditer une machine\ d'un autre user que vous sans droit" return True, None @@ -851,6 +844,9 @@ class Domain(models.Model): self.full_clean() super(Domain, self).save(*args, **kwargs) + def get_instance(domainid): + return Domain.objects.get(pk=domainid) + def can_create(user_request, interfaceid_dest): try: interface = Interface.objects.get(pk=interfaceid_dest) @@ -872,12 +868,11 @@ class Domain(models.Model): % max_lambdauser_aliases return True, None - def can_edit(user_request, domainid): - try: - alias_instance = Domain.objects.get(pk=domainid) - except Domain.DoesNotExist: - return False, u"Alias inexistant" - if not user_request.has_perms(('cableur',)) and (alias_instance.cname is None or alias_instance.cname.interface_parent.machine.user != user_request): + def can_edit(user_request, domain): + if not user_request.has_perms(('cableur',)) and ( + domain.cname is None or \ + domain.cname.interface_parent.machine.user != user_request + ): return False, u"Vous ne pouvez pas ajouter un alias à une machine\ d'un autre user que vous sans droit" return True, None @@ -909,10 +904,13 @@ class IpList(models.Model): self.clean() super(IpList, self).save(*args, **kwargs) + def get_instance(iplistid): + return IpList.objects.get(pk=iplistid) + def can_create(user_request): return True, None - def can_edit(user_request, iplistid): + def can_edit(user_request, iplist): return True, None def __str__(self): @@ -955,17 +953,16 @@ class Service(models.Model): def save(self, *args, **kwargs): super(Service, self).save(*args, **kwargs) + def get_instance(serviceid): + return Service.objects.get(pk=serviceid) + def can_create(user_request): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un service" - def can_edit(user_request, serviceid): + def can_edit(user_request, service): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des services" - try: - service_instance = Service.objects.get(pk=serviceid) - except Service.DoesNotExist: - return False, u"Service inexistant" return True, None def __str__(self): @@ -1008,10 +1005,13 @@ class Service_link(models.Model): ) < timezone.now() ) + def get_instance(servicelinkid): + return ServiceLink.objects.get(pk=servicelinkid) + def can_create(user_request): return True, None - def can_edit(user_request, service_linkid): + def can_edit(user_request, servicelink): return True, None def __str__(self): @@ -1027,17 +1027,16 @@ class OuverturePortList(models.Model): max_length=255 ) + def get_instance(ouvertureportlistid): + return OuverturePortList.objects.get(pk=ouvertureportlistid) + def can_create(user_request): return user_request.has_perms(('bureau',)) , u"Vous n'avez pas le droit\ d'ouvrir un port" - def can_edit(user_request, ouvertureportlistpk): + def can_edit(user_request, ouvertureportlist): if not user_request.has_perms(('bureau',)): return False, u"Vous n'avez pas le droit d'éditer des ouvertures de port" - try: - port_list_instance = OuverturePortList.objects.get(pk=ouvertureportlistpk) - except OuverturePortList.DoesNotExist: - return False, u"Ouverture de port inexistante" return True, None def __str__(self): @@ -1110,10 +1109,13 @@ class OuverturePort(models.Model): default=OUT, ) + def get_instance(ouvertureportid): + return OuverturePort.objects.get(pk=ouvertureportid) + def can_create(user_request): return True, None - def can_edit(user_request, ouvertureportid): + def can_edit(user_request, ouvertureport): return True, None def __str__(self): From 28ef82176f6bb8535b13221dfbc9f94deea7329c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Kervella?= Date: Thu, 30 Nov 2017 20:38:16 +0000 Subject: [PATCH 015/114] Use @can_create and @can_edit on machines.models --- machines/models.py | 56 ++++---- machines/urls.py | 6 +- machines/views.py | 336 ++++++++------------------------------------- re2o/utils.py | 6 +- users/models.py | 4 +- 5 files changed, 95 insertions(+), 313 deletions(-) diff --git a/machines/models.py b/machines/models.py index f81fc41f..1f7b5ca9 100644 --- a/machines/models.py +++ b/machines/models.py @@ -58,9 +58,9 @@ class Machine(models.Model): def get_instance(machineid): return Machine.objects.get(pk=machineid) - def can_create(user_request, userid_dest): + def can_create(user_request, userid): try: - user = users.models.User.objects.get(pk=userid_dest) + user = users.models.User.objects.get(pk=userid) except users.models.User.DoesNotExist: return False, u"Utilisateur inexistant" options, created = preferences.models.OptionalMachine.objects.get_or_create() @@ -75,7 +75,7 @@ class Machine(models.Model): % max_lambdauser_interfaces return True, None - def can_edit(user_request, machine): + def can_edit(self, user_request): return True, None def __str__(self): @@ -106,7 +106,7 @@ class MachineType(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un type de machine" - def can_edit(user_request, machinetype): + def can_edit(self, user_request): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des types de machine" return True, None @@ -221,14 +221,14 @@ class IpType(models.Model): self.clean() super(IpType, self).save(*args, **kwargs) - def get_instance(iptyeid): + def get_instance(iptypeid): return IpType.objects.get(pk=iptypeid) def can_create(user_request): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un type d'ip" - def can_edit(user_request, iptype): + def can_edit(self, user_request): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des types d'ip" return True, None @@ -253,7 +253,7 @@ class Vlan(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un vlan" - def can_edit(user_request, vlan): + def can_edit(self, user_request): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des vlans" return True, None @@ -299,7 +299,7 @@ class Nas(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un nas" - def can_edit(user_request, nas): + def can_edit(self, user_request): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des nas" return True, None @@ -347,7 +347,7 @@ class SOA(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement SOA" - def can_edit(user_request, soa): + def can_edit(self, user_request): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregistrements SOA" return True, None @@ -441,7 +441,7 @@ class Extension(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer une extension" - def can_edit(user_request, extension): + def can_edit(self, user_request): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des extensions" return True, None @@ -478,7 +478,7 @@ class Mx(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement MX" - def can_edit(user_request, mx): + def can_edit(self, user_request): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregstrements MX" return True, None @@ -506,7 +506,7 @@ class Ns(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement NS" - def can_edit(user_request, ns): + def can_edit(self, user_request): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregistrements NS" return True, None @@ -530,7 +530,7 @@ class Txt(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement TXT" - def can_edit(user_request, txt): + def can_edit(self, user_request): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregistrement TXT" return True, None @@ -595,7 +595,7 @@ class Srv(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement SRV" - def can_edit(user_request, srv): + def can_edit(self, user_request): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregistrements SRV" return True, None @@ -720,9 +720,9 @@ class Interface(models.Model): def get_instance(interfaceid): return Interface.objects.get(pk=interfaceid) - def can_create(user_request, machineid_dest): + def can_create(user_request, machineid): try: - machine = Machine.objects.get(pk=machineid_dest) + machine = Machine.objects.get(pk=machineid) except Machine.DoesNotExist: return False, u"Machine inexistante" if not user_request.has_perms(('cableur',)): @@ -737,10 +737,10 @@ class Interface(models.Model): % max_lambdauser_interfaces return True, None - def can_edit(user_request, interface): + def can_edit(self, user_request): if not user_request.has_perms(('infra',)) and \ not user_request.has_perms(('cableur',)) and \ - interface.machine.user != user_request: + self.machine.user != user_request: return False, u"Vous ne pouvez pas éditer une machine\ d'un autre user que vous sans droit" return True, None @@ -847,9 +847,9 @@ class Domain(models.Model): def get_instance(domainid): return Domain.objects.get(pk=domainid) - def can_create(user_request, interfaceid_dest): + def can_create(user_request, interfaceid): try: - interface = Interface.objects.get(pk=interfaceid_dest) + interface = Interface.objects.get(pk=interfaceid) except Interface.DoesNotExist: return False, u"Interface inexistante" if not user_request.has_perms(('cableur',)): @@ -868,10 +868,10 @@ class Domain(models.Model): % max_lambdauser_aliases return True, None - def can_edit(user_request, domain): + def can_edit(self, user_request): if not user_request.has_perms(('cableur',)) and ( - domain.cname is None or \ - domain.cname.interface_parent.machine.user != user_request + self.cname is None or \ + self.cname.interface_parent.machine.user != user_request ): return False, u"Vous ne pouvez pas ajouter un alias à une machine\ d'un autre user que vous sans droit" @@ -910,7 +910,7 @@ class IpList(models.Model): def can_create(user_request): return True, None - def can_edit(user_request, iplist): + def can_edit(self, user_request): return True, None def __str__(self): @@ -960,7 +960,7 @@ class Service(models.Model): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un service" - def can_edit(user_request, service): + def can_edit(self, user_request): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des services" return True, None @@ -1011,7 +1011,7 @@ class Service_link(models.Model): def can_create(user_request): return True, None - def can_edit(user_request, servicelink): + def can_edit(self, user_request): return True, None def __str__(self): @@ -1034,7 +1034,7 @@ class OuverturePortList(models.Model): return user_request.has_perms(('bureau',)) , u"Vous n'avez pas le droit\ d'ouvrir un port" - def can_edit(user_request, ouvertureportlist): + def can_edit(self, user_request): if not user_request.has_perms(('bureau',)): return False, u"Vous n'avez pas le droit d'éditer des ouvertures de port" return True, None @@ -1115,7 +1115,7 @@ class OuverturePort(models.Model): def can_create(user_request): return True, None - def can_edit(user_request, ouvertureport): + def can_edit(self, user_request): return True, None def __str__(self): diff --git a/machines/urls.py b/machines/urls.py index c024cf56..1bece2f6 100644 --- a/machines/urls.py +++ b/machines/urls.py @@ -61,7 +61,7 @@ urlpatterns = [ url(r'^del_srv/$', views.del_srv, name='del-srv'), url(r'^index_extension/$', views.index_extension, name='index-extension'), url(r'^add_alias/(?P[0-9]+)$', views.add_alias, name='add-alias'), - url(r'^edit_alias/(?P[0-9]+)$', views.edit_alias, name='edit-alias'), + url(r'^edit_alias/(?P[0-9]+)$', views.edit_alias, name='edit-alias'), url(r'^del_alias/(?P[0-9]+)$', views.del_alias, name='del-alias'), url(r'^index_alias/(?P[0-9]+)$', views.index_alias, name='index-alias'), url(r'^add_service/$', views.add_service, name='add-service'), @@ -104,8 +104,8 @@ urlpatterns = [ url(r'^rest/service_servers/$', views.service_servers, name='service-servers'), url(r'^rest/ouverture_ports/$', views.ouverture_ports, name='ouverture-ports'), url(r'index_portlist/$', views.index_portlist, name='index-portlist'), - url(r'^edit_portlist/(?P[0-9]+)$', views.edit_portlist, name='edit-portlist'), - url(r'^del_portlist/(?P[0-9]+)$', views.del_portlist, name='del-portlist'), + url(r'^edit_portlist/(?P[0-9]+)$', views.edit_portlist, name='edit-portlist'), + url(r'^del_portlist/(?P[0-9]+)$', views.del_portlist, name='del-portlist'), url(r'^add_portlist/$', views.add_portlist, name='add-portlist'), url(r'^port_config/(?P[0-9]+)$', views.configure_ports, name='port-config'), diff --git a/machines/views.py b/machines/views.py index 44c8d066..32bfc712 100644 --- a/machines/views.py +++ b/machines/views.py @@ -123,7 +123,9 @@ from re2o.utils import ( all_active_assigned_interfaces, all_has_access, filter_active_interfaces, - SortTable + SortTable, + can_create, + can_edit ) from re2o.views import form @@ -210,20 +212,12 @@ def generate_ipv4_mbf_param( form, is_type_tt ): return i_mbf_param @login_required +@can_create(Machine) def new_machine(request, userid): """ Fonction de creation d'une machine. Cree l'objet machine, le sous objet interface et l'objet domain à partir de model forms. Trop complexe, devrait être simplifié""" - can, reason = Machine.can_create(request.user, userid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - # No need to check if userid exist, already done in can_create user = User.objects.get(pk=userid) machine = NewMachineForm(request.POST or None) interface = AddInterfaceForm( @@ -270,26 +264,18 @@ def new_machine(request, userid): ) @login_required -def edit_interface(request, interfaceid): +@can_edit(Interface) +def edit_interface(request, interface_instance, interfaceid): """ Edition d'une interface. Distingue suivant les droits les valeurs de interfaces et machines que l'user peut modifier infra permet de modifier le propriétaire""" - can, reason = Interface.can_edit(request.user, interfaceid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - interface = Interface.objects.get(pk=interfaceid) if not request.user.has_perms(('infra',)): - machine_form = BaseEditMachineForm(request.POST or None, instance=interface.machine) - interface_form = BaseEditInterfaceForm(request.POST or None, instance=interface, infra=False) + machine_form = BaseEditMachineForm(request.POST or None, instance=interface_instance.machine) + interface_form = BaseEditInterfaceForm(request.POST or None, instance=interface_instance, infra=False) else: - machine_form = EditMachineForm(request.POST or None, instance=interface.machine) - interface_form = EditInterfaceForm(request.POST or None, instance=interface) - domain_form = DomainForm(request.POST or None, instance=interface.domain) + machine_form = EditMachineForm(request.POST or None, instance=interface_instance.machine) + interface_form = EditInterfaceForm(request.POST or None, instance=interface_instance) + domain_form = DomainForm(request.POST or None, instance=interface_instance.domain) if machine_form.is_valid() and interface_form.is_valid() and domain_form.is_valid(): new_machine = machine_form.save(commit=False) new_interface = interface_form.save(commit=False) @@ -309,7 +295,7 @@ def edit_interface(request, interfaceid): messages.success(request, "La machine a été modifiée") return redirect(reverse( 'users:profil', - kwargs={'userid':str(interface.machine.user.id)} + kwargs={'userid':str(interface_instance.machine.user.id)} )) i_mbf_param = generate_ipv4_mbf_param( interface_form, False ) return form({'machineform': machine_form, 'interfaceform': interface_form, 'domainform': domain_form, 'i_mbf_param': i_mbf_param}, 'machines/machine.html', request) @@ -341,18 +327,10 @@ def del_machine(request, machineid): return form({'objet': machine, 'objet_name': 'machine'}, 'machines/delete.html', request) @login_required +@can_create(Interface) def new_interface(request, machineid): """ Ajoute une interface et son domain associé à une machine existante""" - can, reason = Interface.can_create(request.user, machineid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - # No need to check if machineid exist, already done in can_create machine = Machine.objects.get(pk=machineid) interface_form = AddInterfaceForm(request.POST or None, infra=request.user.has_perms(('infra',))) domain_form = DomainForm(request.POST or None) @@ -409,17 +387,10 @@ def del_interface(request, interfaceid): return form({'objet': interface, 'objet_name': 'interface'}, 'machines/delete.html', request) @login_required +@can_create(IpType) def add_iptype(request): """ Ajoute un range d'ip. Intelligence dans le models, fonction views minimaliste""" - can, reason = IpType.can_create(request.user) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - iptype = IpTypeForm(request.POST or None) if iptype.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -431,18 +402,10 @@ def add_iptype(request): return form({'iptypeform': iptype}, 'machines/machine.html', request) @login_required -def edit_iptype(request, iptypeid): +@can_edit(IpType) +def edit_iptype(request, iptype_instance, iptypeid): """ Edition d'un range. Ne permet pas de le redimensionner pour éviter l'incohérence""" - - can, reason = IpType.can_edit(request.user, iptypeid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - iptype_instance = IpType.objects.get(pk=iptypeid) iptype = EditIpTypeForm(request.POST or None, instance=iptype_instance) if iptype.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -472,16 +435,9 @@ def del_iptype(request): return form({'iptypeform': iptype}, 'machines/machine.html', request) @login_required +@can_create(MachineType) def add_machinetype(request): - can, reason = MachineType.can_create(request.user) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - machinetype = MachineTypeForm(request.POST or None) if machinetype.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -493,17 +449,9 @@ def add_machinetype(request): return form({'machinetypeform': machinetype}, 'machines/machine.html', request) @login_required -def edit_machinetype(request, machinetypeid): +@can_edit(MachineType) +def edit_machinetype(request, machinetype_instance, machinetypeid): - can, reason = MachineType.can_edit(request.user, machinetypeid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - machinetype_instance = MachineType.objects.get(pk=machinetypeid) machinetype = MachineTypeForm(request.POST or None, instance=machinetype_instance) if machinetype.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -532,16 +480,9 @@ def del_machinetype(request): return form({'machinetypeform': machinetype}, 'machines/machine.html', request) @login_required +@can_create(Extension) def add_extension(request): - can, reason = Extension.can_create(request.user) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - extension = ExtensionForm(request.POST or None) if extension.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -553,17 +494,9 @@ def add_extension(request): return form({'extensionform': extension}, 'machines/machine.html', request) @login_required -def edit_extension(request, extensionid): +@can_edit(Extension) +def edit_extension(request, extension_instance, extensionid): - can, reason = Extension.can_edit(request.user, extensionid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - extension_instance = Extension.objects.get(pk=extensionid) extension = ExtensionForm(request.POST or None, instance=extension_instance) if extension.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -592,16 +525,9 @@ def del_extension(request): return form({'extensionform': extension}, 'machines/machine.html', request) @login_required +@can_create(SOA) def add_soa(request): - can, reason = SOA.can_create(request.user) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - soa = SOAForm(request.POST or None) if soa.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -613,17 +539,9 @@ def add_soa(request): return form({'soaform': soa}, 'machines/machine.html', request) @login_required -def edit_soa(request, soaid): +@can_edit(SOA) +def edit_soa(request, soa_instance, soaid): - can, reason = SOA.can_edit(request.user, soaid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - soa_instance = SOA.objects.get(pk=soaid) soa = SOAForm(request.POST or None, instance=soa_instance) if soa.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -652,16 +570,9 @@ def del_soa(request): return form({'soaform': soa}, 'machines/machine.html', request) @login_required +@can_create(Mx) def add_mx(request): - can, reason = Mx.can_create(request.user) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - mx = MxForm(request.POST or None) if mx.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -673,17 +584,9 @@ def add_mx(request): return form({'mxform': mx}, 'machines/machine.html', request) @login_required -def edit_mx(request, mxid): +@can_edit(Mx) +def edit_mx(request, mx_instance, mxid): - can, reason = Mx.can_edit(request.user, mxid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - mx_instance = Mx.objects.get(pk=mxid) mx = MxForm(request.POST or None, instance=mx_instance) if mx.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -712,16 +615,9 @@ def del_mx(request): return form({'mxform': mx}, 'machines/machine.html', request) @login_required +@can_create(Ns) def add_ns(request): - can, reason = Ns.can_create(request.user) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - ns = NsForm(request.POST or None) if ns.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -733,17 +629,9 @@ def add_ns(request): return form({'nsform': ns}, 'machines/machine.html', request) @login_required -def edit_ns(request, nsid): +@can_edit(Ns) +def edit_ns(request, ns_instance, nsid): - can, reason = Ns.can_edit(request.user, nsid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - ns_instance = Ns.objects.get(pk=nsid) ns = NsForm(request.POST or None, instance=ns_instance) if ns.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -772,16 +660,9 @@ def del_ns(request): return form({'nsform': ns}, 'machines/machine.html', request) @login_required +@can_create(Txt) def add_txt(request): - can, reason = Txt.can_create(request.user) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - txt = TxtForm(request.POST or None) if txt.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -793,17 +674,9 @@ def add_txt(request): return form({'txtform': txt}, 'machines/machine.html', request) @login_required -def edit_txt(request, txtid): +@can_edit(Txt) +def edit_txt(request, txt_instance, txtid): - can, reason = Txt.can_edit(request.user, txtid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - txt_instance = Txt.objects.get(pk=txtid) txt = TxtForm(request.POST or None, instance=txt_instance) if txt.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -832,16 +705,9 @@ def del_txt(request): return form({'txtform': txt}, 'machines/machine.html', request) @login_required +@can_create(Srv) def add_srv(request): - can, reason = Srv.can_create(request.user) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - srv = SrvForm(request.POST or None) if srv.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -853,17 +719,9 @@ def add_srv(request): return form({'srvform': srv}, 'machines/machine.html', request) @login_required -def edit_srv(request, srvid): +@can_edit(Srv) +def edit_srv(request, srv_instance, srvid): - can, reason = Srv.can_edit(request.user, srvid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - srv_instance = Srv.objects.get(pk=srvid) srv = SrvForm(request.POST or None, instance=srv_instance) if srv.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -892,17 +750,9 @@ def del_srv(request): return form({'srvform': srv}, 'machines/machine.html', request) @login_required +@can_create(Domain) def add_alias(request, interfaceid): - can, reason = Domain.can_create(request.user, interfaceid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - # No need to check if interfaceid exist, already done in can_create interface = Interface.objects.get(pk=interfaceid) alias = AliasForm(request.POST or None, infra=request.user.has_perms(('infra',))) if alias.is_valid(): @@ -920,27 +770,19 @@ def add_alias(request, interfaceid): return form({'aliasform': alias}, 'machines/machine.html', request) @login_required -def edit_alias(request, aliasid): +@can_edit(Domain) +def edit_alias(request, domain_instance, domainid): - can, reason = Domain.can_edit(request.user, aliasid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - alias_instance = Domain.objects.get(pk=aliasid) - alias = AliasForm(request.POST or None, instance=alias_instance, infra=request.user.has_perms(('infra',))) + alias = AliasForm(request.POST or None, instance=domain_instance, infra=request.user.has_perms(('infra',))) if alias.is_valid(): with transaction.atomic(), reversion.create_revision(): - alias_instance = alias.save() + domain_instance = alias.save() reversion.set_user(request.user) reversion.set_comment("Champs modifié(s) : %s" % ', '.join(field for field in alias.changed_data)) messages.success(request, "Alias modifié") return redirect(reverse( 'machines:index-alias', - kwargs={'interfaceid':str(alias_instance.cname.interface_parent.id)} + kwargs={'interfaceid':str(domain_instance.cname.interface_parent.id)} )) return form({'aliasform': alias}, 'machines/machine.html', request) @@ -976,16 +818,9 @@ def del_alias(request, interfaceid): @login_required +@can_create(Service) def add_service(request): - can, reason = Service.can_create(request.user) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - service = ServiceForm(request.POST or None) if service.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -997,17 +832,9 @@ def add_service(request): return form({'serviceform': service}, 'machines/machine.html', request) @login_required -def edit_service(request, serviceid): +@can_edit(Service) +def edit_service(request, service_instance, serviceid): - can, reason = Service.can_edit(request.user, serviceid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - service_instance = Service.objects.get(pk=serviceid) service = ServiceForm(request.POST or None, instance=service_instance) if service.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -1036,16 +863,9 @@ def del_service(request): return form({'serviceform': service}, 'machines/machine.html', request) @login_required +@can_create(Vlan) def add_vlan(request): - can, reason = Vlan.can_create(request.user) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - vlan = VlanForm(request.POST or None) if vlan.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -1057,17 +877,9 @@ def add_vlan(request): return form({'vlanform': vlan}, 'machines/machine.html', request) @login_required -def edit_vlan(request, vlanid): +@can_edit(Vlan) +def edit_vlan(request, vlan_instance, vlanid): - can, reason = Vlan.can_edit(request.user, vlanid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - vlan_instance = Vlan.objects.get(pk=vlanid) vlan = VlanForm(request.POST or None, instance=vlan_instance) if vlan.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -1096,16 +908,9 @@ def del_vlan(request): return form({'vlanform': vlan}, 'machines/machine.html', request) @login_required +@can_create(Nas) def add_nas(request): - can, reason = Nas.can_create(request.user) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - nas = NasForm(request.POST or None) if nas.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -1117,17 +922,9 @@ def add_nas(request): return form({'nasform': nas}, 'machines/machine.html', request) @login_required -def edit_nas(request, nasid): +@can_edit(Nas) +def edit_nas(request, nas_instance, nasid): - can, reason = Nas.can_edit(request.user, nasid) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - nas_instance = Nas.objects.get(pk=nasid) nas = NasForm(request.POST or None, instance=nas_instance) if nas.is_valid(): with transaction.atomic(), reversion.create_revision(): @@ -1369,18 +1166,10 @@ def index_portlist(request): return render(request, "machines/index_portlist.html", {'port_list':port_list}) @login_required -def edit_portlist(request, pk): +@can_edit(OuverturePortList) +def edit_portlist(request, ouvertureportlist_instance, ouvertureportlistid): - can, reason = OuverturePortList.can_edit(request.user, pk) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - - port_list_instance = OuverturePortList.objects.get(pk=pk) - port_list = EditOuverturePortListForm(request.POST or None, instance=port_list_instance) + port_list = EditOuverturePortListForm(request.POST or None, instance=ouvertureportlist_instance) port_formset = modelformset_factory( OuverturePort, fields=('begin','end','protocole','io'), @@ -1388,7 +1177,7 @@ def edit_portlist(request, pk): can_delete=True, min_num=1, validate_min=True, - )(request.POST or None, queryset=port_list_instance.ouvertureport_set.all()) + )(request.POST or None, queryset=ouvertureportlist_instance.ouvertureport_set.all()) if port_list.is_valid() and port_formset.is_valid(): pl = port_list.save() instances = port_formset.save(commit=False) @@ -1403,9 +1192,9 @@ def edit_portlist(request, pk): @login_required @permission_required('bureau') -def del_portlist(request, pk): +def del_portlist(request, ouvertureportlistid): try: - port_list_instance = OuverturePortList.objects.get(pk=pk) + port_list_instance = OuverturePortList.objects.get(pk=ouvertureportlistid) except OuverturePortList.DoesNotExist: messages.error(request, "Liste de ports inexistante") return redirect(reverse('machines:index-portlist')) @@ -1417,16 +1206,9 @@ def del_portlist(request, pk): return redirect(reverse('machines:index-portlist')) @login_required +@can_create(OuverturePortList) def add_portlist(request): - can, reason = OuverturePortList.can_create(request.user) - if not can: - messages.error(request, reason) - return redirect(reverse( - 'users:profil', - kwargs={'userid':str(request.user.id)} - )) - port_list = EditOuverturePortListForm(request.POST or None) port_formset = modelformset_factory( OuverturePort, diff --git a/re2o/utils.py b/re2o/utils.py index 866af9df..1f8143cb 100644 --- a/re2o/utils.py +++ b/re2o/utils.py @@ -57,8 +57,8 @@ def can_create(model): of models. """ def decorator(view): - def wrapper(request,*args, **kwargs): - can, msg = model.can_create(request.user) + def wrapper(request, *args, **kwargs): + can, msg = model.can_create(request.user, *args, **kwargs) if not can: messages.error(request, msg or "Vous ne pouvez pas accéder à ce menu") return redirect(reverse('users:profil', @@ -85,7 +85,7 @@ def can_edit(model): return redirect(reverse('users:profil', kwargs={'userid':str(request.user.id)} )) - can, msg = model.can_edit(instance, request.user) + can, msg = instance.can_edit(request.user) if not can: messages.error(request, msg or "Vous ne pouvez pas accéder à ce menu") return redirect(reverse('users:profil', diff --git a/users/models.py b/users/models.py index 9606482d..59d356a9 100644 --- a/users/models.py +++ b/users/models.py @@ -935,7 +935,7 @@ class ServiceUser(AbstractBaseUser): return user.has_perms(('infra',)), u"Vous n'avez pas le droit de\ créer un service user" - def can_edit(instance, user): + def can_edit(self, user): return user.has_perms(('infra',)), u"Vous n'avez pas le droit d'éditer\ les services users" @@ -1119,7 +1119,7 @@ class Ban(models.Model): def __str__(self): return str(self.user) + ' ' + str(self.raison) - def can_create(user): + def can_create(user, userid): return user.has_perms(('bofh',)), u"Vous n'avez pas le droit de\ créer des bannissement" From 3284760fa1486dce130a810be140eb720cc5fc19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Kervella?= Date: Thu, 30 Nov 2017 20:48:32 +0000 Subject: [PATCH 016/114] =?UTF-8?q?Ajoute=20des=20args=20et=20kwargs=20par?= =?UTF-8?q?tout=20pour=20=C3=A9viter=20les=20mauvaises=20surprises?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- machines/models.py | 108 ++++++++++++++++++++++----------------------- users/models.py | 18 ++++---- 2 files changed, 63 insertions(+), 63 deletions(-) diff --git a/machines/models.py b/machines/models.py index 1f7b5ca9..2ba0c652 100644 --- a/machines/models.py +++ b/machines/models.py @@ -55,10 +55,10 @@ class Machine(models.Model): ) active = models.BooleanField(default=True) - def get_instance(machineid): + def get_instance(machineid, *args, **kwargs): return Machine.objects.get(pk=machineid) - def can_create(user_request, userid): + def can_create(user_request, userid, *args, **kwargs): try: user = users.models.User.objects.get(pk=userid) except users.models.User.DoesNotExist: @@ -75,7 +75,7 @@ class Machine(models.Model): % max_lambdauser_interfaces return True, None - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): return True, None def __str__(self): @@ -99,14 +99,14 @@ class MachineType(models.Model): machinetype""" return Interface.objects.filter(type=self) - def get_instance(machinetypeid): + def get_instance(machinetypeid, *args, **kwargs): return MachineType.objects.get(pk=machinetypeid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un type de machine" - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des types de machine" return True, None @@ -221,14 +221,14 @@ class IpType(models.Model): self.clean() super(IpType, self).save(*args, **kwargs) - def get_instance(iptypeid): + def get_instance(iptypeid, *args, **kwargs): return IpType.objects.get(pk=iptypeid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un type d'ip" - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des types d'ip" return True, None @@ -246,14 +246,14 @@ class Vlan(models.Model): name = models.CharField(max_length=256) comment = models.CharField(max_length=256, blank=True) - def get_instance(vlanid): + def get_instance(vlanid, *args, **kwargs): return Vlan.objects.get(pk=vlanid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un vlan" - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des vlans" return True, None @@ -292,14 +292,14 @@ class Nas(models.Model): ) autocapture_mac = models.BooleanField(default=False) - def get_instance(nasid): + def get_instance(nasid, *args, **kwargs): return Nas.objects.get(pk=nasid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un nas" - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des nas" return True, None @@ -340,14 +340,14 @@ class SOA(models.Model): help_text='Time To Live' ) - def get_instance(soaid): + def get_instance(soaid, *args, **kwargs): return SOA.objects.get(pk=soaid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement SOA" - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregistrements SOA" return True, None @@ -434,14 +434,14 @@ class Extension(models.Model): entry += "@ IN AAAA " + str(self.origin_v6) return entry - def get_instance(extensionid): + def get_instance(extensionid, *args, **kwargs): return Extension.objects.get(pk=extensionid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer une extension" - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des extensions" return True, None @@ -471,14 +471,14 @@ class Mx(models.Model): fichiers de zones""" return "@ IN MX " + str(self.priority).ljust(3) + " " + str(self.name) - def get_instance(mxid): + def get_instance(mxid, *args, **kwargs): return Mx.objects.get(pk=mxid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement MX" - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregstrements MX" return True, None @@ -499,14 +499,14 @@ class Ns(models.Model): """Renvoie un enregistrement NS complet pour les filezones""" return "@ IN NS " + str(self.ns) - def get_instance(nsid): + def get_instance(nsid, *args, **kwargs): return Ns.objects.get(pk=nsid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement NS" - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregistrements NS" return True, None @@ -523,14 +523,14 @@ class Txt(models.Model): field1 = models.CharField(max_length=255) field2 = models.TextField(max_length=2047) - def get_instance(txtid): + def get_instance(txtid, *args, **kwargs): return Txt.objects.get(pk=txtid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement TXT" - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregistrement TXT" return True, None @@ -588,14 +588,14 @@ class Srv(models.Model): help_text="Serveur cible" ) - def get_instance(srvid): + def get_instance(srvid, *args, **kwargs): return Srv.objects.get(pk=srvid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un enregistrement SRV" - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des enregistrements SRV" return True, None @@ -717,10 +717,10 @@ class Interface(models.Model): correspondent pas") super(Interface, self).save(*args, **kwargs) - def get_instance(interfaceid): + def get_instance(interfaceid, *args, **kwargs): return Interface.objects.get(pk=interfaceid) - def can_create(user_request, machineid): + def can_create(user_request, machineid, *args, **kwargs): try: machine = Machine.objects.get(pk=machineid) except Machine.DoesNotExist: @@ -737,7 +737,7 @@ class Interface(models.Model): % max_lambdauser_interfaces return True, None - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('infra',)) and \ not user_request.has_perms(('cableur',)) and \ self.machine.user != user_request: @@ -844,10 +844,10 @@ class Domain(models.Model): self.full_clean() super(Domain, self).save(*args, **kwargs) - def get_instance(domainid): + def get_instance(domainid, *args, **kwargs): return Domain.objects.get(pk=domainid) - def can_create(user_request, interfaceid): + def can_create(user_request, interfaceid, *args, **kwargs): try: interface = Interface.objects.get(pk=interfaceid) except Interface.DoesNotExist: @@ -868,7 +868,7 @@ class Domain(models.Model): % max_lambdauser_aliases return True, None - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('cableur',)) and ( self.cname is None or \ self.cname.interface_parent.machine.user != user_request @@ -904,13 +904,13 @@ class IpList(models.Model): self.clean() super(IpList, self).save(*args, **kwargs) - def get_instance(iplistid): + def get_instance(iplistid, *args, **kwargs): return IpList.objects.get(pk=iplistid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return True, None - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): return True, None def __str__(self): @@ -953,14 +953,14 @@ class Service(models.Model): def save(self, *args, **kwargs): super(Service, self).save(*args, **kwargs) - def get_instance(serviceid): + def get_instance(serviceid, *args, **kwargs): return Service.objects.get(pk=serviceid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return user_request.has_perms(('infra',)) , u"Vous n'avez pas le droit\ de créer un service" - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('infra',)): return False, u"Vous n'avez pas le droit d'éditer des services" return True, None @@ -1005,13 +1005,13 @@ class Service_link(models.Model): ) < timezone.now() ) - def get_instance(servicelinkid): + def get_instance(servicelinkid, *args, **kwargs): return ServiceLink.objects.get(pk=servicelinkid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return True, None - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): return True, None def __str__(self): @@ -1027,14 +1027,14 @@ class OuverturePortList(models.Model): max_length=255 ) - def get_instance(ouvertureportlistid): + def get_instance(ouvertureportlistid, *args, **kwargs): return OuverturePortList.objects.get(pk=ouvertureportlistid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return user_request.has_perms(('bureau',)) , u"Vous n'avez pas le droit\ d'ouvrir un port" - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): if not user_request.has_perms(('bureau',)): return False, u"Vous n'avez pas le droit d'éditer des ouvertures de port" return True, None @@ -1109,13 +1109,13 @@ class OuverturePort(models.Model): default=OUT, ) - def get_instance(ouvertureportid): + def get_instance(ouvertureportid, *args, **kwargs): return OuverturePort.objects.get(pk=ouvertureportid) - def can_create(user_request): + def can_create(user_request, *args, **kwargs): return True, None - def can_edit(self, user_request): + def can_edit(self, user_request, *args, **kwargs): return True, None def __str__(self): diff --git a/users/models.py b/users/models.py index 59d356a9..9db01879 100644 --- a/users/models.py +++ b/users/models.py @@ -762,7 +762,7 @@ class User(AbstractBaseUser): num += 1 return composed_pseudo(num) - def can_create(user): + def can_create(user, *args, **kwargs): options, _created = OptionalUser.objects.get_or_create() if options.all_can_create: return True, None @@ -770,7 +770,7 @@ class User(AbstractBaseUser): return user.has_perms(('cableur',)), u"Vous n'avez pas le\ droit de créer un utilisateur" - def can_edit(self, user): + def can_edit(self, user, *args, **kwargs): if self.is_class_club and user.is_class_adherent: if self == user or user.has_perms(('cableur',)) or\ user.adherent in self.club.administrators.all(): @@ -783,7 +783,7 @@ class User(AbstractBaseUser): else: return False, u"Vous ne pouvez éditer un autre utilisateur que vous même" - def can_view(self, user): + def can_view(self, user, *args, **kwargs): if self.is_class_club and user.is_class_adherent: if self == user or user.has_perms(('cableur',)) or\ user.adherent in self.club.administrators.all() or\ @@ -797,7 +797,7 @@ class User(AbstractBaseUser): else: return False, u"Vous ne pouvez voir un autre utilisateur que vous même" - def get_instance(userid): + def get_instance(userid, *args, **kwargs): return User.objects.get(pk=userid) def __str__(self): @@ -927,7 +927,7 @@ class ServiceUser(AbstractBaseUser): def __str__(self): return self.pseudo - def can_create(user): + def can_create(user, *args, **kwargs): options, _created = OptionalUser.objects.get_or_create() if options.all_can_create: return True, None @@ -935,11 +935,11 @@ class ServiceUser(AbstractBaseUser): return user.has_perms(('infra',)), u"Vous n'avez pas le droit de\ créer un service user" - def can_edit(self, user): + def can_edit(self, user, *args, **kwargs): return user.has_perms(('infra',)), u"Vous n'avez pas le droit d'éditer\ les services users" - def get_instance(userid): + def get_instance(userid, *args, **kwargs): return ServiceUser.objects.get(pk=userid) @receiver(post_save, sender=ServiceUser) @@ -971,7 +971,7 @@ class Right(models.Model): def __str__(self): return str(self.user) - def can_create(user): + def can_create(user, *args, **kwargs): return user.has_perms('bureau'), u"Vous n'avez pas le droit de\ créer des droits" @@ -1119,7 +1119,7 @@ class Ban(models.Model): def __str__(self): return str(self.user) + ' ' + str(self.raison) - def can_create(user, userid): + def can_create(user, *args, **kwargs): return user.has_perms(('bofh',)), u"Vous n'avez pas le droit de\ créer des bannissement" From 781085c6433eed2a9d823a06a30e20a6eeefa0cb Mon Sep 17 00:00:00 2001 From: Gabriel Detraz Date: Fri, 1 Dec 2017 02:28:55 +0100 Subject: [PATCH 017/114] Error synthaxe --- users/models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/users/models.py b/users/models.py index 9db01879..0a44cf96 100644 --- a/users/models.py +++ b/users/models.py @@ -972,7 +972,7 @@ class Right(models.Model): return str(self.user) def can_create(user, *args, **kwargs): - return user.has_perms('bureau'), u"Vous n'avez pas le droit de\ + return user.has_perms(('bureau',)), u"Vous n'avez pas le droit de\ créer des droits" From 92944ec8158df296d679728fb287c6bb8d64c4ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Kervella?= Date: Fri, 1 Dec 2017 23:13:52 +0000 Subject: [PATCH 018/114] templatetags for acl that use models not instances --- re2o/templatetags/acl.py | 170 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 re2o/templatetags/acl.py diff --git a/re2o/templatetags/acl.py b/re2o/templatetags/acl.py new file mode 100644 index 00000000..6cb5e4d4 --- /dev/null +++ b/re2o/templatetags/acl.py @@ -0,0 +1,170 @@ +# -*- 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 © 2017 Maël Kervella +# +# 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. + +""" +Set of templatags for using acl in templates: + - can_create + - cannot_create + +**Parameters**: + model_name - The model_name that needs to be checked for the current user + +**Usage**: + {% model %} +