Codebase hardening: 102 fixes across 35+ files
Deep audit identified 106 findings; 102 fixed, 4 deferred. Covers 8 areas: - Settings & deploy: env-gated DEBUG/SECRET_KEY, HTTPS headers, gunicorn, celery worker - Auth (registered_user): password write_only, request.data fixes, transaction safety, proper HTTP status codes - Workout app: IDOR protection, get_object_or_404, prefetch_related N+1 fixes, transaction.atomic - Video/scripts: path traversal sanitization, HLS trigger guard, auth on cache wipe - Models (exercise/equipment/muscle/superset): null-safe __str__, stable IDs, prefetch support - Generator views: helper for registered_user lookup, logger.exception, bulk_update, transaction wrapping - Generator core (rules/selector/generator): push-pull ratio, type affinity normalization, modality checks, side-pair exact match, word-boundary regex, equipment cache clearing - Generator services (plan_builder/analyzer/normalizer): transaction.atomic, muscle cache, bulk_update, glutes classification fix Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -17,14 +17,26 @@ class Video(models.Model):
|
||||
gender = models.PositiveSmallIntegerField(
|
||||
choices=VIDEO_GENDER
|
||||
)
|
||||
|
||||
|
||||
def __str__(self):
|
||||
return str(self.video_file)
|
||||
|
||||
def save(self, **kwargs):
|
||||
super(Video, self).save(**kwargs)
|
||||
filename = self.video_file.name
|
||||
create_hls_tasks.delay(filename)
|
||||
def save(self, *args, **kwargs):
|
||||
is_new = self.pk is None
|
||||
if self.pk:
|
||||
try:
|
||||
old = type(self).objects.get(pk=self.pk)
|
||||
video_changed = old.video_file != self.video_file
|
||||
except type(self).DoesNotExist:
|
||||
video_changed = True
|
||||
else:
|
||||
video_changed = bool(self.video_file)
|
||||
|
||||
super(Video, self).save(*args, **kwargs)
|
||||
|
||||
if self.video_file and (is_new or video_changed):
|
||||
filename = self.video_file.name
|
||||
create_hls_tasks.delay(filename)
|
||||
|
||||
|
||||
|
||||
@@ -33,10 +45,22 @@ class ExerciseVideo(models.Model):
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
video_file = models.FileField(upload_to='videos/', null=True, verbose_name="")
|
||||
|
||||
def save(self, **kwargs):
|
||||
super(ExerciseVideo, self).save(**kwargs)
|
||||
filename = self.video_file.name
|
||||
create_hls_tasks.delay(filename)
|
||||
def save(self, *args, **kwargs):
|
||||
is_new = self.pk is None
|
||||
if self.pk:
|
||||
try:
|
||||
old = type(self).objects.get(pk=self.pk)
|
||||
video_changed = old.video_file != self.video_file
|
||||
except type(self).DoesNotExist:
|
||||
video_changed = True
|
||||
else:
|
||||
video_changed = bool(self.video_file)
|
||||
|
||||
super(ExerciseVideo, self).save(*args, **kwargs)
|
||||
|
||||
if self.video_file and (is_new or video_changed):
|
||||
filename = self.video_file.name
|
||||
create_hls_tasks.delay(filename)
|
||||
|
||||
@receiver(pre_delete, sender=ExerciseVideo)
|
||||
def delete_exercise_video(sender, instance, using, **kwargs):
|
||||
|
||||
@@ -9,5 +9,7 @@ class VideoSerializer(serializers.ModelSerializer):
|
||||
model = Video
|
||||
fields = ('video_file', 'gender_value',)
|
||||
|
||||
def get_video_file(self, obj):
|
||||
return '/media/' + obj.video_file.name + '_720p.m3u8'
|
||||
def get_video_file(self, obj):
|
||||
if not obj.video_file:
|
||||
return None
|
||||
return '/media/' + obj.video_file.name + '_720p.m3u8'
|
||||
|
||||
@@ -7,7 +7,8 @@ from django.core.files.storage import default_storage
|
||||
|
||||
@shared_task()
|
||||
def create_hls_tasks(filename):
|
||||
end_location = str(settings.MEDIA_ROOT) + "/" + str(filename) +'.m3u8'
|
||||
base_name = os.path.splitext(str(filename))[0]
|
||||
end_location = str(settings.MEDIA_ROOT) + "/" + base_name + '.m3u8'
|
||||
if not default_storage.exists(end_location):
|
||||
media_location = str(settings.MEDIA_ROOT) + "/" + str(filename)
|
||||
video = ffmpeg_streaming.input(media_location)
|
||||
@@ -21,6 +22,6 @@ def create_hls_tasks(filename):
|
||||
# first_video.get('height', "Unknown")
|
||||
# )
|
||||
# print(f"Dimensions: {dimensions[0]}x{dimensions[1]}") # f-string
|
||||
|
||||
|
||||
hls.auto_generate_representations()
|
||||
hls.output(end_location)
|
||||
hls.output(end_location)
|
||||
|
||||
@@ -3,7 +3,6 @@ from .serializers import *
|
||||
|
||||
from django.shortcuts import render
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.response import Response
|
||||
from rest_framework import status
|
||||
from django.contrib.auth.models import User
|
||||
@@ -48,17 +47,33 @@ def nsfw_videos(request):
|
||||
@permission_classes([IsAuthenticated])
|
||||
def hls_videos(request):
|
||||
video_url = request.GET.get('video_name', '')
|
||||
type = request.GET.get('video_type', '')
|
||||
video_type = request.GET.get('video_type', '')
|
||||
|
||||
end_location = str(settings.MEDIA_ROOT) + '/hls/'+ video_url +'.m3u8'
|
||||
end_file_name = '/media/hls/'+ video_url +'_720p.m3u8'
|
||||
# Sanitize inputs to prevent path traversal
|
||||
video_url = os.path.basename(video_url)
|
||||
video_type = os.path.basename(video_type)
|
||||
|
||||
if not video_url or not video_type:
|
||||
return Response({"error": "video_name and video_type are required"}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
end_location = os.path.join(str(settings.MEDIA_ROOT), 'hls', video_url + '.m3u8')
|
||||
end_file_name = '/media/hls/' + video_url + '_720p.m3u8'
|
||||
|
||||
# Verify the resolved path is within MEDIA_ROOT
|
||||
if not os.path.realpath(end_location).startswith(os.path.realpath(str(settings.MEDIA_ROOT))):
|
||||
return Response({"error": "Invalid path"}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
if default_storage.exists(end_location):
|
||||
return JsonResponse({'file_location': end_file_name})
|
||||
|
||||
media_location = os.path.join(settings.MEDIA_ROOT) + "/" + type + "/" + video_url
|
||||
media_location = os.path.join(str(settings.MEDIA_ROOT), video_type, video_url)
|
||||
|
||||
# Verify media_location is within MEDIA_ROOT
|
||||
if not os.path.realpath(media_location).startswith(os.path.realpath(str(settings.MEDIA_ROOT))):
|
||||
return Response({"error": "Invalid path"}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
video = ffmpeg_streaming.input(media_location)
|
||||
|
||||
|
||||
hls = video.hls(Formats.h264())
|
||||
#_720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024))
|
||||
hls.auto_generate_representations()
|
||||
@@ -67,9 +82,17 @@ def hls_videos(request):
|
||||
# {{url}}/videos/hls_video?video_name=Recover_24.mp4&video_type=videos
|
||||
return JsonResponse({'file_location': end_file_name})
|
||||
|
||||
@api_view(['GET'])
|
||||
@api_view(['POST'])
|
||||
@authentication_classes([TokenAuthentication])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def create_hls(request):
|
||||
create_hls_tasks.delay()
|
||||
return JsonResponse({'running': "running"})
|
||||
filename = request.data.get('filename', '')
|
||||
if not filename:
|
||||
return Response({"error": "filename is required"}, status=status.HTTP_400_BAD_REQUEST)
|
||||
# Sanitize to prevent path traversal
|
||||
filename = os.path.basename(filename)
|
||||
full_path = os.path.join(str(settings.MEDIA_ROOT), 'videos', filename)
|
||||
if not os.path.realpath(full_path).startswith(os.path.realpath(str(settings.MEDIA_ROOT))):
|
||||
return Response({"error": "Invalid path"}, status=status.HTTP_400_BAD_REQUEST)
|
||||
create_hls_tasks.delay(os.path.join('videos', filename))
|
||||
return JsonResponse({'running': "running"})
|
||||
|
||||
Reference in New Issue
Block a user