uchill/backend/apps/users/middleware/mentor_student_access.py

67 lines
3.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
Middleware: доступ ментор—студент только после подтверждения приглашения.
Блокирует взаимодействие ментора со студентом, если студент ещё не подтвердил приглашение
(и родитель при необходимости).
Проверка по client_id/student_id в query-параметрах; проверка в теле запроса — в самих view.
"""
from django.http import HttpResponseForbidden
from django.utils.deprecation import MiddlewareMixin
class MentorStudentAccessMiddleware(MiddlewareMixin):
"""
Проверяет, что ментор обращается только к своим подтверждённым студентам.
Если в query-параметрах передан client_id или student_id (user id студента),
проверяется наличие связи mentor в client.mentors (приглашение подтверждено).
"""
EXCLUDED_PATHS_PREFIXES = (
'/api/manage/clients/add_client',
'/api/invitation/',
'/admin/',
'/media/',
'/static/',
'/api/health/',
)
def process_request(self, request):
if not request.path.startswith('/api/'):
return None
for prefix in self.EXCLUDED_PATHS_PREFIXES:
if request.path.startswith(prefix):
return None
if not request.user.is_authenticated or getattr(request.user, 'role', None) != 'mentor':
return None
client_id = None
student_id = None
if request.GET.get('client_id'):
try:
client_id = int(request.GET.get('client_id'))
except (TypeError, ValueError):
pass
if request.GET.get('student_id'):
try:
student_id = int(request.GET.get('student_id'))
except (TypeError, ValueError):
pass
if client_id is None and student_id is None:
return None
from apps.users.models import Client
if client_id is not None:
if not Client.objects.filter(id=client_id, mentors=request.user).exists():
return HttpResponseForbidden(
'Доступ к этому студенту запрещён до подтверждения приглашения.',
content_type='text/plain; charset=utf-8',
)
if student_id is not None:
if not Client.objects.filter(user_id=student_id, mentors=request.user).exists():
return HttpResponseForbidden(
'Доступ к этому студенту запрещён до подтверждения приглашения.',
content_type='text/plain; charset=utf-8',
)
return None