45 lines
1.5 KiB
Python
45 lines
1.5 KiB
Python
import os
|
|
import re
|
|
import json
|
|
import hashlib
|
|
from pathlib import Path
|
|
from django.http import HttpResponse, JsonResponse, FileResponse
|
|
from django.views import View
|
|
from rest_framework.views import APIView
|
|
from rest_framework.response import Response
|
|
from rest_framework.permissions import AllowAny
|
|
|
|
|
|
class IPInfoView(APIView):
|
|
permission_classes = [AllowAny]
|
|
|
|
def get(self, request):
|
|
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '')
|
|
ip = x_forwarded_for.split(',')[0].strip() if x_forwarded_for else request.META.get('REMOTE_ADDR', '')
|
|
return Response({'code': 0, 'data': {'ip': ip}})
|
|
|
|
|
|
class AssetDownloadView(View):
|
|
def get(self, request, sha1):
|
|
# 验证 sha1 参数格式,防止路径遍历
|
|
if not re.match(r'^[0-9a-fA-F]{40}$', sha1):
|
|
return HttpResponse('Invalid hash', status=400)
|
|
|
|
resource_dir = Path('./resource').resolve()
|
|
file_path = (resource_dir / sha1[0:2] / sha1[2:4] / sha1[4:6] / sha1).resolve()
|
|
|
|
# 确保解析后的路径在允许的目录内
|
|
if not str(file_path).startswith(str(resource_dir)):
|
|
return HttpResponse('Invalid path', status=400)
|
|
|
|
if file_path.exists():
|
|
return FileResponse(open(file_path, 'rb'), as_attachment=True, filename=sha1)
|
|
return JsonResponse({'code': 404, 'msg': '文件不存在'}, status=404)
|
|
|
|
|
|
class HealthCheckView(APIView):
|
|
permission_classes = [AllowAny]
|
|
|
|
def get(self, request):
|
|
return Response({'code': 0, 'msg': 'ok', 'service': 'gvsds-django'})
|