mirror of
https://git.v0id.ovh/n3wt-innov/n3wt-school.git
synced 2026-04-04 03:31:28 +00:00
feat: Securisation du Backend
This commit is contained in:
@ -2,6 +2,12 @@ from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.backends import ModelBackend
|
||||
from Auth.models import Profile
|
||||
from N3wtSchool import bdd
|
||||
from rest_framework_simplejwt.authentication import JWTAuthentication
|
||||
from rest_framework_simplejwt.exceptions import TokenError, InvalidToken
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("Auth")
|
||||
|
||||
|
||||
class EmailBackend(ModelBackend):
|
||||
def authenticate(self, request, username=None, password=None, **kwargs):
|
||||
@ -18,3 +24,45 @@ class EmailBackend(ModelBackend):
|
||||
except Profile.DoesNotExist:
|
||||
return None
|
||||
|
||||
|
||||
class LoggingJWTAuthentication(JWTAuthentication):
|
||||
"""
|
||||
Surclasse JWTAuthentication pour loguer pourquoi un token Bearer est rejeté.
|
||||
Cela aide à diagnostiquer les 401 sans avoir à ajouter des prints partout.
|
||||
"""
|
||||
|
||||
def authenticate(self, request):
|
||||
header = self.get_header(request)
|
||||
if header is None:
|
||||
logger.debug("JWT: pas de header Authorization dans la requête %s %s",
|
||||
request.method, request.path)
|
||||
return None
|
||||
|
||||
raw_token = self.get_raw_token(header)
|
||||
if raw_token is None:
|
||||
logger.debug("JWT: header Authorization présent mais token vide pour %s %s",
|
||||
request.method, request.path)
|
||||
return None
|
||||
|
||||
try:
|
||||
validated_token = self.get_validated_token(raw_token)
|
||||
except InvalidToken as e:
|
||||
logger.warning(
|
||||
"JWT: token invalide pour %s %s — %s",
|
||||
request.method, request.path, str(e)
|
||||
)
|
||||
raise
|
||||
|
||||
try:
|
||||
user = self.get_user(validated_token)
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"JWT: utilisateur introuvable pour %s %s — %s",
|
||||
request.method, request.path, str(e)
|
||||
)
|
||||
raise
|
||||
|
||||
logger.debug("JWT: authentification réussie user_id=%s pour %s %s",
|
||||
user.pk, request.method, request.path)
|
||||
return user, validated_token
|
||||
|
||||
|
||||
Reference in New Issue
Block a user