1
0
mirror of https://github.com/hanxi/xiaomusic.git synced 2026-03-25 09:49:46 +08:00

feat: 加密音乐和图片访问链接 (#200)

* use basic auth, cannot work

* Revert "use basic auth, cannot work"

This reverts commit 16a9683855.

* use access key/code control

* Auto-format code 🧹🌟🤖

---------

Co-authored-by: Formatter [BOT] <runner@fv-az1766-921.lyuwioyq51hutffh0ei52p4blg.dx.internal.cloudapp.net>
This commit is contained in:
Gao, Ruiyuan
2024-09-25 18:41:28 +08:00
committed by GitHub
parent dec21aa57c
commit db8b90487f
2 changed files with 77 additions and 5 deletions

View File

@@ -1,4 +1,5 @@
import asyncio
import hashlib
import json
import mimetypes
import os
@@ -381,11 +382,46 @@ async def file_iterator(file_path, start, end):
yield data
def access_key_verification(file_path, key, code):
if config.disable_httpauth:
return True
log.debug(f"访问限制接收端[{file_path}, {key}, {code}]")
if key is not None:
current_key_bytes = key.encode("utf8")
correct_key_bytes = (
config.httpauth_username + config.httpauth_password
).encode("utf8")
is_correct_key = secrets.compare_digest(correct_key_bytes, current_key_bytes)
if is_correct_key:
return True
if code is not None:
current_code_bytes = code.encode("utf8")
correct_code_bytes = (
hashlib.md5(
(
file_path + config.httpauth_username + config.httpauth_password
).encode("utf-8")
)
.hexdigest()
.encode("utf-8")
)
is_correct_code = secrets.compare_digest(correct_code_bytes, current_code_bytes)
if is_correct_code:
return True
return False
range_pattern = re.compile(r"bytes=(\d+)-(\d*)")
@app.get("/music/{file_path:path}")
async def music_file(request: Request, file_path: str):
async def music_file(request: Request, file_path: str, key: str = "", code: str = ""):
if not access_key_verification(request.url.path, key, code):
raise HTTPException(status_code=404, detail="File not found")
absolute_path = os.path.abspath(config.music_path)
absolute_file_path = os.path.normpath(os.path.join(absolute_path, file_path))
if not absolute_file_path.startswith(absolute_path):
@@ -432,7 +468,10 @@ async def music_options():
@app.get("/picture/{file_path:path}")
async def get_picture(request: Request, file_path: str):
async def get_picture(request: Request, file_path: str, key: str = "", code: str = ""):
if not access_key_verification(request.url.path, key, code):
raise HTTPException(status_code=404, detail="File not found")
absolute_path = os.path.abspath(config.picture_cache_path)
absolute_file_path = os.path.normpath(os.path.join(absolute_path, file_path))
if not absolute_file_path.startswith(absolute_path):