From 7c6dfa107373e3274172664328cbe8b5a4614e47 Mon Sep 17 00:00:00 2001 From: Tom Hubrecht Date: Sun, 20 Dec 2020 01:58:38 +0100 Subject: [PATCH] More access control --- elections/mixins.py | 45 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/elections/mixins.py b/elections/mixins.py index e2065b2..ef1f685 100644 --- a/elections/mixins.py +++ b/elections/mixins.py @@ -1,11 +1,46 @@ -# TODO: -class CreatorOnlyMixin: - """Restreint l'accès au créateurice de l'élection""" +from django.utils import timezone +from django.views.generic.detail import SingleObjectMixin + +from .models import Election, Option, Question + + +class RestrictAccessMixin: + """Permet de restreindre l'accès à des élections/questions/options""" + + f_prefixes = {Election: "", Question: "election__", Option: "question__election__"} + + def get_f_prefix(self): + return self.f_prefixes.get(self.model, None) + + def get_filters(self): + return {} def get_queryset(self): + qs = super().get_queryset() + if self.model in self.f_prefixes: + return qs.filter(**self.get_filters()) + # On ne sait pas ce qu'on manipule donc on ne renvoie rien + return qs.none() + + +class CreatorOnlyMixin(RestrictAccessMixin): + """Restreint l'accès au créateurice de l'élection""" + + def get_filters(self): + filters = super().get_filters() # TODO: change the way we collect the user according to the model used - user = self.request.user - return super().get_queryset().filter(created_by=user) + filters[self.get_f_prefix() + "created_by"] = self.request.user + return filters + + +class CreatorOnlyEditMixin(CreatorOnlyMixin, SingleObjectMixin): + """Permet au créateurice de modifier l'élection implicitement""" + + def get_filters(self): + # On ne peut modifier que les élections qui n'ont pas commencé + filters = super().get_filters() + filters[self.get_f_prefix() + "start_date__gt"] = timezone.now() + return filters class AdministratorOnlyMixin: