chore: WIP uilisant d'un CSRF global à l'appli

This commit is contained in:
N3WT DE COMPET
2025-02-17 09:26:12 +01:00
parent cccb5efa2c
commit ef1b036dcc
18 changed files with 563 additions and 145 deletions

View File

@ -11,11 +11,8 @@ urlpatterns = [
re_path(r'^subscribe$', SubscribeView.as_view(), name='subscribe'),
re_path(r'^newPassword$', NewPasswordView.as_view(), name='newPassword'),
re_path(r'^resetPassword/(?P<code>[a-zA-Z]+)$', ResetPasswordView.as_view(), name='resetPassword'),
re_path(r'^infoSession$', Auth.views.infoSession, name='infoSession'),
re_path(r'^infoSession$', SessionView.as_view(), name='infoSession'),
re_path(r'^profiles$', ProfileView.as_view(), name="profile"),
re_path(r'^profiles/(?P<id>[0-9]+)$', ProfileSimpleView.as_view(), name="profile"),
# Test SESSION VIEW
re_path(r'^session$', SessionView.as_view(), name="session"),
]

View File

@ -29,6 +29,8 @@ import Subscriptions.util as util
from N3wtSchool import bdd, error
from rest_framework_simplejwt.authentication import JWTAuthentication
@swagger_auto_schema(
method='get',
@ -57,7 +59,7 @@ class SessionView(APIView):
401: openapi.Response('Session invalide')
}
)
def post(self, request):
def get(self, request):
token = request.META.get('HTTP_AUTHORIZATION', '').split('Bearer ')[-1]
try:
@ -146,27 +148,6 @@ class ProfileSimpleView(APIView):
def delete(self, request, id):
return bdd.delete_object(Profile, id)
@swagger_auto_schema(
method='get',
operation_description="Obtenir les informations de session",
responses={200: openapi.Response('Informations de session', schema=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
'cacheSession': openapi.Schema(type=openapi.TYPE_BOOLEAN),
'typeProfil': openapi.Schema(type=openapi.TYPE_STRING),
'username': openapi.Schema(type=openapi.TYPE_STRING)
}
))}
)
@api_view(['GET'])
def infoSession(request):
profilCache = cache.get('session_cache')
if profilCache:
return JsonResponse({"cacheSession":True,"typeProfil":profilCache.droit, "username":profilCache.email}, safe=False)
else:
return JsonResponse({"cacheSession":False,"typeProfil":Profile.Droits.PROFIL_UNDEFINED, "username":""}, safe=False)
@method_decorator(csrf_protect, name='dispatch')
@method_decorator(ensure_csrf_cookie, name='dispatch')
class LoginView(APIView):
@ -195,7 +176,7 @@ class LoginView(APIView):
def post(self, request):
data=JSONParser().parse(request)
validatorAuthentication = validator.ValidatorAuthentication(data=data)
retour = error.returnMessage[error.WRONGid]
retour = error.returnMessage[error.WRONG_ID]
validationOk, errorFields = validatorAuthentication.validate()
user = None
if validationOk:
@ -212,15 +193,8 @@ class LoginView(APIView):
retour = ''
else:
retour = error.returnMessage[error.PROFIL_INACTIVE]
# Génération du token JWT
# jwt_token = jwt.encode({
# 'id': user.id,
# 'email': user.email,
# 'role': "admin"
# }, settings.SECRET_KEY, algorithm='HS256')
else:
retour = error.returnMessage[error.WRONGid]
retour = error.returnMessage[error.WRONG_ID]
return JsonResponse({

View File

@ -13,6 +13,7 @@ https://docs.djangoproject.com/en/5.0/ref/settings/
from pathlib import Path
import json
import os
from datetime import timedelta
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
@ -53,6 +54,7 @@ INSTALLED_APPS = [
'django_celery_beat',
'N3wtSchool',
'drf_yasg',
'rest_framework_simplejwt'
]
MIDDLEWARE = [
@ -250,10 +252,19 @@ CORS_ALLOW_ALL_HEADERS = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
os.getenv('CORS_ALLOWED_ORIGINS', 'http://localhost:3000')
'http://localhost:3000'
]
CSRF_TRUSTED_ORIGINS = os.getenv('CSRF_TRUSTED_ORIGINS', 'http://localhost:3000,http://localhost:8080').split(',')
CSRF_TRUSTED_ORIGINS = [
'http://localhost:3000',
'http://localhost:8080'
]
# CORS_ALLOWED_ORIGINS = [
# os.getenv('CORS_ALLOWED_ORIGINS', 'http://localhost:3000')
# ]
# CSRF_TRUSTED_ORIGINS = os.getenv('CSRF_TRUSTED_ORIGINS', 'http://localhost:3000,http://localhost:8080').split(',')
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_SECURE = False
@ -289,7 +300,10 @@ NB_MAX_PAGE = 100
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'Subscriptions.pagination.CustomPagination',
'PAGE_SIZE': NB_RESULT_PER_PAGE
'PAGE_SIZE': NB_RESULT_PER_PAGE,
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
CELERY_BROKER_URL = 'redis://redis:6379/0'
@ -308,3 +322,18 @@ REDIS_DB = 0
REDIS_PASSWORD = None
SECRET_KEY = 'QWQ8bYlCz1NpQ9G0vR5kxMnvWszfH2y3'
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': True,
'ALGORITHM': 'HS256',
'SIGNING_KEY': SECRET_KEY,
'VERIFYING_KEY': None,
'AUTH_HEADER_TYPES': ('Bearer',),
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
}

Binary file not shown.