feat(security): enhance image URL and domain validation

This commit is contained in:
InfinityPacer
2024-10-14 01:33:53 +08:00
parent efb624259a
commit 422474b4b7
5 changed files with 218 additions and 83 deletions
+3 -42
View File
@@ -1,55 +1,16 @@
from typing import List, Any
from typing import Any, List
import requests
from fastapi import APIRouter, Depends, Response
from fastapi import APIRouter, Depends
from app import schemas
from app.chain.douban import DoubanChain
from app.core.config import settings
from app.core.context import MediaInfo
from app.core.security import verify_token, verify_resource_token
from app.core.security import verify_token
from app.schemas import MediaType
from app.utils.http import RequestUtils
router = APIRouter()
@router.get("/img", summary="豆瓣图片代理")
def douban_img(imgurl: str, _: schemas.TokenPayload = Depends(verify_resource_token)) -> Any:
"""
豆瓣图片代理
"""
def __download_image(url: str) -> requests.Response:
return RequestUtils(headers={
'Referer': "https://movie.douban.com/"
}, ua=settings.USER_AGENT).get_res(url=url)
if not imgurl:
return None
if settings.GLOBAL_IMAGE_CACHE:
# 获取Url中除域名外的路径
url_path = "/".join(imgurl.split('/')[3:])
# 生成缓存文件路径
cache_path = settings.CACHE_PATH / 'images' / url_path
# 如果缓存文件不存在,下载图片并保存
if not cache_path.exists():
response = __download_image(imgurl)
if response:
if not cache_path.parent.exists():
cache_path.parent.mkdir(parents=True)
with open(cache_path, 'wb') as f:
f.write(response.content)
return Response(content=response.content, media_type="image/jpeg")
else:
return Response(content=cache_path.read_bytes(), media_type="image/jpeg")
else:
response = __download_image(imgurl)
if response:
return Response(content=response.content, media_type="image/jpeg")
return None
@router.get("/person/{person_id}", summary="人物详情", response_model=schemas.MediaPerson)
def douban_person(person_id: int,
_: schemas.TokenPayload = Depends(verify_token)) -> Any: