feat: Securisation du Backend

This commit is contained in:
Luc SORIGNET
2026-02-27 10:45:36 +01:00
parent 2fef6d61a4
commit fa843097ba
55 changed files with 2898 additions and 910 deletions

View File

@ -4,6 +4,7 @@ from django.utils.decorators import method_decorator
from rest_framework.parsers import JSONParser, MultiPartParser, FormParser
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, BasePermission
from .models import Establishment
from .serializers import EstablishmentSerializer
from N3wtSchool.bdd import delete_object, getAllObjects, getObject
@ -15,9 +16,29 @@ import N3wtSchool.mailManager as mailer
import os
from N3wtSchool import settings
@method_decorator(csrf_protect, name='dispatch')
@method_decorator(ensure_csrf_cookie, name='dispatch')
class IsWebhookApiKey(BasePermission):
def has_permission(self, request, view):
api_key = settings.WEBHOOK_API_KEY
if not api_key:
return False
return request.headers.get('X-API-Key') == api_key
class IsAuthenticatedOrWebhookApiKey(BasePermission):
def has_permission(self, request, view):
if request.user and request.user.is_authenticated:
return True
return IsWebhookApiKey().has_permission(request, view)
class EstablishmentListCreateView(APIView):
def get_permissions(self):
if self.request.method == 'POST':
return [IsAuthenticatedOrWebhookApiKey()]
return [IsAuthenticated()]
def get(self, request):
establishments = getAllObjects(Establishment)
establishments_serializer = EstablishmentSerializer(establishments, many=True)
@ -44,6 +65,7 @@ class EstablishmentListCreateView(APIView):
@method_decorator(csrf_protect, name='dispatch')
@method_decorator(ensure_csrf_cookie, name='dispatch')
class EstablishmentDetailView(APIView):
permission_classes = [IsAuthenticated]
parser_classes = [MultiPartParser, FormParser]
def get(self, request, id=None):
@ -87,7 +109,9 @@ def create_establishment_with_directeur(establishment_data):
directeur_email = directeur_data.get("email")
last_name = directeur_data.get("last_name", "")
first_name = directeur_data.get("first_name", "")
password = directeur_data.get("password", "Provisoire01!")
password = directeur_data.get("password")
if not password:
raise ValueError("Le champ 'directeur.password' est obligatoire pour créer un établissement.")
# Création ou récupération du profil utilisateur
profile, created = Profile.objects.get_or_create(