mirror of
https://github.com/vastsa/FileCodeBox.git
synced 2026-11-21 22:47:13 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cdaf3638b8 | ||
|
|
1b6d8e7277 | ||
|
|
eb6fc627ae | ||
|
|
c1fb802223 | ||
|
|
1d03337e2f | ||
|
|
8d6eaacb70 | ||
|
|
3fe136536e | ||
|
|
aa6904a12c | ||
|
|
135dfdda9d | ||
|
|
e3ea7825bf | ||
|
|
6759539078 | ||
|
|
530f52aa1e | ||
|
|
b859ec211e | ||
|
|
8ac367d0b8 | ||
|
|
63cf725802 | ||
|
|
ccbc710d74 | ||
|
|
2d18b02005 | ||
|
|
e75fe596d0 | ||
|
|
be7ce2b30e | ||
|
|
0dbb594f4a | ||
|
|
b6aa28c345 | ||
|
|
fc6046a663 | ||
|
|
3467e973ac | ||
|
|
a1de598277 | ||
|
|
1ba0d2a044 | ||
|
|
1f0b0b791c | ||
|
|
4ae53fc4a5 | ||
|
|
35e069ccc3 | ||
|
|
2fa1faebe0 | ||
|
|
0ced9b1f38 | ||
|
|
1eb69e4cc5 | ||
|
|
71fc1ad8ea | ||
|
|
64ebc59a84 | ||
|
|
78b1dbe81f | ||
|
|
6805206efd | ||
|
|
6fe68be2dd | ||
|
|
0d71b914e4 | ||
|
|
20fcf0c3df | ||
|
|
75d345e5d0 | ||
|
|
a0c453b014 | ||
|
|
1cc901d2b9 | ||
|
|
e7b5792602 | ||
|
|
843a237fad | ||
|
|
4a9bf3a3a0 | ||
|
|
c380778336 | ||
|
|
f1c09b0b20 |
No files matched your search
+6
-9
@@ -3,13 +3,16 @@ FROM node:20-alpine AS frontend-builder
|
|||||||
|
|
||||||
RUN apk add --no-cache git python3 make g++
|
RUN apk add --no-cache git python3 make g++
|
||||||
|
|
||||||
|
RUN corepack enable && \
|
||||||
|
corepack prepare pnpm@9.15.9 --activate
|
||||||
|
|
||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
|
|
||||||
# 克隆并构建 2024 主题
|
# 克隆并构建 2024 主题
|
||||||
RUN git clone --depth 1 https://github.com/vastsa/FileCodeBoxFronted.git /build/fronted-2024 && \
|
RUN git clone --depth 1 https://github.com/vastsa/FileCodeBoxFronted.git /build/fronted-2024 && \
|
||||||
cd /build/fronted-2024 && \
|
cd /build/fronted-2024 && \
|
||||||
npm install && \
|
pnpm install --frozen-lockfile --prod=false && \
|
||||||
npm run build
|
pnpm run build
|
||||||
|
|
||||||
# 克隆并构建 2023 主题
|
# 克隆并构建 2023 主题
|
||||||
RUN git clone --depth 1 https://github.com/vastsa/FileCodeBoxFronted2023.git /build/fronted-2023 && \
|
RUN git clone --depth 1 https://github.com/vastsa/FileCodeBoxFronted2023.git /build/fronted-2023 && \
|
||||||
@@ -47,10 +50,4 @@ ENV HOST="0.0.0.0" \
|
|||||||
EXPOSE 12345
|
EXPOSE 12345
|
||||||
|
|
||||||
# 生产环境启动命令
|
# 生产环境启动命令
|
||||||
CMD uvicorn main:app \
|
CMD ["sh", "-c", "exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" --proxy-headers --forwarded-allow-ips '*'"]
|
||||||
--host $HOST \
|
|
||||||
--port $PORT \
|
|
||||||
--workers $WORKERS \
|
|
||||||
--log-level $LOG_LEVEL \
|
|
||||||
--proxy-headers \
|
|
||||||
--forwarded-allow-ips "*"
|
|
||||||
@@ -12,6 +12,13 @@ from core.settings import settings
|
|||||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||||
|
|
||||||
|
|
||||||
|
def _get_jwt_secret() -> bytes:
|
||||||
|
secret = getattr(settings, "jwt_secret", "")
|
||||||
|
if not secret:
|
||||||
|
raise RuntimeError("JWT签名密钥未初始化")
|
||||||
|
return secret.encode()
|
||||||
|
|
||||||
|
|
||||||
def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str:
|
def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str:
|
||||||
"""
|
"""
|
||||||
创建JWT token
|
创建JWT token
|
||||||
@@ -25,9 +32,7 @@ def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str:
|
|||||||
json.dumps({**data, "exp": int(time.time()) + expires_in}).encode()
|
json.dumps({**data, "exp": int(time.time()) + expires_in}).encode()
|
||||||
).decode()
|
).decode()
|
||||||
|
|
||||||
signature = hmac.new(
|
signature = hmac.new(_get_jwt_secret(), f"{header}.{payload}".encode(), "sha256").digest()
|
||||||
settings.admin_token.encode(), f"{header}.{payload}".encode(), "sha256"
|
|
||||||
).digest()
|
|
||||||
signature = base64.b64encode(signature).decode()
|
signature = base64.b64encode(signature).decode()
|
||||||
|
|
||||||
return f"{header}.{payload}.{signature}"
|
return f"{header}.{payload}.{signature}"
|
||||||
@@ -44,7 +49,7 @@ def verify_token(token: str) -> dict:
|
|||||||
|
|
||||||
# 验证签名
|
# 验证签名
|
||||||
expected_signature = hmac.new(
|
expected_signature = hmac.new(
|
||||||
settings.admin_token.encode(),
|
_get_jwt_secret(),
|
||||||
f"{header_b64}.{payload_b64}".encode(),
|
f"{header_b64}.{payload_b64}".encode(),
|
||||||
"sha256",
|
"sha256",
|
||||||
).digest()
|
).digest()
|
||||||
@@ -85,6 +90,18 @@ def _require_admin_payload(authorization: str) -> dict:
|
|||||||
return payload
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def get_admin_session(authorization: str = Header(default=None)) -> dict:
|
||||||
|
token = _extract_bearer_token(authorization)
|
||||||
|
payload = _require_admin_payload(authorization)
|
||||||
|
return {
|
||||||
|
"id": "admin",
|
||||||
|
"username": "admin",
|
||||||
|
"token": token,
|
||||||
|
"token_type": "Bearer",
|
||||||
|
"expires_at": payload.get("exp"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
ADMIN_PUBLIC_ENDPOINTS = {("POST", "/admin/login")}
|
ADMIN_PUBLIC_ENDPOINTS = {("POST", "/admin/login")}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+44
-1
@@ -1,5 +1,5 @@
|
|||||||
import datetime
|
import datetime
|
||||||
from typing import Optional, Union
|
from typing import Any, Optional, Union
|
||||||
|
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
@@ -8,6 +8,10 @@ class IDData(BaseModel):
|
|||||||
id: int
|
id: int
|
||||||
|
|
||||||
|
|
||||||
|
class IDsData(BaseModel):
|
||||||
|
ids: list[int]
|
||||||
|
|
||||||
|
|
||||||
class ShareItem(BaseModel):
|
class ShareItem(BaseModel):
|
||||||
expire_value: int
|
expire_value: int
|
||||||
expire_style: str = "day"
|
expire_style: str = "day"
|
||||||
@@ -29,3 +33,42 @@ class UpdateFileData(BaseModel):
|
|||||||
suffix: Optional[str] = None
|
suffix: Optional[str] = None
|
||||||
expired_at: Optional[Union[datetime.datetime, str]] = None
|
expired_at: Optional[Union[datetime.datetime, str]] = None
|
||||||
expired_count: Optional[int] = None
|
expired_count: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
|
class BatchUpdateFileData(BaseModel):
|
||||||
|
ids: list[int]
|
||||||
|
expired_at: Optional[Union[datetime.datetime, str]] = None
|
||||||
|
expired_count: Optional[int] = None
|
||||||
|
clearExpiredAt: Optional[bool] = None
|
||||||
|
clear_expired_at: Optional[bool] = None
|
||||||
|
|
||||||
|
|
||||||
|
class FilePolicyActionData(BaseModel):
|
||||||
|
id: int
|
||||||
|
action: str
|
||||||
|
downloadLimit: Optional[int] = None
|
||||||
|
download_limit: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
|
class BatchFilePolicyActionData(BaseModel):
|
||||||
|
ids: list[int]
|
||||||
|
action: str
|
||||||
|
downloadLimit: Optional[int] = None
|
||||||
|
download_limit: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
|
class FileMetadataData(BaseModel):
|
||||||
|
id: int
|
||||||
|
note: Optional[str] = None
|
||||||
|
tags: Optional[list[str]] = None
|
||||||
|
|
||||||
|
|
||||||
|
class FileViewPresetData(BaseModel):
|
||||||
|
id: Optional[str] = None
|
||||||
|
name: str
|
||||||
|
filters: Optional[dict[str, Any]] = None
|
||||||
|
params: Optional[dict[str, Any]] = None
|
||||||
|
|
||||||
|
|
||||||
|
class FileViewPresetDeleteData(BaseModel):
|
||||||
|
id: str
|
||||||
+1494
-42
File diff suppressed because it is too large.
Load diff
+446
-11
@@ -3,16 +3,32 @@
|
|||||||
# @File : views.py
|
# @File : views.py
|
||||||
# @Software: PyCharm
|
# @Software: PyCharm
|
||||||
import datetime
|
import datetime
|
||||||
|
from collections import Counter
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||||
from apps.admin.dependencies import (
|
from apps.admin.dependencies import (
|
||||||
admin_required,
|
admin_required,
|
||||||
|
get_admin_session,
|
||||||
get_file_service,
|
get_file_service,
|
||||||
get_config_service,
|
get_config_service,
|
||||||
get_local_file_service,
|
get_local_file_service,
|
||||||
)
|
)
|
||||||
from apps.admin.schemas import IDData, ShareItem, DeleteItem, LoginData, UpdateFileData
|
from apps.admin.schemas import (
|
||||||
|
IDData,
|
||||||
|
IDsData,
|
||||||
|
BatchUpdateFileData,
|
||||||
|
BatchFilePolicyActionData,
|
||||||
|
FilePolicyActionData,
|
||||||
|
FileMetadataData,
|
||||||
|
FileViewPresetData,
|
||||||
|
FileViewPresetDeleteData,
|
||||||
|
ShareItem,
|
||||||
|
DeleteItem,
|
||||||
|
LoginData,
|
||||||
|
UpdateFileData,
|
||||||
|
)
|
||||||
from core.response import APIResponse
|
from core.response import APIResponse
|
||||||
from apps.base.models import FileCodes, KeyValue
|
from apps.base.models import FileCodes, KeyValue
|
||||||
from apps.admin.dependencies import create_token
|
from apps.admin.dependencies import create_token
|
||||||
@@ -24,6 +40,14 @@ admin_api = APIRouter(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _pick_query_text(*values: Optional[str]) -> Optional[str]:
|
||||||
|
for value in values:
|
||||||
|
normalized_value = str(value or "").strip()
|
||||||
|
if normalized_value:
|
||||||
|
return normalized_value
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
@admin_api.post("/login")
|
@admin_api.post("/login")
|
||||||
async def login(data: LoginData):
|
async def login(data: LoginData):
|
||||||
if not verify_password(data.password, settings.admin_token):
|
if not verify_password(data.password, settings.admin_token):
|
||||||
@@ -33,10 +57,37 @@ async def login(data: LoginData):
|
|||||||
return APIResponse(detail={"token": token, "token_type": "Bearer"})
|
return APIResponse(detail={"token": token, "token_type": "Bearer"})
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.get("/verify")
|
||||||
|
async def verify_admin(session: dict = Depends(get_admin_session)):
|
||||||
|
return APIResponse(detail=session)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.post("/logout")
|
||||||
|
async def logout_admin():
|
||||||
|
return APIResponse(detail={"ok": True})
|
||||||
|
|
||||||
|
|
||||||
|
async def build_dashboard_recent_file(file_code: FileCodes) -> dict:
|
||||||
|
is_expired = await file_code.is_expired()
|
||||||
|
return {
|
||||||
|
"id": file_code.id,
|
||||||
|
"code": file_code.code,
|
||||||
|
"name": file_code.prefix + file_code.suffix,
|
||||||
|
"suffix": file_code.suffix,
|
||||||
|
"size": file_code.size,
|
||||||
|
"text": file_code.text is not None,
|
||||||
|
"expiredAt": file_code.expired_at,
|
||||||
|
"expiredCount": file_code.expired_count,
|
||||||
|
"usedCount": file_code.used_count,
|
||||||
|
"createdAt": file_code.created_at,
|
||||||
|
"isExpired": is_expired,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@admin_api.get("/dashboard")
|
@admin_api.get("/dashboard")
|
||||||
async def dashboard():
|
async def dashboard(file_service: FileService = Depends(get_file_service)):
|
||||||
all_codes = await FileCodes.all()
|
all_codes = await FileCodes.all()
|
||||||
all_size = str(sum([code.size for code in all_codes]))
|
all_size = sum([code.size for code in all_codes])
|
||||||
sys_start = await KeyValue.filter(key="sys_start").first()
|
sys_start = await KeyValue.filter(key="sys_start").first()
|
||||||
now = await get_now()
|
now = await get_now()
|
||||||
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||||
@@ -46,19 +97,83 @@ async def dashboard():
|
|||||||
created_at__gte=yesterday_start, created_at__lte=yesterday_end
|
created_at__gte=yesterday_start, created_at__lte=yesterday_end
|
||||||
)
|
)
|
||||||
today_codes = FileCodes.filter(created_at__gte=today_start)
|
today_codes = FileCodes.filter(created_at__gte=today_start)
|
||||||
|
yesterday_file_codes = await yesterday_codes
|
||||||
|
today_file_codes = await today_codes
|
||||||
|
expired_count = 0
|
||||||
|
for file_code in all_codes:
|
||||||
|
if await file_code.is_expired():
|
||||||
|
expired_count += 1
|
||||||
|
health_summary = await file_service.build_file_health_summary(all_codes, now=now)
|
||||||
|
|
||||||
|
text_count = sum(1 for file_code in all_codes if file_code.text is not None)
|
||||||
|
chunked_count = sum(1 for file_code in all_codes if file_code.is_chunked)
|
||||||
|
used_count = sum([file_code.used_count for file_code in all_codes])
|
||||||
|
suffix_counter = Counter(
|
||||||
|
"Text" if file_code.text is not None else (file_code.suffix or "file")
|
||||||
|
for file_code in all_codes
|
||||||
|
)
|
||||||
|
recent_file_codes = sorted(
|
||||||
|
all_codes,
|
||||||
|
key=lambda file_code: file_code.created_at.timestamp()
|
||||||
|
if file_code.created_at
|
||||||
|
else 0,
|
||||||
|
reverse=True,
|
||||||
|
)[:8]
|
||||||
|
recent_activities = await file_service.list_admin_activities(limit=8)
|
||||||
return APIResponse(
|
return APIResponse(
|
||||||
detail={
|
detail={
|
||||||
"totalFiles": len(all_codes),
|
"totalFiles": len(all_codes),
|
||||||
"storageUsed": all_size,
|
"storageUsed": str(all_size),
|
||||||
"sysUptime": sys_start.value,
|
"sysUptime": sys_start.value if sys_start else None,
|
||||||
"yesterdayCount": await yesterday_codes.count(),
|
"yesterdayCount": len(yesterday_file_codes),
|
||||||
"yesterdaySize": str(sum([code.size for code in await yesterday_codes])),
|
"yesterdaySize": str(sum([code.size for code in yesterday_file_codes])),
|
||||||
"todayCount": await today_codes.count(),
|
"todayCount": len(today_file_codes),
|
||||||
"todaySize": str(sum([code.size for code in await today_codes])),
|
"todaySize": str(sum([code.size for code in today_file_codes])),
|
||||||
|
"activeCount": len(all_codes) - expired_count,
|
||||||
|
"expiredCount": expired_count,
|
||||||
|
"textCount": text_count,
|
||||||
|
"fileCount": len(all_codes) - text_count,
|
||||||
|
"chunkedCount": chunked_count,
|
||||||
|
"usedCount": used_count,
|
||||||
|
"storageBackend": settings.file_storage,
|
||||||
|
"uploadSizeLimit": settings.uploadSize,
|
||||||
|
"openUpload": settings.openUpload,
|
||||||
|
"enableChunk": settings.enableChunk,
|
||||||
|
"maxSaveSeconds": settings.max_save_seconds,
|
||||||
|
**health_summary,
|
||||||
|
"healthSummary": health_summary,
|
||||||
|
"topSuffixes": [
|
||||||
|
{"suffix": suffix, "count": count}
|
||||||
|
for suffix, count in suffix_counter.most_common(8)
|
||||||
|
],
|
||||||
|
"recentFiles": [
|
||||||
|
await build_dashboard_recent_file(file_code)
|
||||||
|
for file_code in recent_file_codes
|
||||||
|
],
|
||||||
|
"recentActivities": recent_activities["activities"],
|
||||||
|
"recent_activities": recent_activities["activities"],
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.get("/activities")
|
||||||
|
async def admin_activities(
|
||||||
|
limit: int = 20,
|
||||||
|
action: Optional[str] = None,
|
||||||
|
targetType: Optional[str] = None,
|
||||||
|
target_type: Optional[str] = None,
|
||||||
|
keyword: Optional[str] = None,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
result = await file_service.list_admin_activities(
|
||||||
|
limit=limit,
|
||||||
|
action=action,
|
||||||
|
target_type=_pick_query_text(targetType, target_type),
|
||||||
|
keyword=keyword,
|
||||||
|
)
|
||||||
|
return APIResponse(detail=result)
|
||||||
|
|
||||||
|
|
||||||
@admin_api.delete("/file/delete")
|
@admin_api.delete("/file/delete")
|
||||||
async def file_delete(
|
async def file_delete(
|
||||||
data: IDData,
|
data: IDData,
|
||||||
@@ -68,24 +183,296 @@ async def file_delete(
|
|||||||
return APIResponse()
|
return APIResponse()
|
||||||
|
|
||||||
|
|
||||||
|
async def batch_delete_files(
|
||||||
|
data: IDsData,
|
||||||
|
file_service: FileService,
|
||||||
|
):
|
||||||
|
if not data.ids:
|
||||||
|
raise HTTPException(status_code=400, detail="请选择要删除的文件")
|
||||||
|
result = await file_service.delete_files(data.ids)
|
||||||
|
return APIResponse(detail=result)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.delete("/file/batch-delete")
|
||||||
|
async def file_batch_delete(
|
||||||
|
data: IDsData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await batch_delete_files(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.post("/file/batch-delete")
|
||||||
|
async def file_batch_delete_post(
|
||||||
|
data: IDsData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await batch_delete_files(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
|
async def batch_update_files(
|
||||||
|
data: BatchUpdateFileData,
|
||||||
|
file_service: FileService,
|
||||||
|
):
|
||||||
|
if not data.ids:
|
||||||
|
raise HTTPException(status_code=400, detail="请选择要更新的文件")
|
||||||
|
|
||||||
|
update_data = {}
|
||||||
|
fields_set = data.model_fields_set
|
||||||
|
should_clear_expired_at = bool(data.clearExpiredAt or data.clear_expired_at)
|
||||||
|
|
||||||
|
if should_clear_expired_at:
|
||||||
|
update_data["expired_at"] = None
|
||||||
|
update_data["expired_count"] = -1
|
||||||
|
elif "expired_at" in fields_set and data.expired_at != "":
|
||||||
|
update_data["expired_at"] = data.expired_at
|
||||||
|
|
||||||
|
if (
|
||||||
|
not should_clear_expired_at
|
||||||
|
and "expired_count" in fields_set
|
||||||
|
and data.expired_count is not None
|
||||||
|
):
|
||||||
|
update_data["expired_count"] = data.expired_count
|
||||||
|
|
||||||
|
if not update_data:
|
||||||
|
raise HTTPException(status_code=400, detail="请选择要更新的字段")
|
||||||
|
|
||||||
|
result = await file_service.update_files(data.ids, update_data)
|
||||||
|
return APIResponse(detail=result)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.patch("/file/batch-update")
|
||||||
|
async def file_batch_update(
|
||||||
|
data: BatchUpdateFileData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await batch_update_files(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.post("/file/batch-update")
|
||||||
|
async def file_batch_update_post(
|
||||||
|
data: BatchUpdateFileData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await batch_update_files(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
|
async def apply_file_policy_action(
|
||||||
|
data: FilePolicyActionData,
|
||||||
|
file_service: FileService,
|
||||||
|
):
|
||||||
|
download_limit = data.downloadLimit
|
||||||
|
if download_limit is None:
|
||||||
|
download_limit = data.download_limit
|
||||||
|
|
||||||
|
detail = await file_service.apply_file_policy_action(
|
||||||
|
file_id=data.id,
|
||||||
|
action=data.action,
|
||||||
|
download_limit=download_limit,
|
||||||
|
)
|
||||||
|
return APIResponse(detail=detail)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.patch("/file/policy-action")
|
||||||
|
async def file_policy_action(
|
||||||
|
data: FilePolicyActionData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await apply_file_policy_action(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.post("/file/policy-action")
|
||||||
|
async def file_policy_action_post(
|
||||||
|
data: FilePolicyActionData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await apply_file_policy_action(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
|
async def apply_batch_file_policy_action(
|
||||||
|
data: BatchFilePolicyActionData,
|
||||||
|
file_service: FileService,
|
||||||
|
):
|
||||||
|
if not data.ids:
|
||||||
|
raise HTTPException(status_code=400, detail="请选择要更新的文件")
|
||||||
|
|
||||||
|
download_limit = data.downloadLimit
|
||||||
|
if download_limit is None:
|
||||||
|
download_limit = data.download_limit
|
||||||
|
|
||||||
|
result = await file_service.apply_files_policy_action(
|
||||||
|
file_ids=data.ids,
|
||||||
|
action=data.action,
|
||||||
|
download_limit=download_limit,
|
||||||
|
)
|
||||||
|
return APIResponse(detail=result)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.patch("/file/batch-policy-action")
|
||||||
|
async def file_batch_policy_action(
|
||||||
|
data: BatchFilePolicyActionData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await apply_batch_file_policy_action(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.post("/file/batch-policy-action")
|
||||||
|
async def file_batch_policy_action_post(
|
||||||
|
data: BatchFilePolicyActionData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await apply_batch_file_policy_action(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
@admin_api.get("/file/list")
|
@admin_api.get("/file/list")
|
||||||
async def file_list(
|
async def file_list(
|
||||||
page: int = 1,
|
page: int = 1,
|
||||||
size: int = 10,
|
size: int = 10,
|
||||||
keyword: str = "",
|
keyword: str = "",
|
||||||
|
status: str = "",
|
||||||
|
type: str = "",
|
||||||
|
health: str = "",
|
||||||
|
sortBy: str = "created_at",
|
||||||
|
sortOrder: str = "desc",
|
||||||
file_service: FileService = Depends(get_file_service),
|
file_service: FileService = Depends(get_file_service),
|
||||||
):
|
):
|
||||||
files, total = await file_service.list_files(page, size, keyword)
|
page = max(page, 1)
|
||||||
|
size = min(max(size, 1), 100)
|
||||||
|
files, total, summary = await file_service.list_files(
|
||||||
|
page,
|
||||||
|
size,
|
||||||
|
keyword,
|
||||||
|
status=status,
|
||||||
|
file_type=type,
|
||||||
|
health=health,
|
||||||
|
sort_by=sortBy,
|
||||||
|
sort_order=sortOrder,
|
||||||
|
)
|
||||||
return APIResponse(
|
return APIResponse(
|
||||||
detail={
|
detail={
|
||||||
"page": page,
|
"page": page,
|
||||||
"size": size,
|
"size": size,
|
||||||
"data": files,
|
"data": files,
|
||||||
"total": total,
|
"total": total,
|
||||||
|
"summary": summary,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.get("/file/detail")
|
||||||
|
async def file_detail(
|
||||||
|
id: int,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
detail = await file_service.get_file_detail(id)
|
||||||
|
return APIResponse(detail=detail)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.post("/file/detail")
|
||||||
|
async def file_detail_post(
|
||||||
|
data: IDData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
detail = await file_service.get_file_detail(data.id)
|
||||||
|
return APIResponse(detail=detail)
|
||||||
|
|
||||||
|
|
||||||
|
async def update_file_metadata(
|
||||||
|
data: FileMetadataData,
|
||||||
|
file_service: FileService,
|
||||||
|
):
|
||||||
|
fields_set = data.model_fields_set
|
||||||
|
update_note = "note" in fields_set
|
||||||
|
update_tags = "tags" in fields_set
|
||||||
|
if not update_note and not update_tags:
|
||||||
|
raise HTTPException(status_code=400, detail="请选择要更新的元数据")
|
||||||
|
|
||||||
|
detail = await file_service.update_file_metadata(
|
||||||
|
file_id=data.id,
|
||||||
|
note=data.note,
|
||||||
|
tags=data.tags,
|
||||||
|
update_note=update_note,
|
||||||
|
update_tags=update_tags,
|
||||||
|
)
|
||||||
|
return APIResponse(detail=detail)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.patch("/file/metadata")
|
||||||
|
async def file_metadata(
|
||||||
|
data: FileMetadataData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await update_file_metadata(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.post("/file/metadata")
|
||||||
|
async def file_metadata_post(
|
||||||
|
data: FileMetadataData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await update_file_metadata(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.get("/file/view-presets")
|
||||||
|
async def file_view_presets(
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
result = await file_service.list_file_view_presets()
|
||||||
|
return APIResponse(detail=result)
|
||||||
|
|
||||||
|
|
||||||
|
async def save_file_view_preset(
|
||||||
|
data: FileViewPresetData,
|
||||||
|
file_service: FileService,
|
||||||
|
):
|
||||||
|
filters = data.filters if data.filters is not None else data.params
|
||||||
|
preset = await file_service.save_file_view_preset(
|
||||||
|
preset_id=data.id,
|
||||||
|
name=data.name,
|
||||||
|
filters=filters or {},
|
||||||
|
)
|
||||||
|
return APIResponse(detail=preset)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.post("/file/view-presets")
|
||||||
|
async def file_view_presets_save(
|
||||||
|
data: FileViewPresetData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await save_file_view_preset(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.patch("/file/view-presets")
|
||||||
|
async def file_view_presets_patch(
|
||||||
|
data: FileViewPresetData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await save_file_view_preset(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
|
async def delete_file_view_preset(
|
||||||
|
data: FileViewPresetDeleteData,
|
||||||
|
file_service: FileService,
|
||||||
|
):
|
||||||
|
result = await file_service.delete_file_view_preset(data.id)
|
||||||
|
return APIResponse(detail=result)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.delete("/file/view-presets")
|
||||||
|
async def file_view_presets_delete(
|
||||||
|
data: FileViewPresetDeleteData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await delete_file_view_preset(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.post("/file/view-presets/delete")
|
||||||
|
async def file_view_presets_delete_post(
|
||||||
|
data: FileViewPresetDeleteData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
return await delete_file_view_preset(data, file_service)
|
||||||
|
|
||||||
|
|
||||||
@admin_api.get("/config/get")
|
@admin_api.get("/config/get")
|
||||||
async def get_config(
|
async def get_config(
|
||||||
config_service: ConfigService = Depends(get_config_service),
|
config_service: ConfigService = Depends(get_config_service),
|
||||||
@@ -97,9 +484,17 @@ async def get_config(
|
|||||||
async def update_config(
|
async def update_config(
|
||||||
data: dict,
|
data: dict,
|
||||||
config_service: ConfigService = Depends(get_config_service),
|
config_service: ConfigService = Depends(get_config_service),
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
):
|
):
|
||||||
data.pop("themesChoices")
|
data.pop("themesChoices", None)
|
||||||
await config_service.update_config(data)
|
await config_service.update_config(data)
|
||||||
|
await file_service.record_admin_activity(
|
||||||
|
action="config.update",
|
||||||
|
target_type="config",
|
||||||
|
target_name="system",
|
||||||
|
count=1,
|
||||||
|
meta={"fields": sorted(data.keys())},
|
||||||
|
)
|
||||||
return APIResponse()
|
return APIResponse()
|
||||||
|
|
||||||
|
|
||||||
@@ -112,6 +507,16 @@ async def file_download(
|
|||||||
return file_content
|
return file_content
|
||||||
|
|
||||||
|
|
||||||
|
@admin_api.get("/file/preview")
|
||||||
|
async def file_preview(
|
||||||
|
id: int,
|
||||||
|
maxChars: int = 4000,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
|
):
|
||||||
|
preview = await file_service.preview_file(id, maxChars)
|
||||||
|
return APIResponse(detail=preview)
|
||||||
|
|
||||||
|
|
||||||
@admin_api.get("/local/lists")
|
@admin_api.get("/local/lists")
|
||||||
async def get_local_lists(
|
async def get_local_lists(
|
||||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||||
@@ -124,8 +529,16 @@ async def get_local_lists(
|
|||||||
async def delete_local_file(
|
async def delete_local_file(
|
||||||
item: DeleteItem,
|
item: DeleteItem,
|
||||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
):
|
):
|
||||||
result = await local_file_service.delete_file(item.filename)
|
result = await local_file_service.delete_file(item.filename)
|
||||||
|
await file_service.record_admin_activity(
|
||||||
|
action="local_file.delete",
|
||||||
|
target_type="local_file",
|
||||||
|
target_name=item.filename,
|
||||||
|
count=1,
|
||||||
|
meta={"success": bool(result)},
|
||||||
|
)
|
||||||
return APIResponse(detail=result)
|
return APIResponse(detail=result)
|
||||||
|
|
||||||
|
|
||||||
@@ -135,16 +548,29 @@ async def share_local_file(
|
|||||||
file_service: FileService = Depends(get_file_service),
|
file_service: FileService = Depends(get_file_service),
|
||||||
):
|
):
|
||||||
share_info = await file_service.share_local_file(item)
|
share_info = await file_service.share_local_file(item)
|
||||||
|
await file_service.record_admin_activity(
|
||||||
|
action="local_file.share",
|
||||||
|
target_type="file",
|
||||||
|
target_id=share_info.get("id") if isinstance(share_info, dict) else None,
|
||||||
|
target_name=item.filename,
|
||||||
|
count=1,
|
||||||
|
meta={
|
||||||
|
"expireValue": item.expire_value,
|
||||||
|
"expireStyle": item.expire_style,
|
||||||
|
},
|
||||||
|
)
|
||||||
return APIResponse(detail=share_info)
|
return APIResponse(detail=share_info)
|
||||||
|
|
||||||
|
|
||||||
@admin_api.patch("/file/update")
|
@admin_api.patch("/file/update")
|
||||||
async def update_file(
|
async def update_file(
|
||||||
data: UpdateFileData,
|
data: UpdateFileData,
|
||||||
|
file_service: FileService = Depends(get_file_service),
|
||||||
):
|
):
|
||||||
file_code = await FileCodes.filter(id=data.id).first()
|
file_code = await FileCodes.filter(id=data.id).first()
|
||||||
if not file_code:
|
if not file_code:
|
||||||
raise HTTPException(status_code=404, detail="文件不存在")
|
raise HTTPException(status_code=404, detail="文件不存在")
|
||||||
|
target_name = file_service._build_file_activity_name(file_code)
|
||||||
update_data = {}
|
update_data = {}
|
||||||
|
|
||||||
if data.code is not None and data.code != file_code.code:
|
if data.code is not None and data.code != file_code.code:
|
||||||
@@ -166,4 +592,13 @@ async def update_file(
|
|||||||
update_data["expired_count"] = data.expired_count
|
update_data["expired_count"] = data.expired_count
|
||||||
|
|
||||||
await file_code.update_from_dict(update_data).save()
|
await file_code.update_from_dict(update_data).save()
|
||||||
|
if update_data:
|
||||||
|
await file_service.record_admin_activity(
|
||||||
|
action="file.update",
|
||||||
|
target_type="file",
|
||||||
|
target_id=data.id,
|
||||||
|
target_name=target_name,
|
||||||
|
count=1,
|
||||||
|
meta={"fields": sorted(update_data.keys())},
|
||||||
|
)
|
||||||
return APIResponse(detail="更新成功")
|
return APIResponse(detail="更新成功")
|
||||||
@@ -1,7 +1,69 @@
|
|||||||
from typing import Dict, Union
|
from ipaddress import ip_address, ip_network
|
||||||
|
from typing import Dict, Iterable, Union
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from fastapi import HTTPException, Request
|
from fastapi import HTTPException, Request
|
||||||
|
|
||||||
|
from core.settings import settings
|
||||||
|
|
||||||
|
|
||||||
|
def _iter_trusted_proxies() -> Iterable[str]:
|
||||||
|
trusted_proxies = getattr(settings, "trustedProxies", [])
|
||||||
|
if isinstance(trusted_proxies, str):
|
||||||
|
trusted_proxies = [item.strip() for item in trusted_proxies.split(",")]
|
||||||
|
return [item for item in trusted_proxies if item]
|
||||||
|
|
||||||
|
|
||||||
|
def _is_trusted_proxy(host: str) -> bool:
|
||||||
|
try:
|
||||||
|
remote_addr = ip_address(host)
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
for proxy in _iter_trusted_proxies():
|
||||||
|
try:
|
||||||
|
if remote_addr in ip_network(proxy, strict=False):
|
||||||
|
return True
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _get_forwarded_for_ip(header_value: str, fallback_ip: str) -> str:
|
||||||
|
forwarded_chain = [
|
||||||
|
item.strip() for item in header_value.split(",") if item.strip()
|
||||||
|
]
|
||||||
|
if not forwarded_chain:
|
||||||
|
return fallback_ip
|
||||||
|
|
||||||
|
for candidate in reversed(forwarded_chain):
|
||||||
|
try:
|
||||||
|
ip_address(candidate)
|
||||||
|
except ValueError:
|
||||||
|
return fallback_ip
|
||||||
|
if not _is_trusted_proxy(candidate):
|
||||||
|
return candidate
|
||||||
|
return forwarded_chain[0]
|
||||||
|
|
||||||
|
|
||||||
|
def get_client_ip(request: Request) -> str:
|
||||||
|
client_host = request.client.host if request.client else "unknown"
|
||||||
|
if not _is_trusted_proxy(client_host):
|
||||||
|
return client_host
|
||||||
|
|
||||||
|
forwarded_for = request.headers.get("X-Forwarded-For")
|
||||||
|
if forwarded_for:
|
||||||
|
return _get_forwarded_for_ip(forwarded_for, client_host)
|
||||||
|
|
||||||
|
real_ip = request.headers.get("X-Real-IP")
|
||||||
|
if real_ip:
|
||||||
|
try:
|
||||||
|
ip_address(real_ip)
|
||||||
|
except ValueError:
|
||||||
|
return client_host
|
||||||
|
return real_ip
|
||||||
|
|
||||||
|
return client_host
|
||||||
|
|
||||||
|
|
||||||
class IPRateLimit:
|
class IPRateLimit:
|
||||||
def __init__(self, count: int, minutes: int):
|
def __init__(self, count: int, minutes: int):
|
||||||
@@ -35,11 +97,7 @@ class IPRateLimit:
|
|||||||
}
|
}
|
||||||
|
|
||||||
def __call__(self, request: Request) -> str:
|
def __call__(self, request: Request) -> str:
|
||||||
ip = (
|
ip = get_client_ip(request)
|
||||||
request.headers.get("X-Real-IP")
|
|
||||||
or request.headers.get("X-Forwarded-For")
|
|
||||||
or request.client.host
|
|
||||||
)
|
|
||||||
if not self.check_ip(ip):
|
if not self.check_ip(ip):
|
||||||
raise HTTPException(status_code=423, detail="请求次数过多,请稍后再试")
|
raise HTTPException(status_code=423, detail="请求次数过多,请稍后再试")
|
||||||
return ip
|
return ip
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
from tortoise import connections
|
||||||
|
|
||||||
|
|
||||||
|
def _need_upgrade(columns: list[tuple]) -> bool:
|
||||||
|
for column in columns:
|
||||||
|
# PRAGMA table_info 返回 (cid, name, type, notnull, dflt_value, pk)
|
||||||
|
if column[1] == "size":
|
||||||
|
column_type = (column[2] or "").upper()
|
||||||
|
return "BIGINT" not in column_type
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
async def migrate():
|
||||||
|
conn = connections.get("default")
|
||||||
|
result = await conn.execute_query("PRAGMA table_info(filecodes)")
|
||||||
|
columns = result[1] if result and len(result) > 1 else []
|
||||||
|
|
||||||
|
if not columns or not _need_upgrade(columns):
|
||||||
|
return
|
||||||
|
|
||||||
|
await conn.execute_script(
|
||||||
|
"""
|
||||||
|
BEGIN;
|
||||||
|
CREATE TABLE IF NOT EXISTS filecodes_new
|
||||||
|
(
|
||||||
|
id INTEGER not null
|
||||||
|
primary key autoincrement,
|
||||||
|
code VARCHAR(255) not null
|
||||||
|
unique,
|
||||||
|
prefix VARCHAR(255) default '' not null,
|
||||||
|
suffix VARCHAR(255) default '' not null,
|
||||||
|
uuid_file_name VARCHAR(255),
|
||||||
|
file_path VARCHAR(255),
|
||||||
|
size BIGINT default 0 not null,
|
||||||
|
text TEXT,
|
||||||
|
expired_at TIMESTAMP,
|
||||||
|
expired_count INT default 0 not null,
|
||||||
|
used_count INT default 0 not null,
|
||||||
|
created_at TIMESTAMP default CURRENT_TIMESTAMP not null,
|
||||||
|
file_hash VARCHAR(128),
|
||||||
|
is_chunked BOOL default False not null,
|
||||||
|
upload_id VARCHAR(128)
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO filecodes_new (id, code, prefix, suffix, uuid_file_name, file_path, size, text,
|
||||||
|
expired_at, expired_count, used_count, created_at, file_hash,
|
||||||
|
is_chunked, upload_id)
|
||||||
|
SELECT id,
|
||||||
|
code,
|
||||||
|
prefix,
|
||||||
|
suffix,
|
||||||
|
uuid_file_name,
|
||||||
|
file_path,
|
||||||
|
size,
|
||||||
|
text,
|
||||||
|
expired_at,
|
||||||
|
expired_count,
|
||||||
|
used_count,
|
||||||
|
created_at,
|
||||||
|
file_hash,
|
||||||
|
is_chunked,
|
||||||
|
upload_id
|
||||||
|
FROM filecodes;
|
||||||
|
|
||||||
|
DROP TABLE filecodes;
|
||||||
|
ALTER TABLE filecodes_new
|
||||||
|
RENAME TO filecodes;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_filecodes_code_1c7ee7
|
||||||
|
on filecodes (code);
|
||||||
|
COMMIT;
|
||||||
|
"""
|
||||||
|
)
|
||||||
+1
-1
@@ -19,7 +19,7 @@ class FileCodes(models.Model):
|
|||||||
suffix = fields.CharField(max_length=255, default="")
|
suffix = fields.CharField(max_length=255, default="")
|
||||||
uuid_file_name = fields.CharField(max_length=255, null=True)
|
uuid_file_name = fields.CharField(max_length=255, null=True)
|
||||||
file_path = fields.CharField(max_length=255, null=True)
|
file_path = fields.CharField(max_length=255, null=True)
|
||||||
size = fields.IntField(default=0)
|
size = fields.BigIntField(default=0)
|
||||||
text = fields.TextField(null=True)
|
text = fields.TextField(null=True)
|
||||||
expired_at = fields.DatetimeField(null=True)
|
expired_at = fields.DatetimeField(null=True)
|
||||||
expired_count = fields.IntField(default=0)
|
expired_count = fields.IntField(default=0)
|
||||||
|
|||||||
+19
-4
@@ -76,8 +76,6 @@ async def get_expire_info(
|
|||||||
expired_at, extra = result
|
expired_at, extra = result
|
||||||
if expire_style == "count":
|
if expire_style == "count":
|
||||||
expired_count = extra
|
expired_count = extra
|
||||||
elif expire_style == "forever":
|
|
||||||
code = await get_random_code(style="string")
|
|
||||||
else:
|
else:
|
||||||
expired_at = result
|
expired_at = result
|
||||||
if expired_at and expired_at - now > max_timedelta:
|
if expired_at and expired_at - now > max_timedelta:
|
||||||
@@ -91,9 +89,26 @@ async def get_expire_info(
|
|||||||
return expired_at, expired_count, used_count, code
|
return expired_at, expired_count, used_count, code
|
||||||
|
|
||||||
|
|
||||||
async def get_random_code(style: str = "num") -> str:
|
def get_code_generate_type() -> str:
|
||||||
|
code_generate_type = getattr(settings, "code_generate_type", "number")
|
||||||
|
if code_generate_type in {"secret", "string"}:
|
||||||
|
return "secret"
|
||||||
|
return "number"
|
||||||
|
|
||||||
|
|
||||||
|
async def get_random_code(style: str | None = None) -> str:
|
||||||
|
code_style = style or get_code_generate_type()
|
||||||
|
if code_style == "num":
|
||||||
|
code_style = "number"
|
||||||
|
if code_style == "string":
|
||||||
|
code_style = "secret"
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
code = await get_random_num() if style == "num" else await get_random_string()
|
code = (
|
||||||
|
await get_random_num()
|
||||||
|
if code_style == "number"
|
||||||
|
else await get_random_string()
|
||||||
|
)
|
||||||
if not await FileCodes.filter(code=code).exists():
|
if not await FileCodes.filter(code=code).exists():
|
||||||
return str(code)
|
return str(code)
|
||||||
|
|
||||||
|
|||||||
+154
-25
@@ -1,4 +1,5 @@
|
|||||||
import datetime
|
import datetime
|
||||||
|
from fnmatch import fnmatchcase
|
||||||
import hashlib
|
import hashlib
|
||||||
import os
|
import os
|
||||||
import uuid
|
import uuid
|
||||||
@@ -7,7 +8,8 @@ from urllib.parse import unquote
|
|||||||
|
|
||||||
from typing import Optional, Tuple, Union
|
from typing import Optional, Tuple, Union
|
||||||
|
|
||||||
from fastapi import APIRouter, Form, UploadFile, File, Depends, HTTPException
|
from fastapi import APIRouter, Form, Request, UploadFile, File, Depends, HTTPException
|
||||||
|
from pydantic import BaseModel, ValidationError
|
||||||
from starlette import status
|
from starlette import status
|
||||||
|
|
||||||
from apps.admin.dependencies import share_required_login
|
from apps.admin.dependencies import share_required_login
|
||||||
@@ -95,10 +97,46 @@ async def validate_file_size(file: UploadFile, max_size: int) -> int:
|
|||||||
return size
|
return size
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_allowed_file_types() -> list[str]:
|
||||||
|
raw_value = settings.allowed_file_types
|
||||||
|
if isinstance(raw_value, str):
|
||||||
|
values = raw_value.replace(";", ",").split(",")
|
||||||
|
elif isinstance(raw_value, (list, tuple, set)):
|
||||||
|
values = raw_value
|
||||||
|
else:
|
||||||
|
values = []
|
||||||
|
|
||||||
|
allowed = [str(item).strip().lower() for item in values if str(item).strip()]
|
||||||
|
return allowed or ["*"]
|
||||||
|
|
||||||
|
|
||||||
|
def validate_file_type(file_name: str, content_type: Optional[str] = None) -> None:
|
||||||
|
allowed = normalize_allowed_file_types()
|
||||||
|
if "*" in allowed or "*/*" in allowed:
|
||||||
|
return
|
||||||
|
|
||||||
|
normalized_name = file_name.strip().lower()
|
||||||
|
normalized_content_type = (content_type or "").strip().lower()
|
||||||
|
|
||||||
|
for rule in allowed:
|
||||||
|
if "/" in rule and fnmatchcase(normalized_content_type, rule):
|
||||||
|
return
|
||||||
|
|
||||||
|
extension = rule if rule.startswith(".") else f".{rule}"
|
||||||
|
if normalized_name.endswith(extension):
|
||||||
|
return
|
||||||
|
|
||||||
|
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
|
||||||
|
|
||||||
|
|
||||||
async def create_file_code(code, **kwargs):
|
async def create_file_code(code, **kwargs):
|
||||||
return await FileCodes.create(code=code, **kwargs)
|
return await FileCodes.create(code=code, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_share_code(code: str) -> str:
|
||||||
|
return str(code or "").strip()
|
||||||
|
|
||||||
|
|
||||||
@share_api.post("/text/", dependencies=[Depends(share_required_login)])
|
@share_api.post("/text/", dependencies=[Depends(share_required_login)])
|
||||||
async def share_text(
|
async def share_text(
|
||||||
text: str = Form(...),
|
text: str = Form(...),
|
||||||
@@ -135,6 +173,7 @@ async def share_file(
|
|||||||
ip: str = Depends(ip_limit["upload"]),
|
ip: str = Depends(ip_limit["upload"]),
|
||||||
):
|
):
|
||||||
file_size = await validate_file_size(file, settings.uploadSize)
|
file_size = await validate_file_size(file, settings.uploadSize)
|
||||||
|
validate_file_type(file.filename or "", file.content_type)
|
||||||
if expire_style not in settings.expireStyle:
|
if expire_style not in settings.expireStyle:
|
||||||
raise HTTPException(status_code=400, detail="过期时间类型错误")
|
raise HTTPException(status_code=400, detail="过期时间类型错误")
|
||||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||||
@@ -161,7 +200,10 @@ async def share_file(
|
|||||||
async def get_code_file_by_code(
|
async def get_code_file_by_code(
|
||||||
code: str, check: bool = True
|
code: str, check: bool = True
|
||||||
) -> Tuple[bool, Union[FileCodes, str]]:
|
) -> Tuple[bool, Union[FileCodes, str]]:
|
||||||
file_code = await FileCodes.filter(code=code).first()
|
normalized_code = normalize_share_code(code)
|
||||||
|
if not normalized_code:
|
||||||
|
return False, "文件不存在"
|
||||||
|
file_code = await FileCodes.filter(code=normalized_code).first()
|
||||||
if not file_code:
|
if not file_code:
|
||||||
return False, "文件不存在"
|
return False, "文件不存在"
|
||||||
if await file_code.is_expired() and check:
|
if await file_code.is_expired() and check:
|
||||||
@@ -176,6 +218,64 @@ async def update_file_usage(file_code: FileCodes) -> None:
|
|||||||
await file_code.save()
|
await file_code.save()
|
||||||
|
|
||||||
|
|
||||||
|
def build_file_metadata(file_code: FileCodes) -> dict:
|
||||||
|
is_text = file_code.text is not None
|
||||||
|
remaining_downloads = (
|
||||||
|
file_code.expired_count if file_code.expired_count > 0 else None
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"code": file_code.code,
|
||||||
|
"name": file_code.prefix + file_code.suffix,
|
||||||
|
"size": file_code.size,
|
||||||
|
"type": "text" if is_text else "file",
|
||||||
|
"is_text": is_text,
|
||||||
|
"created_at": file_code.created_at,
|
||||||
|
"expired_at": file_code.expired_at,
|
||||||
|
"expires_at": file_code.expired_at,
|
||||||
|
"expired_count": file_code.expired_count,
|
||||||
|
"used_count": file_code.used_count,
|
||||||
|
"remaining_downloads": remaining_downloads,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def build_select_detail(
|
||||||
|
file_code: FileCodes, file_storage: FileStorageInterface
|
||||||
|
) -> dict:
|
||||||
|
metadata = build_file_metadata(file_code)
|
||||||
|
download_url = (
|
||||||
|
None if file_code.text is not None else await file_storage.get_file_url(file_code)
|
||||||
|
)
|
||||||
|
content = file_code.text if file_code.text is not None else None
|
||||||
|
return {
|
||||||
|
**metadata,
|
||||||
|
"text": content if content is not None else download_url,
|
||||||
|
"content": content,
|
||||||
|
"download_url": download_url,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@share_api.get("/metadata/")
|
||||||
|
async def get_file_metadata(code: str, ip: str = Depends(ip_limit["error"])):
|
||||||
|
has, file_code = await get_code_file_by_code(code)
|
||||||
|
if not has:
|
||||||
|
ip_limit["error"].add_ip(ip)
|
||||||
|
return APIResponse(code=404, detail=file_code)
|
||||||
|
|
||||||
|
assert isinstance(file_code, FileCodes)
|
||||||
|
return APIResponse(detail=build_file_metadata(file_code))
|
||||||
|
|
||||||
|
|
||||||
|
@share_api.post("/metadata/")
|
||||||
|
async def post_file_metadata(data: SelectFileModel, ip: str = Depends(ip_limit["error"])):
|
||||||
|
has, file_code = await get_code_file_by_code(data.code)
|
||||||
|
if not has:
|
||||||
|
ip_limit["error"].add_ip(ip)
|
||||||
|
return APIResponse(code=404, detail=file_code)
|
||||||
|
|
||||||
|
assert isinstance(file_code, FileCodes)
|
||||||
|
return APIResponse(detail=build_file_metadata(file_code))
|
||||||
|
|
||||||
|
|
||||||
@share_api.get("/select/")
|
@share_api.get("/select/")
|
||||||
async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
|
async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
|
||||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||||
@@ -199,27 +299,17 @@ async def select_file(data: SelectFileModel, ip: str = Depends(ip_limit["error"]
|
|||||||
|
|
||||||
assert isinstance(file_code, FileCodes)
|
assert isinstance(file_code, FileCodes)
|
||||||
await update_file_usage(file_code)
|
await update_file_usage(file_code)
|
||||||
return APIResponse(
|
return APIResponse(detail=await build_select_detail(file_code, file_storage))
|
||||||
detail={
|
|
||||||
"code": file_code.code,
|
|
||||||
"name": file_code.prefix + file_code.suffix,
|
|
||||||
"size": file_code.size,
|
|
||||||
"text": (
|
|
||||||
file_code.text
|
|
||||||
if file_code.text is not None
|
|
||||||
else await file_storage.get_file_url(file_code)
|
|
||||||
),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@share_api.get("/download")
|
@share_api.get("/download")
|
||||||
async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"])):
|
async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"])):
|
||||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||||
if await get_select_token(code) != key:
|
normalized_code = normalize_share_code(code)
|
||||||
|
if await get_select_token(normalized_code) != key:
|
||||||
ip_limit["error"].add_ip(ip)
|
ip_limit["error"].add_ip(ip)
|
||||||
raise HTTPException(status_code=403, detail="下载鉴权失败")
|
raise HTTPException(status_code=403, detail="下载鉴权失败")
|
||||||
has, file_code = await get_code_file_by_code(code, False)
|
has, file_code = await get_code_file_by_code(normalized_code, False)
|
||||||
if not has:
|
if not has:
|
||||||
return APIResponse(code=404, detail="文件不存在")
|
return APIResponse(code=404, detail="文件不存在")
|
||||||
assert isinstance(file_code, FileCodes)
|
assert isinstance(file_code, FileCodes)
|
||||||
@@ -233,8 +323,31 @@ async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"]
|
|||||||
chunk_api = APIRouter(prefix="/chunk", tags=["切片"])
|
chunk_api = APIRouter(prefix="/chunk", tags=["切片"])
|
||||||
|
|
||||||
|
|
||||||
|
async def parse_body_model(request: Request, model_class: type[BaseModel]):
|
||||||
|
content_type = request.headers.get("content-type", "").lower()
|
||||||
|
try:
|
||||||
|
if "application/x-www-form-urlencoded" in content_type or "multipart/form-data" in content_type:
|
||||||
|
payload = dict(await request.form())
|
||||||
|
else:
|
||||||
|
payload = await request.json()
|
||||||
|
return model_class.model_validate(payload)
|
||||||
|
except ValidationError as e:
|
||||||
|
raise HTTPException(status_code=422, detail=e.errors())
|
||||||
|
except Exception:
|
||||||
|
raise HTTPException(status_code=400, detail="请求体格式错误")
|
||||||
|
|
||||||
|
|
||||||
|
async def parse_init_chunk_upload(request: Request) -> InitChunkUploadModel:
|
||||||
|
return await parse_body_model(request, InitChunkUploadModel)
|
||||||
|
|
||||||
|
|
||||||
|
async def parse_complete_upload(request: Request) -> CompleteUploadModel:
|
||||||
|
return await parse_body_model(request, CompleteUploadModel)
|
||||||
|
|
||||||
|
|
||||||
@chunk_api.post("/upload/init/", dependencies=[Depends(share_required_login)])
|
@chunk_api.post("/upload/init/", dependencies=[Depends(share_required_login)])
|
||||||
async def init_chunk_upload(data: InitChunkUploadModel):
|
async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chunk_upload)):
|
||||||
|
validate_file_type(data.file_name)
|
||||||
# 服务端校验:根据 total_chunks * chunk_size 计算理论最大上传量
|
# 服务端校验:根据 total_chunks * chunk_size 计算理论最大上传量
|
||||||
total_chunks = (data.file_size + data.chunk_size - 1) // data.chunk_size
|
total_chunks = (data.file_size + data.chunk_size - 1) // data.chunk_size
|
||||||
max_possible_size = total_chunks * data.chunk_size
|
max_possible_size = total_chunks * data.chunk_size
|
||||||
@@ -444,7 +557,9 @@ async def get_upload_status(upload_id: str):
|
|||||||
"/upload/complete/{upload_id}", dependencies=[Depends(share_required_login)]
|
"/upload/complete/{upload_id}", dependencies=[Depends(share_required_login)]
|
||||||
)
|
)
|
||||||
async def complete_upload(
|
async def complete_upload(
|
||||||
upload_id: str, data: CompleteUploadModel, ip: str = Depends(ip_limit["upload"])
|
upload_id: str,
|
||||||
|
data: CompleteUploadModel = Depends(parse_complete_upload),
|
||||||
|
ip: str = Depends(ip_limit["upload"]),
|
||||||
):
|
):
|
||||||
# 获取上传基本信息
|
# 获取上传基本信息
|
||||||
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
|
||||||
@@ -524,6 +639,14 @@ presign_api = APIRouter(prefix="/presign", tags=["预签名上传"])
|
|||||||
PRESIGN_SESSION_EXPIRES = 900 # 15分钟
|
PRESIGN_SESSION_EXPIRES = 900 # 15分钟
|
||||||
|
|
||||||
|
|
||||||
|
def build_proxy_upload_urls(upload_id: str) -> dict:
|
||||||
|
proxy_upload_url = f"/presign/upload/proxy/{upload_id}"
|
||||||
|
return {
|
||||||
|
"proxy_upload_url": proxy_upload_url,
|
||||||
|
"legacy_proxy_upload_url": f"/api{proxy_upload_url}",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
async def _get_valid_session(
|
async def _get_valid_session(
|
||||||
upload_id: str, expected_mode: Optional[str] = None
|
upload_id: str, expected_mode: Optional[str] = None
|
||||||
) -> PresignUploadSession:
|
) -> PresignUploadSession:
|
||||||
@@ -544,6 +667,7 @@ async def presign_upload_init(
|
|||||||
data: PresignUploadInitRequest, ip: str = Depends(ip_limit["upload"])
|
data: PresignUploadInitRequest, ip: str = Depends(ip_limit["upload"])
|
||||||
):
|
):
|
||||||
"""初始化预签名上传,S3返回直传URL,其他存储返回代理URL"""
|
"""初始化预签名上传,S3返回直传URL,其他存储返回代理URL"""
|
||||||
|
validate_file_type(data.file_name)
|
||||||
if data.file_size > settings.uploadSize:
|
if data.file_size > settings.uploadSize:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
403,
|
403,
|
||||||
@@ -563,7 +687,8 @@ async def presign_upload_init(
|
|||||||
)
|
)
|
||||||
|
|
||||||
mode = "direct" if presigned_url else "proxy"
|
mode = "direct" if presigned_url else "proxy"
|
||||||
upload_url = presigned_url or f"/api/presign/upload/proxy/{upload_id}"
|
proxy_urls = build_proxy_upload_urls(upload_id)
|
||||||
|
upload_url = presigned_url or proxy_urls["proxy_upload_url"]
|
||||||
|
|
||||||
await PresignUploadSession.create(
|
await PresignUploadSession.create(
|
||||||
upload_id=upload_id,
|
upload_id=upload_id,
|
||||||
@@ -577,13 +702,17 @@ async def presign_upload_init(
|
|||||||
)
|
)
|
||||||
|
|
||||||
ip_limit["upload"].add_ip(ip)
|
ip_limit["upload"].add_ip(ip)
|
||||||
|
detail = {
|
||||||
|
"upload_id": upload_id,
|
||||||
|
"upload_url": upload_url,
|
||||||
|
"mode": mode,
|
||||||
|
"expires_in": PRESIGN_SESSION_EXPIRES,
|
||||||
|
}
|
||||||
|
if mode == "proxy":
|
||||||
|
detail.update(proxy_urls)
|
||||||
|
|
||||||
return APIResponse(
|
return APIResponse(
|
||||||
detail={
|
detail=detail
|
||||||
"upload_id": upload_id,
|
|
||||||
"upload_url": upload_url,
|
|
||||||
"mode": mode,
|
|
||||||
"expires_in": PRESIGN_SESSION_EXPIRES,
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+114
@@ -0,0 +1,114 @@
|
|||||||
|
from apps.base.models import KeyValue
|
||||||
|
from apps.base.utils import ip_limit
|
||||||
|
from core.database import db_startup_lock
|
||||||
|
from core.logger import logger
|
||||||
|
from core.security import (
|
||||||
|
generate_jwt_secret,
|
||||||
|
is_config_initialized,
|
||||||
|
is_valid_jwt_secret,
|
||||||
|
prepare_security_config,
|
||||||
|
)
|
||||||
|
from core.settings import DEFAULT_CONFIG, settings
|
||||||
|
from core.utils import hash_password
|
||||||
|
|
||||||
|
|
||||||
|
MIN_ADMIN_PASSWORD_LENGTH = 8
|
||||||
|
SETUP_CONFIG_FIELDS = {
|
||||||
|
"allowed_file_types",
|
||||||
|
"code_generate_type",
|
||||||
|
"enableChunk",
|
||||||
|
"errorCount",
|
||||||
|
"errorMinute",
|
||||||
|
"expireStyle",
|
||||||
|
"max_save_seconds",
|
||||||
|
"name",
|
||||||
|
"openUpload",
|
||||||
|
"uploadCount",
|
||||||
|
"uploadMinute",
|
||||||
|
"uploadSize",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def ensure_settings_row() -> None:
|
||||||
|
initial_security = prepare_security_config(DEFAULT_CONFIG)
|
||||||
|
_, created = await KeyValue.get_or_create(
|
||||||
|
key="settings", defaults={"value": initial_security.config}
|
||||||
|
)
|
||||||
|
if created:
|
||||||
|
logger.warning(
|
||||||
|
"系统尚未初始化,请在浏览器中打开站点并完成管理员密码设置"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def ensure_security_settings() -> None:
|
||||||
|
config_record = await KeyValue.filter(key="settings").first()
|
||||||
|
if not config_record:
|
||||||
|
return
|
||||||
|
|
||||||
|
current_config = {**DEFAULT_CONFIG, **(config_record.value or {})}
|
||||||
|
security_config = prepare_security_config(current_config)
|
||||||
|
if not security_config.changed:
|
||||||
|
return
|
||||||
|
|
||||||
|
config_record.value = security_config.config
|
||||||
|
await config_record.save()
|
||||||
|
if security_config.setup_required:
|
||||||
|
logger.warning("检测到空密码或旧版默认管理员密码,请通过初始化页面重新设置")
|
||||||
|
elif security_config.password_hashed:
|
||||||
|
logger.info("已将管理员密码迁移为哈希存储")
|
||||||
|
if security_config.jwt_secret_rotated:
|
||||||
|
logger.info("已生成独立 JWT 签名密钥")
|
||||||
|
await refresh_settings()
|
||||||
|
|
||||||
|
|
||||||
|
def _sync_ip_limits() -> None:
|
||||||
|
ip_limit["error"].minutes = settings.errorMinute
|
||||||
|
ip_limit["error"].count = settings.errorCount
|
||||||
|
ip_limit["upload"].minutes = settings.uploadMinute
|
||||||
|
ip_limit["upload"].count = settings.uploadCount
|
||||||
|
|
||||||
|
|
||||||
|
async def refresh_settings() -> None:
|
||||||
|
"""从数据库读取最新配置并应用到运行时。"""
|
||||||
|
config_record = await KeyValue.filter(key="settings").first()
|
||||||
|
settings.user_config = config_record.value if config_record and config_record.value else {}
|
||||||
|
_sync_ip_limits()
|
||||||
|
|
||||||
|
|
||||||
|
def is_runtime_initialized() -> bool:
|
||||||
|
return is_config_initialized(dict(settings.items()))
|
||||||
|
|
||||||
|
|
||||||
|
async def initialize_system(
|
||||||
|
admin_password: str,
|
||||||
|
site_name: str | None = None,
|
||||||
|
setup_options: dict | None = None,
|
||||||
|
) -> None:
|
||||||
|
password = str(admin_password or "").strip()
|
||||||
|
if len(password) < MIN_ADMIN_PASSWORD_LENGTH:
|
||||||
|
raise ValueError(f"管理员密码至少需要 {MIN_ADMIN_PASSWORD_LENGTH} 位")
|
||||||
|
|
||||||
|
async with db_startup_lock():
|
||||||
|
config_record = await KeyValue.filter(key="settings").first()
|
||||||
|
current_config = {
|
||||||
|
**DEFAULT_CONFIG,
|
||||||
|
**(config_record.value if config_record and config_record.value else {}),
|
||||||
|
}
|
||||||
|
if is_config_initialized(current_config):
|
||||||
|
raise ValueError("系统已经初始化,请直接登录后台")
|
||||||
|
|
||||||
|
next_config = dict(current_config)
|
||||||
|
for key, value in (setup_options or {}).items():
|
||||||
|
if key in SETUP_CONFIG_FIELDS:
|
||||||
|
next_config[key] = value
|
||||||
|
|
||||||
|
normalized_site_name = str(site_name or "").strip()
|
||||||
|
if normalized_site_name:
|
||||||
|
next_config["name"] = normalized_site_name[:80]
|
||||||
|
|
||||||
|
next_config["admin_token"] = hash_password(password)
|
||||||
|
if not is_valid_jwt_secret(next_config.get("jwt_secret")):
|
||||||
|
next_config["jwt_secret"] = generate_jwt_secret()
|
||||||
|
|
||||||
|
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
|
||||||
|
await refresh_settings()
|
||||||
+83
-18
@@ -1,6 +1,9 @@
|
|||||||
|
import asyncio
|
||||||
import glob
|
import glob
|
||||||
import importlib
|
import importlib
|
||||||
import os
|
import os
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from typing import IO
|
||||||
|
|
||||||
from tortoise import Tortoise
|
from tortoise import Tortoise
|
||||||
|
|
||||||
@@ -8,29 +11,91 @@ from core.logger import logger
|
|||||||
from core.settings import data_root
|
from core.settings import data_root
|
||||||
|
|
||||||
|
|
||||||
|
_DB_FILE = os.path.join(data_root, "filecodebox.db")
|
||||||
|
_STARTUP_LOCK_FILE = os.path.join(data_root, "filecodebox.startup.lock")
|
||||||
|
|
||||||
|
|
||||||
|
def get_db_config() -> dict:
|
||||||
|
return {
|
||||||
|
"connections": {
|
||||||
|
"default": {
|
||||||
|
"engine": "tortoise.backends.sqlite",
|
||||||
|
"credentials": {
|
||||||
|
"file_path": _DB_FILE,
|
||||||
|
"journal_mode": "WAL",
|
||||||
|
"busy_timeout": 10000,
|
||||||
|
"foreign_keys": "ON",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"apps": {
|
||||||
|
"models": {
|
||||||
|
"models": ["apps.base.models"],
|
||||||
|
"default_connection": "default",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"use_tz": False,
|
||||||
|
"timezone": "Asia/Shanghai",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _lock_file(file_obj: IO[str]) -> None:
|
||||||
|
if os.name == "nt":
|
||||||
|
import msvcrt
|
||||||
|
|
||||||
|
# Windows 需要锁定至少 1 字节
|
||||||
|
if os.fstat(file_obj.fileno()).st_size == 0:
|
||||||
|
file_obj.write("0")
|
||||||
|
file_obj.flush()
|
||||||
|
msvcrt.locking(file_obj.fileno(), msvcrt.LK_LOCK, 1)
|
||||||
|
else:
|
||||||
|
import fcntl
|
||||||
|
|
||||||
|
fcntl.flock(file_obj.fileno(), fcntl.LOCK_EX)
|
||||||
|
|
||||||
|
|
||||||
|
def _unlock_file(file_obj: IO[str]) -> None:
|
||||||
|
if os.name == "nt":
|
||||||
|
import msvcrt
|
||||||
|
|
||||||
|
msvcrt.locking(file_obj.fileno(), msvcrt.LK_UNLCK, 1)
|
||||||
|
else:
|
||||||
|
import fcntl
|
||||||
|
|
||||||
|
fcntl.flock(file_obj.fileno(), fcntl.LOCK_UN)
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def db_startup_lock():
|
||||||
|
os.makedirs(data_root, exist_ok=True)
|
||||||
|
lock_file = open(_STARTUP_LOCK_FILE, "a+", encoding="utf-8")
|
||||||
|
try:
|
||||||
|
await asyncio.to_thread(_lock_file, lock_file)
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
await asyncio.to_thread(_unlock_file, lock_file)
|
||||||
|
lock_file.close()
|
||||||
|
|
||||||
|
|
||||||
async def init_db():
|
async def init_db():
|
||||||
try:
|
try:
|
||||||
# 使用正确的Tortoise初始化配置格式
|
db_config = get_db_config()
|
||||||
db_config = {
|
|
||||||
"db_url": f"sqlite://{data_root}/filecodebox.db",
|
|
||||||
"modules": {"models": ["apps.base.models"]},
|
|
||||||
"use_tz": False,
|
|
||||||
"timezone": "Asia/Shanghai"
|
|
||||||
}
|
|
||||||
|
|
||||||
await Tortoise.init(**db_config)
|
if not Tortoise._inited:
|
||||||
|
await Tortoise.init(config=db_config)
|
||||||
|
|
||||||
# 创建migrations表
|
async with db_startup_lock():
|
||||||
await Tortoise.get_connection("default").execute_script("""
|
# 创建migrations表
|
||||||
CREATE TABLE IF NOT EXISTS migrates (
|
await Tortoise.get_connection("default").execute_script("""
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
CREATE TABLE IF NOT EXISTS migrates (
|
||||||
migration_file VARCHAR(255) NOT NULL UNIQUE,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
migration_file VARCHAR(255) NOT NULL UNIQUE,
|
||||||
)
|
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
""")
|
)
|
||||||
|
""")
|
||||||
|
|
||||||
# 执行迁移
|
# 执行迁移
|
||||||
await execute_migrations()
|
await execute_migrations()
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"数据库初始化失败: {str(e)}")
|
logger.error(f"数据库初始化失败: {str(e)}")
|
||||||
|
|||||||
@@ -12,4 +12,9 @@ T = TypeVar("T")
|
|||||||
class APIResponse(BaseModel, Generic[T]):
|
class APIResponse(BaseModel, Generic[T]):
|
||||||
code: int = 200
|
code: int = 200
|
||||||
message: str = "ok"
|
message: str = "ok"
|
||||||
|
msg: Optional[str] = None
|
||||||
detail: Optional[T] = None
|
detail: Optional[T] = None
|
||||||
|
|
||||||
|
def model_post_init(self, __context) -> None:
|
||||||
|
if self.msg is None:
|
||||||
|
self.msg = self.message
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import copy
|
||||||
|
import secrets
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from core.utils import hash_password, is_password_hashed, verify_password
|
||||||
|
|
||||||
|
|
||||||
|
JWT_SECRET_MIN_LENGTH = 32
|
||||||
|
INTERNAL_CONFIG_KEYS = {"jwt_secret"}
|
||||||
|
LEGACY_DEFAULT_ADMIN_TOKEN = "FileCodeBox" + "2023"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SecurityConfigResult:
|
||||||
|
config: dict[str, Any]
|
||||||
|
changed: bool = False
|
||||||
|
password_hashed: bool = False
|
||||||
|
jwt_secret_rotated: bool = False
|
||||||
|
setup_required: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
def generate_jwt_secret() -> str:
|
||||||
|
return secrets.token_urlsafe(48)
|
||||||
|
|
||||||
|
|
||||||
|
def is_valid_jwt_secret(secret: Any) -> bool:
|
||||||
|
return isinstance(secret, str) and len(secret) >= JWT_SECRET_MIN_LENGTH
|
||||||
|
|
||||||
|
|
||||||
|
def is_config_initialized(config: dict[str, Any]) -> bool:
|
||||||
|
admin_token = str(config.get("admin_token") or "")
|
||||||
|
if not admin_token:
|
||||||
|
return False
|
||||||
|
return not verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token)
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_security_config(config: dict[str, Any]) -> SecurityConfigResult:
|
||||||
|
next_config = copy.deepcopy(config)
|
||||||
|
result = SecurityConfigResult(config=next_config)
|
||||||
|
|
||||||
|
admin_token = str(next_config.get("admin_token") or "")
|
||||||
|
if not admin_token:
|
||||||
|
result.setup_required = True
|
||||||
|
elif verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token):
|
||||||
|
next_config["admin_token"] = ""
|
||||||
|
result.setup_required = True
|
||||||
|
result.changed = True
|
||||||
|
elif not is_password_hashed(admin_token):
|
||||||
|
next_config["admin_token"] = hash_password(admin_token)
|
||||||
|
result.password_hashed = True
|
||||||
|
result.changed = True
|
||||||
|
|
||||||
|
jwt_secret = next_config.get("jwt_secret")
|
||||||
|
if not is_valid_jwt_secret(jwt_secret):
|
||||||
|
next_config["jwt_secret"] = generate_jwt_secret()
|
||||||
|
result.jwt_secret_rotated = True
|
||||||
|
result.changed = True
|
||||||
|
|
||||||
|
return result
|
||||||
+7
-2
@@ -26,6 +26,7 @@ DEFAULT_CONFIG = {
|
|||||||
"s3_region_name": "auto",
|
"s3_region_name": "auto",
|
||||||
"s3_signature_version": "s3v2",
|
"s3_signature_version": "s3v2",
|
||||||
"s3_hostname": "",
|
"s3_hostname": "",
|
||||||
|
"s3_addressing_style": "auto",
|
||||||
"s3_proxy": 0,
|
"s3_proxy": 0,
|
||||||
"max_save_seconds": 0,
|
"max_save_seconds": 0,
|
||||||
"aws_session_token": "",
|
"aws_session_token": "",
|
||||||
@@ -37,10 +38,13 @@ DEFAULT_CONFIG = {
|
|||||||
"onedrive_proxy": 0,
|
"onedrive_proxy": 0,
|
||||||
"webdav_root_path": "filebox_storage",
|
"webdav_root_path": "filebox_storage",
|
||||||
"webdav_proxy": 0,
|
"webdav_proxy": 0,
|
||||||
"admin_token": "FileCodeBox2023",
|
"admin_token": "",
|
||||||
|
"jwt_secret": "",
|
||||||
"openUpload": 1,
|
"openUpload": 1,
|
||||||
"uploadSize": 1024 * 1024 * 10,
|
"uploadSize": 1024 * 1024 * 10,
|
||||||
|
"allowed_file_types": ["*"],
|
||||||
"expireStyle": ["day", "hour", "minute", "forever", "count"],
|
"expireStyle": ["day", "hour", "minute", "forever", "count"],
|
||||||
|
"code_generate_type": "number",
|
||||||
"uploadMinute": 1,
|
"uploadMinute": 1,
|
||||||
"enableChunk": 0,
|
"enableChunk": 0,
|
||||||
"webdav_url": "",
|
"webdav_url": "",
|
||||||
@@ -65,12 +69,13 @@ DEFAULT_CONFIG = {
|
|||||||
],
|
],
|
||||||
"themesSelect": "themes/2024",
|
"themesSelect": "themes/2024",
|
||||||
"errorMinute": 1,
|
"errorMinute": 1,
|
||||||
"errorCount": 1,
|
"errorCount": 10,
|
||||||
"serverWorkers": 1,
|
"serverWorkers": 1,
|
||||||
"serverHost": "0.0.0.0",
|
"serverHost": "0.0.0.0",
|
||||||
"serverPort": 12345,
|
"serverPort": 12345,
|
||||||
"showAdminAddr": 0,
|
"showAdminAddr": 0,
|
||||||
"robotsText": "User-agent: *\nDisallow: /",
|
"robotsText": "User-agent: *\nDisallow: /",
|
||||||
|
"trustedProxies": [],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+51
-64
@@ -267,6 +267,7 @@ class S3FileStorage(FileStorageInterface):
|
|||||||
self.signature_version = settings.s3_signature_version
|
self.signature_version = settings.s3_signature_version
|
||||||
self.endpoint_url = settings.s3_endpoint_url or f"https://{self.s3_hostname}"
|
self.endpoint_url = settings.s3_endpoint_url or f"https://{self.s3_hostname}"
|
||||||
self.aws_session_token = settings.aws_session_token
|
self.aws_session_token = settings.aws_session_token
|
||||||
|
self.addressing_style = str(settings.s3_addressing_style or "auto").lower()
|
||||||
self.proxy = settings.s3_proxy
|
self.proxy = settings.s3_proxy
|
||||||
self.session = aioboto3.Session(
|
self.session = aioboto3.Session(
|
||||||
aws_access_key_id=self.access_key_id,
|
aws_access_key_id=self.access_key_id,
|
||||||
@@ -278,14 +279,26 @@ class S3FileStorage(FileStorageInterface):
|
|||||||
# 如果提供了 s3_endpoint_url,则优先使用它
|
# 如果提供了 s3_endpoint_url,则优先使用它
|
||||||
self.endpoint_url = settings.s3_endpoint_url
|
self.endpoint_url = settings.s3_endpoint_url
|
||||||
|
|
||||||
|
def _client_config(self) -> Config:
|
||||||
|
config = {"signature_version": self.signature_version}
|
||||||
|
s3_config = {}
|
||||||
|
if self.addressing_style in {"path", "virtual", "auto"}:
|
||||||
|
s3_config["addressing_style"] = self.addressing_style
|
||||||
|
if s3_config:
|
||||||
|
config["s3"] = s3_config
|
||||||
|
return Config(**config)
|
||||||
|
|
||||||
|
def _client(self):
|
||||||
|
return self.session.client(
|
||||||
|
"s3",
|
||||||
|
endpoint_url=self.endpoint_url,
|
||||||
|
aws_session_token=self.aws_session_token,
|
||||||
|
region_name=self.region_name,
|
||||||
|
config=self._client_config(),
|
||||||
|
)
|
||||||
|
|
||||||
async def save_file(self, file: UploadFile, save_path: str):
|
async def save_file(self, file: UploadFile, save_path: str):
|
||||||
async with self.session.client(
|
async with self._client() as s3:
|
||||||
"s3",
|
|
||||||
endpoint_url=self.endpoint_url,
|
|
||||||
aws_session_token=self.aws_session_token,
|
|
||||||
region_name=self.region_name,
|
|
||||||
config=Config(signature_version=self.signature_version),
|
|
||||||
) as s3:
|
|
||||||
# 使用 upload_fileobj 流式上传,避免将整个文件加载到内存
|
# 使用 upload_fileobj 流式上传,避免将整个文件加载到内存
|
||||||
await s3.upload_fileobj(
|
await s3.upload_fileobj(
|
||||||
file.file,
|
file.file,
|
||||||
@@ -295,12 +308,7 @@ class S3FileStorage(FileStorageInterface):
|
|||||||
)
|
)
|
||||||
|
|
||||||
async def delete_file(self, file_code: FileCodes):
|
async def delete_file(self, file_code: FileCodes):
|
||||||
async with self.session.client(
|
async with self._client() as s3:
|
||||||
"s3",
|
|
||||||
endpoint_url=self.endpoint_url,
|
|
||||||
region_name=self.region_name,
|
|
||||||
config=Config(signature_version=self.signature_version),
|
|
||||||
) as s3:
|
|
||||||
await s3.delete_object(
|
await s3.delete_object(
|
||||||
Bucket=self.bucket_name, Key=await file_code.get_file_path()
|
Bucket=self.bucket_name, Key=await file_code.get_file_path()
|
||||||
)
|
)
|
||||||
@@ -310,12 +318,7 @@ class S3FileStorage(FileStorageInterface):
|
|||||||
filename = file_code.prefix + file_code.suffix
|
filename = file_code.prefix + file_code.suffix
|
||||||
content_length = None # 初始化为 None,表示未知大小
|
content_length = None # 初始化为 None,表示未知大小
|
||||||
|
|
||||||
async with self.session.client(
|
async with self._client() as s3:
|
||||||
"s3",
|
|
||||||
endpoint_url=self.endpoint_url,
|
|
||||||
region_name=self.region_name,
|
|
||||||
config=Config(signature_version=self.signature_version),
|
|
||||||
) as s3:
|
|
||||||
# 尝试获取文件大小(HEAD请求)
|
# 尝试获取文件大小(HEAD请求)
|
||||||
try:
|
try:
|
||||||
head_response = await s3.head_object(
|
head_response = await s3.head_object(
|
||||||
@@ -384,12 +387,7 @@ class S3FileStorage(FileStorageInterface):
|
|||||||
if self.proxy:
|
if self.proxy:
|
||||||
return await get_file_url(file_code.code)
|
return await get_file_url(file_code.code)
|
||||||
else:
|
else:
|
||||||
async with self.session.client(
|
async with self._client() as s3:
|
||||||
"s3",
|
|
||||||
endpoint_url=self.endpoint_url,
|
|
||||||
region_name=self.region_name,
|
|
||||||
config=Config(signature_version=self.signature_version),
|
|
||||||
) as s3:
|
|
||||||
result = await s3.generate_presigned_url(
|
result = await s3.generate_presigned_url(
|
||||||
"get_object",
|
"get_object",
|
||||||
Params={
|
Params={
|
||||||
@@ -406,13 +404,7 @@ class S3FileStorage(FileStorageInterface):
|
|||||||
注意:这里不使用 S3 原生的 multipart upload,而是将每个分片作为独立对象存储
|
注意:这里不使用 S3 原生的 multipart upload,而是将每个分片作为独立对象存储
|
||||||
"""
|
"""
|
||||||
chunk_key = str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
|
chunk_key = str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
|
||||||
async with self.session.client(
|
async with self._client() as s3:
|
||||||
's3',
|
|
||||||
endpoint_url=self.endpoint_url,
|
|
||||||
aws_session_token=self.aws_session_token,
|
|
||||||
region_name=self.region_name,
|
|
||||||
config=Config(signature_version=self.signature_version),
|
|
||||||
) as s3:
|
|
||||||
# 将分片作为独立对象上传
|
# 将分片作为独立对象上传
|
||||||
await s3.put_object(
|
await s3.put_object(
|
||||||
Bucket=self.bucket_name,
|
Bucket=self.bucket_name,
|
||||||
@@ -432,13 +424,7 @@ class S3FileStorage(FileStorageInterface):
|
|||||||
file_sha256 = hashlib.sha256()
|
file_sha256 = hashlib.sha256()
|
||||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||||
|
|
||||||
async with self.session.client(
|
async with self._client() as s3:
|
||||||
's3',
|
|
||||||
endpoint_url=self.endpoint_url,
|
|
||||||
aws_session_token=self.aws_session_token,
|
|
||||||
region_name=self.region_name,
|
|
||||||
config=Config(signature_version=self.signature_version),
|
|
||||||
) as s3:
|
|
||||||
# 创建 multipart upload
|
# 创建 multipart upload
|
||||||
mpu = await s3.create_multipart_upload(
|
mpu = await s3.create_multipart_upload(
|
||||||
Bucket=self.bucket_name,
|
Bucket=self.bucket_name,
|
||||||
@@ -512,13 +498,7 @@ class S3FileStorage(FileStorageInterface):
|
|||||||
:param save_path: 文件保存路径
|
:param save_path: 文件保存路径
|
||||||
"""
|
"""
|
||||||
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
chunk_dir = str(Path(save_path).parent / "chunks" / upload_id)
|
||||||
async with self.session.client(
|
async with self._client() as s3:
|
||||||
's3',
|
|
||||||
endpoint_url=self.endpoint_url,
|
|
||||||
aws_session_token=self.aws_session_token,
|
|
||||||
region_name=self.region_name,
|
|
||||||
config=Config(signature_version=self.signature_version),
|
|
||||||
) as s3:
|
|
||||||
try:
|
try:
|
||||||
# 列出并删除所有分片对象
|
# 列出并删除所有分片对象
|
||||||
paginator = s3.get_paginator('list_objects_v2')
|
paginator = s3.get_paginator('list_objects_v2')
|
||||||
@@ -540,13 +520,7 @@ class S3FileStorage(FileStorageInterface):
|
|||||||
:param expires_in: URL过期时间(秒),默认15分钟
|
:param expires_in: URL过期时间(秒),默认15分钟
|
||||||
:return: 预签名PUT URL
|
:return: 预签名PUT URL
|
||||||
"""
|
"""
|
||||||
async with self.session.client(
|
async with self._client() as s3:
|
||||||
"s3",
|
|
||||||
endpoint_url=self.endpoint_url,
|
|
||||||
aws_session_token=self.aws_session_token,
|
|
||||||
region_name=self.region_name,
|
|
||||||
config=Config(signature_version=self.signature_version),
|
|
||||||
) as s3:
|
|
||||||
return await s3.generate_presigned_url(
|
return await s3.generate_presigned_url(
|
||||||
"put_object",
|
"put_object",
|
||||||
Params={
|
Params={
|
||||||
@@ -562,18 +536,31 @@ class S3FileStorage(FileStorageInterface):
|
|||||||
:param save_path: 文件路径
|
:param save_path: 文件路径
|
||||||
:return: 文件是否存在
|
:return: 文件是否存在
|
||||||
"""
|
"""
|
||||||
async with self.session.client(
|
async with self._client() as s3:
|
||||||
"s3",
|
last_error = None
|
||||||
endpoint_url=self.endpoint_url,
|
for attempt in range(3):
|
||||||
aws_session_token=self.aws_session_token,
|
try:
|
||||||
region_name=self.region_name,
|
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
|
||||||
config=Config(signature_version=self.signature_version),
|
return True
|
||||||
) as s3:
|
except Exception as e:
|
||||||
|
last_error = e
|
||||||
|
if attempt < 2:
|
||||||
|
await asyncio.sleep(0.2 * (attempt + 1))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await s3.head_object(Bucket=self.bucket_name, Key=save_path)
|
result = await s3.list_objects_v2(
|
||||||
return True
|
Bucket=self.bucket_name,
|
||||||
except Exception:
|
Prefix=save_path,
|
||||||
return False
|
MaxKeys=1,
|
||||||
|
)
|
||||||
|
for item in result.get("Contents", []):
|
||||||
|
if item.get("Key") == save_path:
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
last_error = e
|
||||||
|
|
||||||
|
logger.warning(f"S3文件确认失败 key={save_path}: {last_error}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
class OneDriveFileStorage(FileStorageInterface):
|
class OneDriveFileStorage(FileStorageInterface):
|
||||||
|
|||||||
+6
-3
@@ -11,15 +11,17 @@ from tortoise.expressions import Q
|
|||||||
|
|
||||||
from apps.base.models import FileCodes, UploadChunk
|
from apps.base.models import FileCodes, UploadChunk
|
||||||
from apps.base.utils import ip_limit, get_chunk_file_path_name
|
from apps.base.utils import ip_limit, get_chunk_file_path_name
|
||||||
|
from core.config import refresh_settings
|
||||||
from core.settings import settings, data_root
|
from core.settings import settings, data_root
|
||||||
from core.storage import FileStorageInterface, storages
|
from core.storage import FileStorageInterface, storages
|
||||||
from core.utils import get_now
|
from core.utils import get_now
|
||||||
|
|
||||||
|
|
||||||
async def delete_expire_files():
|
async def delete_expire_files():
|
||||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
|
await refresh_settings()
|
||||||
|
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||||
# 遍历 share目录下的所有文件夹,删除空的文件夹,并判断父目录是否为空,如果为空也删除
|
# 遍历 share目录下的所有文件夹,删除空的文件夹,并判断父目录是否为空,如果为空也删除
|
||||||
if settings.file_storage == "local":
|
if settings.file_storage == "local":
|
||||||
for root, dirs, files in os.walk(f"{data_root}/share/data"):
|
for root, dirs, files in os.walk(f"{data_root}/share/data"):
|
||||||
@@ -46,10 +48,11 @@ async def delete_expire_files():
|
|||||||
|
|
||||||
|
|
||||||
async def clean_incomplete_uploads():
|
async def clean_incomplete_uploads():
|
||||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
|
||||||
expire_hours = getattr(settings, "chunk_expire_hours", 24)
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
|
await refresh_settings()
|
||||||
|
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||||
|
expire_hours = getattr(settings, "chunk_expire_hours", 24)
|
||||||
now = await get_now()
|
now = await get_now()
|
||||||
expire_time = now - datetime.timedelta(hours=expire_hours)
|
expire_time = now - datetime.timedelta(hours=expire_hours)
|
||||||
expired_sessions = await UploadChunk.filter(
|
expired_sessions = await UploadChunk.filter(
|
||||||
|
|||||||
+6
-4
@@ -5,8 +5,8 @@
|
|||||||
import datetime
|
import datetime
|
||||||
import hashlib
|
import hashlib
|
||||||
import os
|
import os
|
||||||
import random
|
|
||||||
import re
|
import re
|
||||||
|
import secrets
|
||||||
import string
|
import string
|
||||||
import time
|
import time
|
||||||
|
|
||||||
@@ -18,7 +18,7 @@ async def get_random_num():
|
|||||||
获取随机数
|
获取随机数
|
||||||
:return:
|
:return:
|
||||||
"""
|
"""
|
||||||
return random.randint(10000, 99999)
|
return secrets.randbelow(90000) + 10000
|
||||||
|
|
||||||
|
|
||||||
r_s = string.ascii_uppercase + string.digits
|
r_s = string.ascii_uppercase + string.digits
|
||||||
@@ -29,7 +29,7 @@ async def get_random_string():
|
|||||||
获取随机字符串
|
获取随机字符串
|
||||||
:return:
|
:return:
|
||||||
"""
|
"""
|
||||||
return "".join(random.choice(r_s) for _ in range(5))
|
return "".join(secrets.choice(r_s) for _ in range(5))
|
||||||
|
|
||||||
|
|
||||||
async def get_now():
|
async def get_now():
|
||||||
@@ -46,7 +46,9 @@ async def get_select_token(code: str):
|
|||||||
:param code:
|
:param code:
|
||||||
:return:
|
:return:
|
||||||
"""
|
"""
|
||||||
token = settings.admin_token
|
token = getattr(settings, "jwt_secret", "")
|
||||||
|
if not token:
|
||||||
|
raise RuntimeError("应用签名密钥未初始化")
|
||||||
return hashlib.sha256(
|
return hashlib.sha256(
|
||||||
f"{code}{int(time.time() / 1000)}000{token}".encode()
|
f"{code}{int(time.time() / 1000)}000{token}".encode()
|
||||||
).hexdigest()
|
).hexdigest()
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
APP_VERSION = "2.4.0"
|
||||||
+2
-2
@@ -22,7 +22,7 @@ Authorization: Bearer <token>
|
|||||||
```bash
|
```bash
|
||||||
curl -X POST "http://localhost:12345/admin/login" \
|
curl -X POST "http://localhost:12345/admin/login" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{"password": "FileCodeBox2023"}'
|
-d '{"password": "<初始化时设置的管理员密码>"}'
|
||||||
```
|
```
|
||||||
|
|
||||||
**响应示例:**
|
**响应示例:**
|
||||||
@@ -329,4 +329,4 @@ curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file
|
|||||||
- 403: 禁止访问
|
- 403: 禁止访问
|
||||||
- 404: 资源不存在
|
- 404: 资源不存在
|
||||||
- 422: 请求参数验证错误
|
- 422: 请求参数验证错误
|
||||||
- 500: 服务器内部错误
|
- 500: 服务器内部错误
|
||||||
@@ -22,7 +22,7 @@ When guest upload is disabled in admin panel (`openUpload=0`), you need to login
|
|||||||
```bash
|
```bash
|
||||||
curl -X POST "http://localhost:12345/admin/login" \
|
curl -X POST "http://localhost:12345/admin/login" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{"password": "FileCodeBox2023"}'
|
-d '{"password": "<admin-password-set-during-setup>"}'
|
||||||
```
|
```
|
||||||
|
|
||||||
**Response Example:**
|
**Response Example:**
|
||||||
@@ -329,4 +329,4 @@ When an error occurs, the API will return corresponding error message:
|
|||||||
- 403: Forbidden
|
- 403: Forbidden
|
||||||
- 404: Not Found
|
- 404: Not Found
|
||||||
- 422: Validation Error
|
- 422: Validation Error
|
||||||
- 500: Internal Server Error
|
- 500: Internal Server Error
|
||||||
@@ -109,11 +109,11 @@ Default available themes:
|
|||||||
|
|
||||||
| Setting | Type | Default | Description |
|
| Setting | Type | Default | Description |
|
||||||
|---------|------|---------|-------------|
|
|---------|------|---------|-------------|
|
||||||
| `admin_token` | string | `FileCodeBox2023` | Admin login password |
|
| `admin_token` | string | Set during setup | Admin login password |
|
||||||
| `showAdminAddr` | int | `0` | Show admin panel entry on homepage (1=show, 0=hide) |
|
| `showAdminAddr` | int | `0` | Show admin panel entry on homepage (1=show, 0=hide) |
|
||||||
|
|
||||||
::: danger Security Warning
|
::: danger Security Warning
|
||||||
Always change the default `admin_token` in production environments! Using the default password poses serious security risks.
|
The setup page is shown automatically while the system is uninitialized. Complete setup before exposing a production service to the public internet.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
## Security Settings
|
## Security Settings
|
||||||
|
|||||||
@@ -55,8 +55,9 @@ python main.py
|
|||||||
- Download file
|
- Download file
|
||||||
|
|
||||||
4. Admin Panel
|
4. Admin Panel
|
||||||
|
- Open `http://localhost:12345` on first run and complete setup
|
||||||
- Visit `http://localhost:12345/#/admin`
|
- Visit `http://localhost:12345/#/admin`
|
||||||
- Enter admin password: `FileCodeBox2023`
|
- Enter the admin password set during setup
|
||||||
- Enter admin panel
|
- Enter admin panel
|
||||||
- View system information, file list, user management, etc.
|
- View system information, file list, user management, etc.
|
||||||
|
|
||||||
@@ -64,4 +65,4 @@ python main.py
|
|||||||
|
|
||||||
- [Storage Configuration](/en/guide/storage) - Learn how to configure different storage methods
|
- [Storage Configuration](/en/guide/storage) - Learn how to configure different storage methods
|
||||||
- [Security Settings](/en/guide/security) - Learn how to enhance system security
|
- [Security Settings](/en/guide/security) - Learn how to enhance system security
|
||||||
- [API Documentation](/en/api/) - Learn how to integrate through API
|
- [API Documentation](/en/api/) - Learn how to integrate through API
|
||||||
@@ -8,12 +8,13 @@ FileCodeBox provides a fully-featured admin panel that allows administrators to
|
|||||||
|
|
||||||
The admin panel is located at the `/admin` path. Access method:
|
The admin panel is located at the `/admin` path. Access method:
|
||||||
|
|
||||||
1. Visit `http://your-domain.com/admin` in your browser
|
1. On first run, set the admin password on the setup page
|
||||||
2. Enter the admin password (the value of the `admin_token` configuration)
|
2. Visit `http://your-domain.com/admin` in your browser
|
||||||
3. Click the login button
|
3. Enter the admin password (the value of the `admin_token` configuration)
|
||||||
|
4. Click the login button
|
||||||
|
|
||||||
::: tip Tip
|
::: tip Tip
|
||||||
The default admin password is `FileCodeBox2023`. Be sure to change this password in production environments. See [Security Settings](/en/guide/security) for details.
|
The setup page is shown automatically while the system is uninitialized. Complete setup before exposing a production service to the public internet.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
### Show Admin Entry
|
### Show Admin Entry
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ FileCodeBox provides multiple layers of security mechanisms to protect your file
|
|||||||
|
|
||||||
## Admin Password
|
## Admin Password
|
||||||
|
|
||||||
### Change Default Password
|
### First-Run Setup
|
||||||
|
|
||||||
::: danger Important Security Warning
|
::: danger Important Security Warning
|
||||||
FileCodeBox's default admin password is `FileCodeBox2023`. **You must change this password immediately in production environments!** Using the default password allows anyone to access your admin panel.
|
FileCodeBox does not ship with a default admin password. Open the site in your browser on first run and set the admin password on the setup page.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
There are two ways to change the admin password:
|
There are two ways to change the admin password:
|
||||||
@@ -272,7 +272,7 @@ your-domain.com {
|
|||||||
|
|
||||||
Before deploying FileCodeBox, confirm the following security configurations:
|
Before deploying FileCodeBox, confirm the following security configurations:
|
||||||
|
|
||||||
- [ ] Changed default admin password `admin_token`
|
- [ ] Completed first-run setup and set the admin password `admin_token`
|
||||||
- [ ] Hidden admin entry `showAdminAddr: 0`
|
- [ ] Hidden admin entry `showAdminAddr: 0`
|
||||||
- [ ] Configured appropriate upload rate limiting
|
- [ ] Configured appropriate upload rate limiting
|
||||||
- [ ] Configured error rate limiting to prevent brute-force attacks
|
- [ ] Configured error rate limiting to prevent brute-force attacks
|
||||||
|
|||||||
@@ -149,7 +149,7 @@ If guest upload is disabled in admin panel (`openUpload=0`), you need to login f
|
|||||||
# 1. Login to get token
|
# 1. Login to get token
|
||||||
curl -X POST "http://localhost:12345/admin/login" \
|
curl -X POST "http://localhost:12345/admin/login" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{"password": "FileCodeBox2023"}'
|
-d '{"password": "<admin-password-set-during-setup>"}'
|
||||||
|
|
||||||
# Returns: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
|
# Returns: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
|
||||||
|
|
||||||
|
|||||||
@@ -108,11 +108,11 @@ FileCodeBox 支持两种配置方式:
|
|||||||
|
|
||||||
| 配置项 | 类型 | 默认值 | 说明 |
|
| 配置项 | 类型 | 默认值 | 说明 |
|
||||||
|--------|------|--------|------|
|
|--------|------|--------|------|
|
||||||
| `admin_token` | string | `FileCodeBox2023` | 管理员登录密码 |
|
| `admin_token` | string | 初始化页面设置 | 管理员登录密码(哈希存储) |
|
||||||
| `showAdminAddr` | int | `0` | 是否在首页显示管理入口(1=显示,0=隐藏) |
|
| `showAdminAddr` | int | `0` | 是否在首页显示管理入口(1=显示,0=隐藏) |
|
||||||
|
|
||||||
::: danger 安全警告
|
::: danger 安全警告
|
||||||
请务必在生产环境中修改默认的 `admin_token`!使用默认密码会导致严重的安全风险。
|
未初始化时会自动显示初始化页面。生产环境请在服务对外开放前完成初始化。
|
||||||
:::
|
:::
|
||||||
|
|
||||||
## 安全设置
|
## 安全设置
|
||||||
|
|||||||
@@ -109,8 +109,9 @@ python main.py
|
|||||||
- 下载文件
|
- 下载文件
|
||||||
|
|
||||||
4. 后台管理
|
4. 后台管理
|
||||||
|
- 首次访问 `http://localhost:12345` 完成初始化
|
||||||
- 访问 `http://localhost:12345/#/admin`
|
- 访问 `http://localhost:12345/#/admin`
|
||||||
- 输入管理员密码:`FileCodeBox2023`
|
- 输入初始化时设置的管理员密码
|
||||||
- 进入后台管理页面
|
- 进入后台管理页面
|
||||||
- 查看系统信息、文件列表、用户管理等
|
- 查看系统信息、文件列表、用户管理等
|
||||||
|
|
||||||
@@ -118,4 +119,4 @@ python main.py
|
|||||||
|
|
||||||
- [存储配置](/guide/storage) - 了解如何配置不同的存储方式
|
- [存储配置](/guide/storage) - 了解如何配置不同的存储方式
|
||||||
- [安全设置](/guide/security) - 了解如何增强系统安全性
|
- [安全设置](/guide/security) - 了解如何增强系统安全性
|
||||||
- [API 文档](/api/) - 了解如何通过 API 集成
|
- [API 文档](/api/) - 了解如何通过 API 集成
|
||||||
@@ -8,12 +8,13 @@ FileCodeBox 提供了功能完善的管理面板,让管理员可以方便地
|
|||||||
|
|
||||||
管理面板位于 `/admin` 路径。访问方式:
|
管理面板位于 `/admin` 路径。访问方式:
|
||||||
|
|
||||||
1. 在浏览器中访问 `http://your-domain.com/admin`
|
1. 首次访问站点时,按初始化页面设置管理员密码
|
||||||
2. 输入管理员密码(`admin_token` 配置项的值)
|
2. 在浏览器中访问 `http://your-domain.com/admin`
|
||||||
3. 点击登录按钮
|
3. 输入管理员密码(`admin_token` 配置项的值)
|
||||||
|
4. 点击登录按钮
|
||||||
|
|
||||||
::: tip 提示
|
::: tip 提示
|
||||||
默认管理员密码是 `FileCodeBox2023`。请务必在生产环境中修改此密码,详见 [安全设置](/guide/security)。
|
未初始化时会自动进入初始化页面。生产环境请先完成初始化,再开放公网访问。
|
||||||
:::
|
:::
|
||||||
|
|
||||||
### 显示管理入口
|
### 显示管理入口
|
||||||
@@ -384,7 +385,7 @@ Content-Type: application/json
|
|||||||
-- 查看当前配置
|
-- 查看当前配置
|
||||||
SELECT * FROM keyvalue WHERE key = 'settings';
|
SELECT * FROM keyvalue WHERE key = 'settings';
|
||||||
|
|
||||||
-- 或者删除配置,恢复默认密码
|
-- 或者删除配置,重启后重新进入初始化流程
|
||||||
DELETE FROM keyvalue WHERE key = 'settings';
|
DELETE FROM keyvalue WHERE key = 'settings';
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ FileCodeBox 提供了多层安全机制来保护您的文件分享服务。本
|
|||||||
|
|
||||||
## 管理员密码
|
## 管理员密码
|
||||||
|
|
||||||
### 修改默认密码
|
### 首次初始化
|
||||||
|
|
||||||
::: danger 重要安全警告
|
::: danger 重要安全警告
|
||||||
FileCodeBox 的默认管理员密码是 `FileCodeBox2023`。**在生产环境中必须立即修改此密码!**使用默认密码会导致任何人都可以访问您的管理面板。
|
FileCodeBox 首次启动时不会生成默认管理员密码。请在浏览器中打开站点,按初始化页面设置管理员密码,并妥善保存。
|
||||||
:::
|
:::
|
||||||
|
|
||||||
修改管理员密码有两种方式:
|
修改管理员密码有两种方式:
|
||||||
@@ -271,7 +271,7 @@ your-domain.com {
|
|||||||
|
|
||||||
部署 FileCodeBox 前,请确认以下安全配置:
|
部署 FileCodeBox 前,请确认以下安全配置:
|
||||||
|
|
||||||
- [ ] 已修改默认管理员密码 `admin_token`
|
- [ ] 已完成首次初始化并设置管理员密码 `admin_token`
|
||||||
- [ ] 已隐藏管理入口 `showAdminAddr: 0`
|
- [ ] 已隐藏管理入口 `showAdminAddr: 0`
|
||||||
- [ ] 已配置合适的上传频率限制
|
- [ ] 已配置合适的上传频率限制
|
||||||
- [ ] 已配置错误次数限制防止暴力破解
|
- [ ] 已配置错误次数限制防止暴力破解
|
||||||
|
|||||||
@@ -149,7 +149,7 @@ curl -L "http://localhost:12345/share/select/?code=取件码" -o downloaded_file
|
|||||||
# 1. 登录获取 token
|
# 1. 登录获取 token
|
||||||
curl -X POST "http://localhost:12345/admin/login" \
|
curl -X POST "http://localhost:12345/admin/login" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{"password": "FileCodeBox2023"}'
|
-d '{"password": "<初始化时设置的管理员密码>"}'
|
||||||
|
|
||||||
# 返回: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
|
# 返回: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
|
||||||
|
|
||||||
|
|||||||
@@ -3,13 +3,14 @@
|
|||||||
# @File : main.py
|
# @File : main.py
|
||||||
# @Software: PyCharm
|
# @Software: PyCharm
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import html
|
||||||
import time
|
import time
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
|
from urllib.parse import parse_qs
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI, HTTPException, Request
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import HTMLResponse
|
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse
|
||||||
from fastapi.staticfiles import StaticFiles
|
|
||||||
from tortoise import Tortoise
|
from tortoise import Tortoise
|
||||||
from tortoise.contrib.fastapi import register_tortoise
|
from tortoise.contrib.fastapi import register_tortoise
|
||||||
|
|
||||||
@@ -17,12 +18,671 @@ from apps.admin.views import admin_api
|
|||||||
from apps.base.models import KeyValue
|
from apps.base.models import KeyValue
|
||||||
from apps.base.utils import ip_limit
|
from apps.base.utils import ip_limit
|
||||||
from apps.base.views import share_api, chunk_api, presign_api
|
from apps.base.views import share_api, chunk_api, presign_api
|
||||||
from core.database import init_db
|
from core.config import (
|
||||||
|
ensure_security_settings,
|
||||||
|
ensure_settings_row,
|
||||||
|
initialize_system,
|
||||||
|
is_runtime_initialized,
|
||||||
|
refresh_settings,
|
||||||
|
)
|
||||||
|
from core.database import db_startup_lock, get_db_config, init_db
|
||||||
from core.logger import logger
|
from core.logger import logger
|
||||||
from core.response import APIResponse
|
from core.response import APIResponse
|
||||||
from core.settings import data_root, settings, BASE_DIR, DEFAULT_CONFIG
|
from core.settings import settings, BASE_DIR, DEFAULT_CONFIG
|
||||||
from core.tasks import delete_expire_files, clean_incomplete_uploads
|
from core.tasks import delete_expire_files, clean_incomplete_uploads
|
||||||
from core.utils import hash_password, is_password_hashed
|
from core.version import APP_VERSION
|
||||||
|
|
||||||
|
|
||||||
|
def build_public_config() -> dict:
|
||||||
|
return {
|
||||||
|
"name": settings.name,
|
||||||
|
"description": settings.description,
|
||||||
|
"explain": settings.page_explain,
|
||||||
|
"uploadSize": settings.uploadSize,
|
||||||
|
"allowedFileTypes": settings.allowed_file_types,
|
||||||
|
"expireStyle": settings.expireStyle,
|
||||||
|
"enableChunk": settings.enableChunk,
|
||||||
|
"openUpload": settings.openUpload,
|
||||||
|
"notify_title": settings.notify_title,
|
||||||
|
"notify_content": settings.notify_content,
|
||||||
|
"show_admin_address": settings.showAdminAddr,
|
||||||
|
"max_save_seconds": settings.max_save_seconds,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_public_meta() -> dict:
|
||||||
|
return {
|
||||||
|
"version": APP_VERSION,
|
||||||
|
"api": {
|
||||||
|
"legacyConfig": "/",
|
||||||
|
"publicConfig": "/api/v1/config",
|
||||||
|
"health": "/health",
|
||||||
|
},
|
||||||
|
"features": {
|
||||||
|
"chunkUpload": bool(settings.enableChunk),
|
||||||
|
"guestUpload": bool(settings.openUpload),
|
||||||
|
"adminAddressVisible": bool(settings.showAdminAddr),
|
||||||
|
"expirationModes": settings.expireStyle,
|
||||||
|
},
|
||||||
|
"limits": {
|
||||||
|
"uploadSize": settings.uploadSize,
|
||||||
|
"allowedFileTypes": settings.allowed_file_types,
|
||||||
|
"maxSaveSeconds": settings.max_save_seconds,
|
||||||
|
"uploadWindowMinutes": settings.uploadMinute,
|
||||||
|
"uploadWindowCount": settings.uploadCount,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
FILE_SIZE_UNITS = {"KB": 1024, "MB": 1024**2, "GB": 1024**3}
|
||||||
|
SAVE_TIME_UNITS = {"second": 1, "minute": 60, "hour": 3600, "day": 86400}
|
||||||
|
EXPIRE_STYLE_OPTIONS = [
|
||||||
|
("day", "按天"),
|
||||||
|
("hour", "按小时"),
|
||||||
|
("minute", "按分钟"),
|
||||||
|
("forever", "永久"),
|
||||||
|
("count", "按取件次数"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def get_form_value(data: dict, key: str, default: str = "") -> str:
|
||||||
|
value = data.get(key, default)
|
||||||
|
if isinstance(value, list):
|
||||||
|
value = value[-1] if value else default
|
||||||
|
return str(value if value is not None else default)
|
||||||
|
|
||||||
|
|
||||||
|
def get_form_list(data: dict, key: str) -> list[str]:
|
||||||
|
value = data.get(key, [])
|
||||||
|
if isinstance(value, list):
|
||||||
|
return [str(item) for item in value if str(item)]
|
||||||
|
if value:
|
||||||
|
return [str(value)]
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_bool_field(data: dict, key: str, default: bool) -> bool:
|
||||||
|
if key not in data:
|
||||||
|
return default
|
||||||
|
return get_form_value(data, key).lower() in {"1", "true", "on", "yes"}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_int_field(
|
||||||
|
data: dict,
|
||||||
|
key: str,
|
||||||
|
default: int,
|
||||||
|
label: str,
|
||||||
|
min_value: int = 0,
|
||||||
|
max_value: int | None = None,
|
||||||
|
) -> int:
|
||||||
|
raw_value = get_form_value(data, key, str(default)).strip()
|
||||||
|
try:
|
||||||
|
value = int(raw_value)
|
||||||
|
except ValueError:
|
||||||
|
raise ValueError(f"{label} 必须是整数")
|
||||||
|
if value < min_value:
|
||||||
|
raise ValueError(f"{label} 不能小于 {min_value}")
|
||||||
|
if max_value is not None and value > max_value:
|
||||||
|
raise ValueError(f"{label} 不能大于 {max_value}")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def parse_allowed_file_types(value: str) -> list[str]:
|
||||||
|
items = [item.strip() for item in value.split(",") if item.strip()]
|
||||||
|
return items or ["*"]
|
||||||
|
|
||||||
|
|
||||||
|
def parse_setup_options(data: dict) -> dict:
|
||||||
|
upload_size_unit = get_form_value(data, "upload_size_unit", "MB").upper()
|
||||||
|
if upload_size_unit not in FILE_SIZE_UNITS:
|
||||||
|
raise ValueError("文件大小单位不正确")
|
||||||
|
upload_size_value = parse_int_field(
|
||||||
|
data, "upload_size_value", 10, "文件大小限制", min_value=1
|
||||||
|
)
|
||||||
|
|
||||||
|
save_time_unit = get_form_value(data, "save_time_unit", "day")
|
||||||
|
if save_time_unit not in SAVE_TIME_UNITS:
|
||||||
|
raise ValueError("最长保存时间单位不正确")
|
||||||
|
save_time_value = parse_int_field(
|
||||||
|
data, "save_time_value", 0, "最长保存时间", min_value=0
|
||||||
|
)
|
||||||
|
|
||||||
|
expire_styles = get_form_list(data, "expireStyle")
|
||||||
|
valid_expire_styles = {style for style, _label in EXPIRE_STYLE_OPTIONS}
|
||||||
|
expire_styles = [style for style in expire_styles if style in valid_expire_styles]
|
||||||
|
if not expire_styles:
|
||||||
|
raise ValueError("至少需要选择一种过期方式")
|
||||||
|
|
||||||
|
code_generate_type = get_form_value(data, "code_generate_type", "number")
|
||||||
|
if code_generate_type not in {"number", "secret"}:
|
||||||
|
raise ValueError("提取码类型不正确")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"allowed_file_types": parse_allowed_file_types(
|
||||||
|
get_form_value(data, "allowed_file_types", "*")
|
||||||
|
),
|
||||||
|
"code_generate_type": code_generate_type,
|
||||||
|
"enableChunk": int(normalize_bool_field(data, "enableChunk", False)),
|
||||||
|
"errorCount": parse_int_field(
|
||||||
|
data, "errorCount", DEFAULT_CONFIG["errorCount"], "取件错误次数限制", 1
|
||||||
|
),
|
||||||
|
"errorMinute": parse_int_field(
|
||||||
|
data, "errorMinute", DEFAULT_CONFIG["errorMinute"], "取件错误检测窗口", 1
|
||||||
|
),
|
||||||
|
"expireStyle": expire_styles,
|
||||||
|
"max_save_seconds": save_time_value * SAVE_TIME_UNITS[save_time_unit],
|
||||||
|
"openUpload": int(normalize_bool_field(data, "openUpload", True)),
|
||||||
|
"uploadCount": parse_int_field(
|
||||||
|
data, "uploadCount", DEFAULT_CONFIG["uploadCount"], "上传次数限制", 1
|
||||||
|
),
|
||||||
|
"uploadMinute": parse_int_field(
|
||||||
|
data, "uploadMinute", DEFAULT_CONFIG["uploadMinute"], "上传检测窗口", 1
|
||||||
|
),
|
||||||
|
"uploadSize": upload_size_value * FILE_SIZE_UNITS[upload_size_unit],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_expire_style_inputs(selected_styles: list[str]) -> str:
|
||||||
|
inputs = []
|
||||||
|
selected = set(selected_styles)
|
||||||
|
for style, label in EXPIRE_STYLE_OPTIONS:
|
||||||
|
checked = " checked" if style in selected else ""
|
||||||
|
inputs.append(
|
||||||
|
f'<label class="check"><input type="checkbox" name="expireStyle" value="{style}"{checked}> {label}</label>'
|
||||||
|
)
|
||||||
|
return "\n ".join(inputs)
|
||||||
|
|
||||||
|
|
||||||
|
def build_setup_page(error: str = "", form: dict | None = None) -> str:
|
||||||
|
form = form or {}
|
||||||
|
escaped_error = html.escape(error)
|
||||||
|
escaped_site_name = html.escape(
|
||||||
|
get_form_value(form, "site_name", DEFAULT_CONFIG["name"])
|
||||||
|
)
|
||||||
|
escaped_allowed_types = html.escape(get_form_value(form, "allowed_file_types", "*"))
|
||||||
|
upload_size_value = html.escape(get_form_value(form, "upload_size_value", "10"))
|
||||||
|
upload_size_unit = get_form_value(form, "upload_size_unit", "MB").upper()
|
||||||
|
save_time_value = html.escape(get_form_value(form, "save_time_value", "0"))
|
||||||
|
save_time_unit = get_form_value(form, "save_time_unit", "day")
|
||||||
|
upload_minute = html.escape(
|
||||||
|
get_form_value(form, "uploadMinute", str(DEFAULT_CONFIG["uploadMinute"]))
|
||||||
|
)
|
||||||
|
upload_count = html.escape(
|
||||||
|
get_form_value(form, "uploadCount", str(DEFAULT_CONFIG["uploadCount"]))
|
||||||
|
)
|
||||||
|
error_minute = html.escape(
|
||||||
|
get_form_value(form, "errorMinute", str(DEFAULT_CONFIG["errorMinute"]))
|
||||||
|
)
|
||||||
|
error_count = html.escape(
|
||||||
|
get_form_value(form, "errorCount", str(DEFAULT_CONFIG["errorCount"]))
|
||||||
|
)
|
||||||
|
open_upload_checked = (
|
||||||
|
" checked" if normalize_bool_field(form, "openUpload", True) else ""
|
||||||
|
)
|
||||||
|
chunk_checked = (
|
||||||
|
" checked" if normalize_bool_field(form, "enableChunk", False) else ""
|
||||||
|
)
|
||||||
|
code_generate_type = get_form_value(form, "code_generate_type", "number")
|
||||||
|
selected_expire_styles = get_form_list(form, "expireStyle") or list(
|
||||||
|
DEFAULT_CONFIG["expireStyle"]
|
||||||
|
)
|
||||||
|
expire_style_inputs = build_expire_style_inputs(selected_expire_styles)
|
||||||
|
size_unit_options = "\n".join(
|
||||||
|
f'<option value="{unit}"{" selected" if unit == upload_size_unit else ""}>{unit}</option>'
|
||||||
|
for unit in FILE_SIZE_UNITS
|
||||||
|
)
|
||||||
|
save_time_unit_options = "\n".join(
|
||||||
|
f'<option value="{unit}"{" selected" if unit == save_time_unit else ""}>{label}</option>'
|
||||||
|
for unit, label in [
|
||||||
|
("second", "秒"),
|
||||||
|
("minute", "分钟"),
|
||||||
|
("hour", "小时"),
|
||||||
|
("day", "天"),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
code_type_options = "\n".join(
|
||||||
|
f'<option value="{value}"{" selected" if value == code_generate_type else ""}>{label}</option>'
|
||||||
|
for value, label in [("number", "数字"), ("secret", "随机字符")]
|
||||||
|
)
|
||||||
|
error_block = (
|
||||||
|
f'<div class="alert" role="alert">{escaped_error}</div>' if escaped_error else ""
|
||||||
|
)
|
||||||
|
return f"""<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>初始化 FileCodeBox</title>
|
||||||
|
<style>
|
||||||
|
:root {{
|
||||||
|
color-scheme: light;
|
||||||
|
--bg: #f5f5f7;
|
||||||
|
--panel: rgba(255, 255, 255, .86);
|
||||||
|
--panel-strong: rgba(255, 255, 255, .96);
|
||||||
|
--text: #18181b;
|
||||||
|
--muted: #71717a;
|
||||||
|
--line: rgba(228, 228, 231, .9);
|
||||||
|
--line-strong: rgba(212, 212, 216, .95);
|
||||||
|
--primary: #18181b;
|
||||||
|
--primary-soft: #f4f4f5;
|
||||||
|
--danger-bg: #fef2f2;
|
||||||
|
--danger: #b91c1c;
|
||||||
|
}}
|
||||||
|
* {{ box-sizing: border-box; }}
|
||||||
|
body {{
|
||||||
|
margin: 0;
|
||||||
|
min-height: 100vh;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
padding: 14px;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
}}
|
||||||
|
main {{
|
||||||
|
width: min(100%, 1040px);
|
||||||
|
padding: 14px;
|
||||||
|
border: 1px solid rgba(255, 255, 255, .8);
|
||||||
|
border-radius: 20px;
|
||||||
|
background: rgba(255, 255, 255, .62);
|
||||||
|
box-shadow: 0 22px 70px -34px rgba(24, 24, 27, .32);
|
||||||
|
backdrop-filter: blur(22px);
|
||||||
|
}}
|
||||||
|
.setup-header {{
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
padding: 10px 10px 12px;
|
||||||
|
}}
|
||||||
|
.brand-mark {{
|
||||||
|
flex: 0 0 auto;
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
border-radius: 14px;
|
||||||
|
background: #18181b;
|
||||||
|
color: #fff;
|
||||||
|
font-weight: 800;
|
||||||
|
letter-spacing: 0;
|
||||||
|
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .42);
|
||||||
|
}}
|
||||||
|
.title-wrap {{
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
}}
|
||||||
|
h1 {{
|
||||||
|
margin: 0;
|
||||||
|
font-size: 21px;
|
||||||
|
line-height: 1.25;
|
||||||
|
letter-spacing: 0;
|
||||||
|
font-weight: 750;
|
||||||
|
}}
|
||||||
|
p {{
|
||||||
|
margin: 2px 0 0;
|
||||||
|
color: var(--muted);
|
||||||
|
line-height: 1.35;
|
||||||
|
font-size: 13px;
|
||||||
|
}}
|
||||||
|
form {{
|
||||||
|
margin: 0;
|
||||||
|
padding: 12px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 16px;
|
||||||
|
background: var(--panel);
|
||||||
|
}}
|
||||||
|
.panel-grid {{
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1.05fr 1fr 1fr;
|
||||||
|
gap: 10px;
|
||||||
|
}}
|
||||||
|
.panel {{
|
||||||
|
min-width: 0;
|
||||||
|
padding: 10px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 14px;
|
||||||
|
background: rgba(255, 255, 255, .68);
|
||||||
|
}}
|
||||||
|
.panel-wide {{
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1.3fr) minmax(0, .9fr);
|
||||||
|
gap: 12px;
|
||||||
|
align-items: end;
|
||||||
|
}}
|
||||||
|
.panel-title {{
|
||||||
|
margin: 0 0 2px;
|
||||||
|
color: #18181b;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 760;
|
||||||
|
}}
|
||||||
|
label {{
|
||||||
|
display: block;
|
||||||
|
margin: 8px 0 5px;
|
||||||
|
font-weight: 650;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #3f3f46;
|
||||||
|
}}
|
||||||
|
input, select {{
|
||||||
|
width: 100%;
|
||||||
|
height: 34px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 0 10px;
|
||||||
|
font: inherit;
|
||||||
|
color: var(--text);
|
||||||
|
outline: none;
|
||||||
|
background: rgba(255, 255, 255, .84);
|
||||||
|
transition: border-color .2s ease, box-shadow .2s ease, background-color .2s ease;
|
||||||
|
}}
|
||||||
|
input:focus, select:focus {{
|
||||||
|
border-color: #a1a1aa;
|
||||||
|
background: #fff;
|
||||||
|
box-shadow: 0 10px 22px -12px rgba(24, 24, 27, .2), 0 0 0 3px rgba(24, 24, 27, .06);
|
||||||
|
}}
|
||||||
|
.grid {{
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 6px 12px;
|
||||||
|
}}
|
||||||
|
.full {{ grid-column: 1 / -1; }}
|
||||||
|
.span-2 {{ grid-column: span 2; }}
|
||||||
|
.row {{
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) 88px;
|
||||||
|
gap: 8px;
|
||||||
|
}}
|
||||||
|
.checks {{
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
margin-top: 5px;
|
||||||
|
}}
|
||||||
|
.check {{
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
min-height: 36px;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0 9px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 10px;
|
||||||
|
font-weight: 550;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text);
|
||||||
|
white-space: nowrap;
|
||||||
|
background: rgba(255, 255, 255, .72);
|
||||||
|
transition: border-color .2s ease, background-color .2s ease, box-shadow .2s ease;
|
||||||
|
}}
|
||||||
|
.check:hover {{
|
||||||
|
border-color: var(--line-strong);
|
||||||
|
background: #fff;
|
||||||
|
box-shadow: 0 8px 20px -8px rgba(0, 0, 0, .1);
|
||||||
|
}}
|
||||||
|
.check input {{
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
padding: 0;
|
||||||
|
box-shadow: none;
|
||||||
|
}}
|
||||||
|
.section-title {{
|
||||||
|
display: none;
|
||||||
|
}}
|
||||||
|
.help {{
|
||||||
|
margin: 4px 0 0;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
}}
|
||||||
|
.alert {{
|
||||||
|
margin-bottom: 8px;
|
||||||
|
padding: 9px 12px;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--danger-bg);
|
||||||
|
color: var(--danger);
|
||||||
|
font-size: 13px;
|
||||||
|
}}
|
||||||
|
button {{
|
||||||
|
width: 100%;
|
||||||
|
height: 38px;
|
||||||
|
margin-top: 12px;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 12px;
|
||||||
|
background: var(--primary);
|
||||||
|
color: white;
|
||||||
|
font: inherit;
|
||||||
|
font-weight: 700;
|
||||||
|
cursor: pointer;
|
||||||
|
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .42);
|
||||||
|
transition: background-color .2s ease, box-shadow .2s ease;
|
||||||
|
}}
|
||||||
|
button:hover {{
|
||||||
|
background: #27272a;
|
||||||
|
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .56);
|
||||||
|
}}
|
||||||
|
.hint {{
|
||||||
|
margin-top: 8px;
|
||||||
|
margin-bottom: 0;
|
||||||
|
font-size: 12px;
|
||||||
|
}}
|
||||||
|
.compact-help {{
|
||||||
|
display: inline;
|
||||||
|
margin-left: 6px;
|
||||||
|
color: var(--muted);
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 12px;
|
||||||
|
}}
|
||||||
|
.topline {{
|
||||||
|
display: none;
|
||||||
|
}}
|
||||||
|
.badge {{
|
||||||
|
min-height: 26px;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0 10px;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgba(255, 255, 255, .76);
|
||||||
|
color: #52525b;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 650;
|
||||||
|
white-space: nowrap;
|
||||||
|
}}
|
||||||
|
@media (max-width: 640px) {{
|
||||||
|
body {{ padding: 10px; }}
|
||||||
|
main {{ padding: 10px; }}
|
||||||
|
.setup-header {{ align-items: flex-start; padding: 6px 4px 10px; }}
|
||||||
|
.title-wrap {{ align-items: flex-start; }}
|
||||||
|
.panel-grid, .panel-wide {{ grid-template-columns: 1fr; }}
|
||||||
|
.grid, .checks {{ grid-template-columns: 1fr; }}
|
||||||
|
.span-2 {{ grid-column: auto; }}
|
||||||
|
.row {{ grid-template-columns: 1fr; }}
|
||||||
|
.badge {{ display: none; }}
|
||||||
|
}}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<div class="setup-header">
|
||||||
|
<div class="title-wrap">
|
||||||
|
<div class="brand-mark">FCB</div>
|
||||||
|
<div>
|
||||||
|
<h1>初始化 FileCodeBox</h1>
|
||||||
|
<p>首次配置管理员密码、上传限制和取件策略,后续可在后台调整。</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span class="badge">首次配置向导</span>
|
||||||
|
</div>
|
||||||
|
<form method="post" action="/setup" autocomplete="off">
|
||||||
|
{error_block}
|
||||||
|
<div class="panel-grid">
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-title">基础设置</div>
|
||||||
|
<label for="site_name">站点名称</label>
|
||||||
|
<input id="site_name" name="site_name" maxlength="80" value="{escaped_site_name}" placeholder="文件快递柜 - FileCodeBox">
|
||||||
|
|
||||||
|
<label for="admin_password">管理员密码</label>
|
||||||
|
<input id="admin_password" name="admin_password" type="password" minlength="8" required autofocus>
|
||||||
|
|
||||||
|
<label for="confirm_password">确认管理员密码</label>
|
||||||
|
<input id="confirm_password" name="confirm_password" type="password" minlength="8" required>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-title">上传设置</div>
|
||||||
|
<label for="upload_size_value">单文件大小限制</label>
|
||||||
|
<div class="row">
|
||||||
|
<input id="upload_size_value" name="upload_size_value" type="number" min="1" value="{upload_size_value}" required>
|
||||||
|
<select name="upload_size_unit" aria-label="文件大小单位">
|
||||||
|
{size_unit_options}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label for="uploadCount">上传频率 <span class="compact-help">次数 / 分钟</span></label>
|
||||||
|
<div class="row">
|
||||||
|
<input id="uploadCount" name="uploadCount" type="number" min="1" value="{upload_count}" required>
|
||||||
|
<input name="uploadMinute" type="number" min="1" value="{upload_minute}" aria-label="上传检测窗口分钟" required>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid">
|
||||||
|
<input type="hidden" name="openUpload" value="0">
|
||||||
|
<label class="check"><input type="checkbox" name="openUpload" value="1"{open_upload_checked}> 允许游客上传</label>
|
||||||
|
<input type="hidden" name="enableChunk" value="0">
|
||||||
|
<label class="check"><input type="checkbox" name="enableChunk" value="1"{chunk_checked}> 启用切片上传</label>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-title">取件与保存</div>
|
||||||
|
<label for="errorCount">取件错误频率 <span class="compact-help">次数 / 分钟</span></label>
|
||||||
|
<div class="row">
|
||||||
|
<input id="errorCount" name="errorCount" type="number" min="1" value="{error_count}" required>
|
||||||
|
<input name="errorMinute" type="number" min="1" value="{error_minute}" aria-label="取件错误检测窗口分钟" required>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label for="save_time_value">最长保存时间</label>
|
||||||
|
<div class="row">
|
||||||
|
<input id="save_time_value" name="save_time_value" type="number" min="0" value="{save_time_value}" required>
|
||||||
|
<select name="save_time_unit" aria-label="最长保存时间单位">
|
||||||
|
{save_time_unit_options}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label for="code_generate_type">提取码类型</label>
|
||||||
|
<select id="code_generate_type" name="code_generate_type">
|
||||||
|
{code_type_options}
|
||||||
|
</select>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel panel-wide">
|
||||||
|
<div>
|
||||||
|
<div class="panel-title">可用策略</div>
|
||||||
|
<label>允许的过期方式</label>
|
||||||
|
<div class="checks">
|
||||||
|
{expire_style_inputs}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label for="allowed_file_types">允许文件类型 <span class="compact-help">逗号分隔,* 表示不限制</span></label>
|
||||||
|
<input id="allowed_file_types" name="allowed_file_types" value="{escaped_allowed_types}" placeholder="* 或 .zip, image/*">
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<button type="submit">完成初始化</button>
|
||||||
|
</form>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>"""
|
||||||
|
|
||||||
|
|
||||||
|
def build_setup_success_page() -> str:
|
||||||
|
return """<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta http-equiv="refresh" content="2;url=/#/admin">
|
||||||
|
<title>初始化完成</title>
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
min-height: 100vh;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
padding: 24px;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||||
|
background: #f6f8fb;
|
||||||
|
color: #172033;
|
||||||
|
}
|
||||||
|
main {
|
||||||
|
width: min(100%, 420px);
|
||||||
|
padding: 28px;
|
||||||
|
border: 1px solid #d9e1ec;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: #fff;
|
||||||
|
text-align: center;
|
||||||
|
box-shadow: 0 18px 50px rgba(23, 32, 51, .08);
|
||||||
|
}
|
||||||
|
h1 { margin: 0 0 10px; font-size: 24px; letter-spacing: 0; }
|
||||||
|
p { margin: 0 0 22px; color: #60708a; line-height: 1.65; }
|
||||||
|
a {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 42px;
|
||||||
|
padding: 0 18px;
|
||||||
|
border-radius: 6px;
|
||||||
|
background: #2563eb;
|
||||||
|
color: white;
|
||||||
|
text-decoration: none;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<h1>初始化完成</h1>
|
||||||
|
<p>管理员密码已设置,请使用刚才的密码登录后台。</p>
|
||||||
|
<a href="/#/admin">进入后台</a>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>"""
|
||||||
|
|
||||||
|
|
||||||
|
def setup_response(content: str, status_code: int = 200) -> HTMLResponse:
|
||||||
|
return HTMLResponse(
|
||||||
|
content=content,
|
||||||
|
status_code=status_code,
|
||||||
|
media_type="text/html",
|
||||||
|
headers={"Cache-Control": "no-store"},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def is_setup_path(path: str) -> bool:
|
||||||
|
return path.rstrip("/") == "/setup"
|
||||||
|
|
||||||
|
|
||||||
|
def wants_html_response(request: Request) -> bool:
|
||||||
|
if request.method not in {"GET", "HEAD"}:
|
||||||
|
return False
|
||||||
|
accept = request.headers.get("accept", "")
|
||||||
|
return not accept or "text/html" in accept or "*/*" in accept
|
||||||
|
|
||||||
|
|
||||||
|
async def read_setup_payload(request: Request) -> dict:
|
||||||
|
content_type = request.headers.get("content-type", "")
|
||||||
|
if "application/json" in content_type:
|
||||||
|
data = await request.json()
|
||||||
|
return data if isinstance(data, dict) else {}
|
||||||
|
|
||||||
|
body = (await request.body()).decode("utf-8")
|
||||||
|
return {
|
||||||
|
key: values if len(values) > 1 else values[-1]
|
||||||
|
for key, values in parse_qs(body).items()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
@@ -31,14 +691,9 @@ async def lifespan(app: FastAPI):
|
|||||||
# 初始化数据库
|
# 初始化数据库
|
||||||
await init_db()
|
await init_db()
|
||||||
|
|
||||||
# 加载配置
|
# 加载配置(多进程下串行化启动写操作)
|
||||||
await load_config()
|
async with db_startup_lock():
|
||||||
app.mount(
|
await load_config()
|
||||||
"/assets",
|
|
||||||
StaticFiles(directory=f"./{settings.themesSelect}/assets"),
|
|
||||||
name="assets",
|
|
||||||
)
|
|
||||||
|
|
||||||
# 启动后台任务
|
# 启动后台任务
|
||||||
task = asyncio.create_task(delete_expire_files())
|
task = asyncio.create_task(delete_expire_files())
|
||||||
chunk_cleanup_task = asyncio.create_task(clean_incomplete_uploads())
|
chunk_cleanup_task = asyncio.create_task(clean_incomplete_uploads())
|
||||||
@@ -57,35 +712,37 @@ async def lifespan(app: FastAPI):
|
|||||||
|
|
||||||
|
|
||||||
async def load_config():
|
async def load_config():
|
||||||
user_config, _ = await KeyValue.get_or_create(
|
await ensure_settings_row()
|
||||||
key="settings", defaults={"value": DEFAULT_CONFIG}
|
|
||||||
)
|
|
||||||
await KeyValue.update_or_create(
|
await KeyValue.update_or_create(
|
||||||
key="sys_start", defaults={"value": int(time.time() * 1000)}
|
key="sys_start", defaults={"value": int(time.time() * 1000)}
|
||||||
)
|
)
|
||||||
settings.user_config = user_config.value
|
await refresh_settings()
|
||||||
|
await ensure_security_settings()
|
||||||
await migrate_password_to_hash()
|
|
||||||
|
|
||||||
ip_limit["error"].minutes = settings.errorMinute
|
ip_limit["error"].minutes = settings.errorMinute
|
||||||
ip_limit["error"].count = settings.errorCount
|
ip_limit["error"].count = settings.errorCount
|
||||||
ip_limit["upload"].minutes = settings.uploadMinute
|
ip_limit["upload"].minutes = settings.uploadMinute
|
||||||
ip_limit["upload"].count = settings.uploadCount
|
ip_limit["upload"].count = settings.uploadCount
|
||||||
|
|
||||||
|
|
||||||
async def migrate_password_to_hash():
|
|
||||||
if not is_password_hashed(settings.admin_token):
|
|
||||||
hashed = hash_password(settings.admin_token)
|
|
||||||
settings.admin_token = hashed
|
|
||||||
config_record = await KeyValue.filter(key="settings").first()
|
|
||||||
if config_record and config_record.value:
|
|
||||||
config_record.value["admin_token"] = hashed
|
|
||||||
await config_record.save()
|
|
||||||
logger.info("已将管理员密码迁移为哈希存储")
|
|
||||||
|
|
||||||
|
|
||||||
app = FastAPI(lifespan=lifespan)
|
app = FastAPI(lifespan=lifespan)
|
||||||
|
|
||||||
|
@app.middleware("http")
|
||||||
|
async def refresh_settings_middleware(request, call_next):
|
||||||
|
await refresh_settings()
|
||||||
|
if not is_runtime_initialized() and not is_setup_path(request.url.path):
|
||||||
|
if wants_html_response(request):
|
||||||
|
return setup_response(build_setup_page())
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=428,
|
||||||
|
content={
|
||||||
|
"code": 428,
|
||||||
|
"message": "系统未初始化,请先完成初始化",
|
||||||
|
"msg": "系统未初始化,请先完成初始化",
|
||||||
|
"detail": {"setup": "/setup"},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
return await call_next(request)
|
||||||
|
|
||||||
app.add_middleware(
|
app.add_middleware(
|
||||||
CORSMiddleware,
|
CORSMiddleware,
|
||||||
allow_origins=["*"],
|
allow_origins=["*"],
|
||||||
@@ -97,15 +754,7 @@ app.add_middleware(
|
|||||||
# 使用 register_tortoise 来添加异常处理器
|
# 使用 register_tortoise 来添加异常处理器
|
||||||
register_tortoise(
|
register_tortoise(
|
||||||
app,
|
app,
|
||||||
config={
|
config=get_db_config(),
|
||||||
"connections": {"default": f"sqlite://{data_root}/filecodebox.db"},
|
|
||||||
"apps": {
|
|
||||||
"models": {
|
|
||||||
"models": ["apps.base.models"],
|
|
||||||
"default_connection": "default",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
generate_schemas=False,
|
generate_schemas=False,
|
||||||
add_exception_handlers=True,
|
add_exception_handlers=True,
|
||||||
)
|
)
|
||||||
@@ -113,22 +762,87 @@ register_tortoise(
|
|||||||
app.include_router(share_api)
|
app.include_router(share_api)
|
||||||
app.include_router(chunk_api)
|
app.include_router(chunk_api)
|
||||||
app.include_router(presign_api)
|
app.include_router(presign_api)
|
||||||
|
app.include_router(presign_api, prefix="/api")
|
||||||
app.include_router(admin_api)
|
app.include_router(admin_api)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/setup", include_in_schema=False)
|
||||||
|
@app.get("/setup/", include_in_schema=False)
|
||||||
|
async def setup_page():
|
||||||
|
if is_runtime_initialized():
|
||||||
|
return RedirectResponse(url="/", status_code=303)
|
||||||
|
return setup_response(build_setup_page())
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/setup", include_in_schema=False)
|
||||||
|
@app.post("/setup/", include_in_schema=False)
|
||||||
|
async def setup_submit(request: Request):
|
||||||
|
if is_runtime_initialized():
|
||||||
|
return RedirectResponse(url="/", status_code=303)
|
||||||
|
|
||||||
|
data = await read_setup_payload(request)
|
||||||
|
admin_password = str(data.get("admin_password") or "")
|
||||||
|
confirm_password = str(data.get("confirm_password") or "")
|
||||||
|
site_name = str(data.get("site_name") or "")
|
||||||
|
|
||||||
|
if admin_password != confirm_password:
|
||||||
|
return setup_response(build_setup_page("两次输入的管理员密码不一致", data), 400)
|
||||||
|
|
||||||
|
try:
|
||||||
|
setup_options = parse_setup_options(data)
|
||||||
|
await initialize_system(
|
||||||
|
admin_password=admin_password,
|
||||||
|
site_name=site_name,
|
||||||
|
setup_options=setup_options,
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
return setup_response(build_setup_page(str(exc), data), 400)
|
||||||
|
|
||||||
|
if "application/json" in request.headers.get("accept", ""):
|
||||||
|
return APIResponse(detail={"ok": True, "admin": "/#/admin"})
|
||||||
|
return setup_response(build_setup_success_page())
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_theme_root():
|
||||||
|
themes_root = (BASE_DIR / "themes").resolve()
|
||||||
|
theme_root = (BASE_DIR / str(settings.themesSelect)).resolve()
|
||||||
|
try:
|
||||||
|
theme_root.relative_to(themes_root)
|
||||||
|
except ValueError:
|
||||||
|
theme_root = (BASE_DIR / DEFAULT_CONFIG["themesSelect"]).resolve()
|
||||||
|
if not theme_root.exists():
|
||||||
|
theme_root = (BASE_DIR / DEFAULT_CONFIG["themesSelect"]).resolve()
|
||||||
|
return theme_root
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_theme_file(*parts: str):
|
||||||
|
theme_root = resolve_theme_root()
|
||||||
|
file_path = theme_root.joinpath(*parts).resolve()
|
||||||
|
# 防止通过 /assets/../ 读取主题目录外的文件。
|
||||||
|
try:
|
||||||
|
file_path.relative_to(theme_root)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(status_code=404, detail="资源不存在")
|
||||||
|
if not file_path.is_file():
|
||||||
|
raise HTTPException(status_code=404, detail="资源不存在")
|
||||||
|
return file_path
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/assets/{asset_path:path}", include_in_schema=False)
|
||||||
|
async def theme_asset(asset_path: str):
|
||||||
|
return FileResponse(resolve_theme_file("assets", asset_path))
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(404)
|
@app.exception_handler(404)
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
async def index(request=None, exc=None):
|
async def index(request=None, exc=None):
|
||||||
return HTMLResponse(
|
return HTMLResponse(
|
||||||
content=open(
|
content=resolve_theme_file("index.html")
|
||||||
BASE_DIR / f"{settings.themesSelect}/index.html", "r", encoding="utf-8"
|
.read_text(encoding="utf-8")
|
||||||
)
|
|
||||||
.read()
|
|
||||||
.replace("{{title}}", str(settings.name))
|
.replace("{{title}}", str(settings.name))
|
||||||
.replace("{{description}}", str(settings.description))
|
.replace("{{description}}", str(settings.description))
|
||||||
.replace("{{keywords}}", str(settings.keywords))
|
.replace("{{keywords}}", str(settings.keywords))
|
||||||
.replace("{{opacity}}", str(settings.opacity))
|
.replace("{{opacity}}", str(settings.opacity))
|
||||||
.replace('"/assets/', '"assets/')
|
|
||||||
.replace("{{background}}", str(settings.background)),
|
.replace("{{background}}", str(settings.background)),
|
||||||
media_type="text/html",
|
media_type="text/html",
|
||||||
headers={"Cache-Control": "no-cache"},
|
headers={"Cache-Control": "no-cache"},
|
||||||
@@ -142,19 +856,27 @@ async def robots():
|
|||||||
|
|
||||||
@app.post("/")
|
@app.post("/")
|
||||||
async def get_config():
|
async def get_config():
|
||||||
|
return APIResponse(detail=build_public_config())
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/v1/config")
|
||||||
|
async def get_public_config():
|
||||||
return APIResponse(
|
return APIResponse(
|
||||||
detail={
|
detail={
|
||||||
"name": settings.name,
|
"config": build_public_config(),
|
||||||
"description": settings.description,
|
"meta": build_public_meta(),
|
||||||
"explain": settings.page_explain,
|
}
|
||||||
"uploadSize": settings.uploadSize,
|
)
|
||||||
"expireStyle": settings.expireStyle,
|
|
||||||
"enableChunk": settings.enableChunk,
|
|
||||||
"openUpload": settings.openUpload,
|
@app.get("/health")
|
||||||
"notify_title": settings.notify_title,
|
async def health_check():
|
||||||
"notify_content": settings.notify_content,
|
return APIResponse(
|
||||||
"show_admin_address": settings.showAdminAddr,
|
detail={
|
||||||
"max_save_seconds": settings.max_save_seconds,
|
"status": "ok",
|
||||||
|
"version": APP_VERSION,
|
||||||
|
"storage": settings.file_storage,
|
||||||
|
"theme": settings.themesSelect,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -254,7 +254,7 @@ python main.py
|
|||||||
|------|------|
|
|------|------|
|
||||||
| **分享文件** | 打开网页 → 选择/拖拽文件 → 设置有效期 → 获取提取码 |
|
| **分享文件** | 打开网页 → 选择/拖拽文件 → 设置有效期 → 获取提取码 |
|
||||||
| **获取文件** | 打开网页 → 输入提取码 → 下载文件或查看文本 |
|
| **获取文件** | 打开网页 → 输入提取码 → 下载文件或查看文本 |
|
||||||
| **管理后台** | 访问 `/#/admin` → 输入密码 `FileCodeBox2023` |
|
| **管理后台** | 首次访问站点完成初始化 → 访问 `/#/admin` → 输入初始化时设置的密码 |
|
||||||
|
|
||||||
### 命令行使用(curl)
|
### 命令行使用(curl)
|
||||||
|
|
||||||
@@ -323,7 +323,7 @@ curl -L "http://localhost:12345/share/select/?code=提取码" -o filename
|
|||||||
# 1. 获取 token
|
# 1. 获取 token
|
||||||
curl -X POST "http://localhost:12345/admin/login" \
|
curl -X POST "http://localhost:12345/admin/login" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{"password": "FileCodeBox2023"}'
|
-d '{"password": "<初始化时设置的管理员密码>"}'
|
||||||
|
|
||||||
# 2. 携带 token 上传
|
# 2. 携带 token 上传
|
||||||
curl -X POST "http://localhost:12345/share/file/" \
|
curl -X POST "http://localhost:12345/share/file/" \
|
||||||
@@ -468,4 +468,5 @@ git push origin feature/your-feature
|
|||||||
|
|
||||||
Made with ❤️ by [vastsa](https://github.com/vastsa)
|
Made with ❤️ by [vastsa](https://github.com/vastsa)
|
||||||
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
+2
-2
@@ -254,7 +254,7 @@ python main.py
|
|||||||
|-----------|-------|
|
|-----------|-------|
|
||||||
| **Share File** | Open website → Select/drag files → Set expiration → Get passcode |
|
| **Share File** | Open website → Select/drag files → Set expiration → Get passcode |
|
||||||
| **Retrieve File** | Open website → Enter passcode → Download file or view text |
|
| **Retrieve File** | Open website → Enter passcode → Download file or view text |
|
||||||
| **Admin Panel** | Visit `/#/admin` → Enter password `FileCodeBox2023` |
|
| **Admin Panel** | Complete first-run setup → Visit `/#/admin` → Enter the password set during setup |
|
||||||
|
|
||||||
### Command Line Usage (curl)
|
### Command Line Usage (curl)
|
||||||
|
|
||||||
@@ -323,7 +323,7 @@ curl -L "http://localhost:12345/share/select/?code=PASSCODE" -o filename
|
|||||||
# 1. Get token
|
# 1. Get token
|
||||||
curl -X POST "http://localhost:12345/admin/login" \
|
curl -X POST "http://localhost:12345/admin/login" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{"password": "FileCodeBox2023"}'
|
-d '{"password": "<admin-password-set-during-setup>"}'
|
||||||
|
|
||||||
# 2. Upload with token
|
# 2. Upload with token
|
||||||
curl -X POST "http://localhost:12345/share/file/" \
|
curl -X POST "http://localhost:12345/share/file/" \
|
||||||
|
|||||||
@@ -0,0 +1,221 @@
|
|||||||
|
import asyncio
|
||||||
|
import copy
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import apps.admin.services as admin_services
|
||||||
|
import core.config as core_config
|
||||||
|
from apps.admin.dependencies import create_token, verify_token
|
||||||
|
from apps.admin.services import ConfigService
|
||||||
|
from main import parse_setup_options
|
||||||
|
from core.security import (
|
||||||
|
LEGACY_DEFAULT_ADMIN_TOKEN,
|
||||||
|
is_config_initialized,
|
||||||
|
prepare_security_config,
|
||||||
|
)
|
||||||
|
from core.settings import DEFAULT_CONFIG, settings
|
||||||
|
from core.utils import hash_password, verify_password
|
||||||
|
|
||||||
|
|
||||||
|
class SettingsOverrideMixin:
|
||||||
|
def setUp(self):
|
||||||
|
self._original_user_config = dict(settings.user_config)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
settings.user_config = self._original_user_config
|
||||||
|
|
||||||
|
|
||||||
|
class SecurityConfigTests(unittest.TestCase):
|
||||||
|
def test_initial_security_config_requires_setup_and_generates_jwt_secret(self):
|
||||||
|
result = prepare_security_config(DEFAULT_CONFIG)
|
||||||
|
|
||||||
|
self.assertTrue(result.changed)
|
||||||
|
self.assertTrue(result.setup_required)
|
||||||
|
self.assertEqual(result.config["admin_token"], "")
|
||||||
|
self.assertFalse(is_config_initialized(result.config))
|
||||||
|
self.assertGreaterEqual(len(result.config["jwt_secret"]), 32)
|
||||||
|
|
||||||
|
def test_legacy_default_password_requires_setup(self):
|
||||||
|
config = copy.deepcopy(DEFAULT_CONFIG)
|
||||||
|
config["admin_token"] = hash_password(LEGACY_DEFAULT_ADMIN_TOKEN)
|
||||||
|
config["jwt_secret"] = "j" * 48
|
||||||
|
|
||||||
|
result = prepare_security_config(config)
|
||||||
|
|
||||||
|
self.assertTrue(result.setup_required)
|
||||||
|
self.assertEqual(result.config["admin_token"], "")
|
||||||
|
self.assertEqual(result.config["jwt_secret"], "j" * 48)
|
||||||
|
|
||||||
|
def test_custom_plaintext_password_is_hashed_and_initialized(self):
|
||||||
|
config = copy.deepcopy(DEFAULT_CONFIG)
|
||||||
|
config["admin_token"] = "custom-password"
|
||||||
|
config["jwt_secret"] = "j" * 48
|
||||||
|
|
||||||
|
result = prepare_security_config(config)
|
||||||
|
|
||||||
|
self.assertTrue(result.password_hashed)
|
||||||
|
self.assertTrue(is_config_initialized(result.config))
|
||||||
|
self.assertTrue(verify_password("custom-password", result.config["admin_token"]))
|
||||||
|
|
||||||
|
|
||||||
|
class SetupOptionTests(unittest.TestCase):
|
||||||
|
def test_parse_setup_options_converts_common_fields(self):
|
||||||
|
options = parse_setup_options(
|
||||||
|
{
|
||||||
|
"upload_size_value": "20",
|
||||||
|
"upload_size_unit": "MB",
|
||||||
|
"save_time_value": "7",
|
||||||
|
"save_time_unit": "day",
|
||||||
|
"uploadCount": "30",
|
||||||
|
"uploadMinute": "2",
|
||||||
|
"errorCount": "5",
|
||||||
|
"errorMinute": "1",
|
||||||
|
"openUpload": ["0", "1"],
|
||||||
|
"enableChunk": "0",
|
||||||
|
"code_generate_type": "secret",
|
||||||
|
"expireStyle": ["day", "count"],
|
||||||
|
"allowed_file_types": ".zip, image/*",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(options["uploadSize"], 20 * 1024 * 1024)
|
||||||
|
self.assertEqual(options["max_save_seconds"], 7 * 86400)
|
||||||
|
self.assertEqual(options["uploadCount"], 30)
|
||||||
|
self.assertEqual(options["uploadMinute"], 2)
|
||||||
|
self.assertEqual(options["errorCount"], 5)
|
||||||
|
self.assertEqual(options["errorMinute"], 1)
|
||||||
|
self.assertEqual(options["openUpload"], 1)
|
||||||
|
self.assertEqual(options["enableChunk"], 0)
|
||||||
|
self.assertEqual(options["code_generate_type"], "secret")
|
||||||
|
self.assertEqual(options["expireStyle"], ["day", "count"])
|
||||||
|
self.assertEqual(options["allowed_file_types"], [".zip", "image/*"])
|
||||||
|
|
||||||
|
def test_parse_setup_options_allows_turning_guest_upload_off(self):
|
||||||
|
options = parse_setup_options(
|
||||||
|
{
|
||||||
|
"openUpload": "0",
|
||||||
|
"expireStyle": ["day"],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(options["openUpload"], 0)
|
||||||
|
|
||||||
|
def test_parse_setup_options_requires_expire_style(self):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
parse_setup_options({"expireStyle": []})
|
||||||
|
|
||||||
|
|
||||||
|
class AdminJwtTests(SettingsOverrideMixin, unittest.TestCase):
|
||||||
|
def test_admin_jwt_signature_uses_independent_secret(self):
|
||||||
|
settings.admin_token = hash_password("old-admin-password")
|
||||||
|
settings.jwt_secret = "j" * 48
|
||||||
|
|
||||||
|
token = create_token({"is_admin": True}, expires_in=60)
|
||||||
|
self.assertTrue(verify_token(token)["is_admin"])
|
||||||
|
|
||||||
|
settings.admin_token = hash_password("new-admin-password")
|
||||||
|
self.assertTrue(verify_token(token)["is_admin"])
|
||||||
|
|
||||||
|
settings.jwt_secret = "k" * 48
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
verify_token(token)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeKeyValue:
|
||||||
|
saved_value = None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def update_or_create(cls, key, defaults):
|
||||||
|
cls.saved_value = defaults["value"]
|
||||||
|
return None, True
|
||||||
|
|
||||||
|
|
||||||
|
async def fake_refresh_settings():
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class FakeConfigRecord:
|
||||||
|
def __init__(self, value):
|
||||||
|
self.value = value
|
||||||
|
|
||||||
|
|
||||||
|
class FakeConfigQuery:
|
||||||
|
async def first(self):
|
||||||
|
return FakeConfigKeyValue.record
|
||||||
|
|
||||||
|
|
||||||
|
class FakeConfigKeyValue:
|
||||||
|
record = None
|
||||||
|
saved_value = None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def filter(cls, key):
|
||||||
|
return FakeConfigQuery()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def update_or_create(cls, key, defaults):
|
||||||
|
cls.saved_value = defaults["value"]
|
||||||
|
return None, True
|
||||||
|
|
||||||
|
|
||||||
|
class ConfigServiceSecurityTests(SettingsOverrideMixin, unittest.TestCase):
|
||||||
|
def test_admin_password_update_rotates_jwt_secret(self):
|
||||||
|
old_secret = "j" * 48
|
||||||
|
settings.user_config = {
|
||||||
|
**copy.deepcopy(DEFAULT_CONFIG),
|
||||||
|
"admin_token": hash_password("old-admin-password"),
|
||||||
|
"jwt_secret": old_secret,
|
||||||
|
}
|
||||||
|
original_key_value = admin_services.KeyValue
|
||||||
|
original_refresh_settings = admin_services.refresh_settings
|
||||||
|
admin_services.KeyValue = FakeKeyValue
|
||||||
|
admin_services.refresh_settings = fake_refresh_settings
|
||||||
|
FakeKeyValue.saved_value = None
|
||||||
|
try:
|
||||||
|
asyncio.run(ConfigService().update_config({"admin_token": "new-admin-password"}))
|
||||||
|
finally:
|
||||||
|
admin_services.KeyValue = original_key_value
|
||||||
|
admin_services.refresh_settings = original_refresh_settings
|
||||||
|
|
||||||
|
self.assertIsNotNone(FakeKeyValue.saved_value)
|
||||||
|
self.assertTrue(verify_password("new-admin-password", FakeKeyValue.saved_value["admin_token"]))
|
||||||
|
self.assertNotEqual(FakeKeyValue.saved_value["jwt_secret"], old_secret)
|
||||||
|
self.assertGreaterEqual(len(FakeKeyValue.saved_value["jwt_secret"]), 32)
|
||||||
|
|
||||||
|
def test_initialize_system_sets_admin_password_and_jwt_secret(self):
|
||||||
|
original_key_value = core_config.KeyValue
|
||||||
|
original_refresh_settings = core_config.refresh_settings
|
||||||
|
FakeConfigKeyValue.record = FakeConfigRecord(
|
||||||
|
{
|
||||||
|
**copy.deepcopy(DEFAULT_CONFIG),
|
||||||
|
"admin_token": "",
|
||||||
|
"jwt_secret": "",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
FakeConfigKeyValue.saved_value = None
|
||||||
|
core_config.KeyValue = FakeConfigKeyValue
|
||||||
|
core_config.refresh_settings = fake_refresh_settings
|
||||||
|
try:
|
||||||
|
asyncio.run(
|
||||||
|
core_config.initialize_system(
|
||||||
|
admin_password="new-admin-password",
|
||||||
|
site_name="我的文件快递柜",
|
||||||
|
setup_options={
|
||||||
|
"uploadSize": 50 * 1024 * 1024,
|
||||||
|
"errorCount": 6,
|
||||||
|
"expireStyle": ["day", "count"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
core_config.KeyValue = original_key_value
|
||||||
|
core_config.refresh_settings = original_refresh_settings
|
||||||
|
|
||||||
|
self.assertIsNotNone(FakeConfigKeyValue.saved_value)
|
||||||
|
self.assertTrue(
|
||||||
|
verify_password("new-admin-password", FakeConfigKeyValue.saved_value["admin_token"])
|
||||||
|
)
|
||||||
|
self.assertGreaterEqual(len(FakeConfigKeyValue.saved_value["jwt_secret"]), 32)
|
||||||
|
self.assertEqual(FakeConfigKeyValue.saved_value["name"], "我的文件快递柜")
|
||||||
|
self.assertEqual(FakeConfigKeyValue.saved_value["uploadSize"], 50 * 1024 * 1024)
|
||||||
|
self.assertEqual(FakeConfigKeyValue.saved_value["errorCount"], 6)
|
||||||
|
self.assertEqual(FakeConfigKeyValue.saved_value["expireStyle"], ["day", "count"])
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import unittest
|
||||||
|
|
||||||
|
from core.settings import settings
|
||||||
|
from core.storage import S3FileStorage
|
||||||
|
|
||||||
|
|
||||||
|
class SettingsOverrideMixin:
|
||||||
|
def setUp(self):
|
||||||
|
self._original_user_config = dict(settings.user_config)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
settings.user_config = self._original_user_config
|
||||||
|
|
||||||
|
|
||||||
|
class S3StorageConfigTests(SettingsOverrideMixin, unittest.TestCase):
|
||||||
|
def test_client_config_uses_path_style_when_configured(self):
|
||||||
|
storage = S3FileStorage.__new__(S3FileStorage)
|
||||||
|
storage.signature_version = "s3v4"
|
||||||
|
storage.addressing_style = "path"
|
||||||
|
|
||||||
|
config = storage._client_config()
|
||||||
|
|
||||||
|
self.assertEqual(config.signature_version, "s3v4")
|
||||||
|
self.assertEqual(config.s3["addressing_style"], "path")
|
||||||
|
|
||||||
|
def test_client_config_ignores_invalid_addressing_style(self):
|
||||||
|
storage = S3FileStorage.__new__(S3FileStorage)
|
||||||
|
storage.signature_version = "s3v4"
|
||||||
|
storage.addressing_style = "invalid"
|
||||||
|
|
||||||
|
config = storage._client_config()
|
||||||
|
|
||||||
|
self.assertIsNone(config.s3)
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import asyncio
|
||||||
|
import unittest
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from apps.admin.services import FileService
|
||||||
|
from core.settings import settings
|
||||||
|
|
||||||
|
|
||||||
|
class SettingsOverrideMixin:
|
||||||
|
def setUp(self):
|
||||||
|
self._original_user_config = dict(settings.user_config)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
settings.user_config = self._original_user_config
|
||||||
|
|
||||||
|
|
||||||
|
class FakeFileCode:
|
||||||
|
def __init__(self):
|
||||||
|
self.id = 1
|
||||||
|
self.code = "ABC123"
|
||||||
|
self.prefix = "report"
|
||||||
|
self.suffix = ".txt"
|
||||||
|
self.uuid_file_name = "report.txt"
|
||||||
|
self.file_path = "share/data/2026/01/01/abc"
|
||||||
|
self.size = 12
|
||||||
|
self.text = None
|
||||||
|
self.expired_at = datetime(2026, 1, 2, 12, 0, 0)
|
||||||
|
self.expired_count = 3
|
||||||
|
self.used_count = 0
|
||||||
|
self.created_at = datetime(2026, 1, 1, 12, 0, 0)
|
||||||
|
self.file_hash = "a" * 64
|
||||||
|
self.is_chunked = False
|
||||||
|
self.upload_id = None
|
||||||
|
|
||||||
|
async def is_expired(self):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
class AdminFileItemTests(SettingsOverrideMixin, unittest.TestCase):
|
||||||
|
def test_build_admin_file_item_serializes_required_fields(self):
|
||||||
|
settings.file_storage = "local"
|
||||||
|
service = FileService()
|
||||||
|
now = datetime(2026, 1, 1, 13, 0, 0)
|
||||||
|
|
||||||
|
item = asyncio.run(service._build_admin_file_item(FakeFileCode(), now=now))
|
||||||
|
|
||||||
|
self.assertEqual(item["id"], 1)
|
||||||
|
self.assertEqual(item["name"], "report.txt")
|
||||||
|
self.assertEqual(item["type"], "file")
|
||||||
|
self.assertFalse(item["isExpired"])
|
||||||
|
self.assertEqual(item["remainingDownloads"], 3)
|
||||||
|
self.assertEqual(item["file_path"], "share/data/2026/01/01/abc")
|
||||||
|
self.assertIn("never_retrieved", item["statusInsights"]["reasons"])
|
||||||
|
self.assertEqual(item["statusInsights"]["metrics"]["ageSeconds"], 3600)
|
||||||
|
|
||||||
|
def test_build_admin_file_item_marks_expiring_soon(self):
|
||||||
|
settings.file_storage = "local"
|
||||||
|
service = FileService()
|
||||||
|
file_code = FakeFileCode()
|
||||||
|
now = file_code.expired_at - timedelta(hours=2)
|
||||||
|
|
||||||
|
item = asyncio.run(service._build_admin_file_item(file_code, now=now))
|
||||||
|
|
||||||
|
self.assertEqual(item["statusInsights"]["severity"], "warning")
|
||||||
|
self.assertIn("expires_soon", item["statusInsights"]["reasons"])
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import unittest
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from apps.base.views import validate_file_type
|
||||||
|
from core.settings import settings
|
||||||
|
|
||||||
|
|
||||||
|
class SettingsOverrideMixin:
|
||||||
|
def setUp(self):
|
||||||
|
self._original_user_config = dict(settings.user_config)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
settings.user_config = self._original_user_config
|
||||||
|
|
||||||
|
|
||||||
|
class FileTypeValidationTests(SettingsOverrideMixin, unittest.TestCase):
|
||||||
|
def test_allows_extensions_and_mime_patterns(self):
|
||||||
|
settings.allowed_file_types = ["rar", ".zip", "image/*"]
|
||||||
|
|
||||||
|
validate_file_type("backup.RAR")
|
||||||
|
validate_file_type("archive.zip")
|
||||||
|
validate_file_type("avatar.bin", "image/png")
|
||||||
|
|
||||||
|
def test_rejects_disallowed_file_type(self):
|
||||||
|
settings.allowed_file_types = ["rar"]
|
||||||
|
|
||||||
|
with self.assertRaises(HTTPException) as error:
|
||||||
|
validate_file_type("payload.exe", "application/octet-stream")
|
||||||
|
|
||||||
|
self.assertEqual(error.exception.status_code, 403)
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import asyncio
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import apps.base.views as views
|
||||||
|
from apps.base.views import normalize_share_code
|
||||||
|
|
||||||
|
|
||||||
|
class FakeFileCodes:
|
||||||
|
seen_code = None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def filter(cls, **kwargs):
|
||||||
|
cls.seen_code = kwargs.get("code")
|
||||||
|
return cls()
|
||||||
|
|
||||||
|
async def first(self):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class RetrieveCodeTests(unittest.TestCase):
|
||||||
|
def test_normalize_share_code_strips_surrounding_whitespace(self):
|
||||||
|
self.assertEqual(normalize_share_code(" 12345\n"), "12345")
|
||||||
|
|
||||||
|
def test_get_code_file_by_code_queries_normalized_code(self):
|
||||||
|
original_file_codes = views.FileCodes
|
||||||
|
views.FileCodes = FakeFileCodes
|
||||||
|
try:
|
||||||
|
has_file, message = asyncio.run(views.get_code_file_by_code(" 12345\n"))
|
||||||
|
finally:
|
||||||
|
views.FileCodes = original_file_codes
|
||||||
|
|
||||||
|
self.assertFalse(has_file)
|
||||||
|
self.assertEqual(message, "文件不存在")
|
||||||
|
self.assertEqual(FakeFileCodes.seen_code, "12345")
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import asyncio
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
|
from core.settings import BASE_DIR, settings
|
||||||
|
from main import index, resolve_theme_file
|
||||||
|
|
||||||
|
|
||||||
|
class SettingsOverrideMixin:
|
||||||
|
def setUp(self):
|
||||||
|
self._original_user_config = dict(settings.user_config)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
settings.user_config = self._original_user_config
|
||||||
|
|
||||||
|
|
||||||
|
class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
|
||||||
|
def get_theme_index_asset(self, theme: str) -> str:
|
||||||
|
assets = sorted((BASE_DIR / theme / "assets").glob("index-*.js"))
|
||||||
|
self.assertTrue(assets, f"{theme} 缺少 index JS 资源")
|
||||||
|
return assets[0].name
|
||||||
|
|
||||||
|
def test_resolves_assets_from_current_theme(self):
|
||||||
|
settings.themesSelect = "themes/2023"
|
||||||
|
theme_2023_asset = resolve_theme_file(
|
||||||
|
"assets", self.get_theme_index_asset("themes/2023")
|
||||||
|
)
|
||||||
|
|
||||||
|
settings.themesSelect = "themes/2024"
|
||||||
|
theme_2024_asset = resolve_theme_file(
|
||||||
|
"assets", self.get_theme_index_asset("themes/2024")
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertIn("themes/2023/assets", str(theme_2023_asset))
|
||||||
|
self.assertIn("themes/2024/assets", str(theme_2024_asset))
|
||||||
|
|
||||||
|
def test_rejects_theme_asset_path_traversal(self):
|
||||||
|
settings.themesSelect = "themes/2024"
|
||||||
|
|
||||||
|
with self.assertRaises(HTTPException) as error:
|
||||||
|
resolve_theme_file("assets", "..", "..", "core", "settings.py")
|
||||||
|
|
||||||
|
self.assertEqual(error.exception.status_code, 404)
|
||||||
|
|
||||||
|
def test_index_keeps_absolute_asset_urls(self):
|
||||||
|
settings.themesSelect = "themes/2023"
|
||||||
|
|
||||||
|
response = asyncio.run(index())
|
||||||
|
html = response.body.decode("utf-8")
|
||||||
|
|
||||||
|
self.assertIn('src="/assets/', html)
|
||||||
|
self.assertIn('href="/assets/', html)
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import asyncio
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from core.storage import S3FileStorage
|
||||||
|
|
||||||
|
|
||||||
|
class FakeS3Client:
|
||||||
|
def __init__(self, list_response):
|
||||||
|
self.list_response = list_response
|
||||||
|
self.head_calls = 0
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, exc_type, exc, traceback):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def head_object(self, **kwargs):
|
||||||
|
self.head_calls += 1
|
||||||
|
raise RuntimeError("head not supported")
|
||||||
|
|
||||||
|
async def list_objects_v2(self, **kwargs):
|
||||||
|
return self.list_response
|
||||||
|
|
||||||
|
|
||||||
|
class S3FileExistsTests(unittest.TestCase):
|
||||||
|
def test_file_exists_falls_back_to_list_objects(self):
|
||||||
|
client = FakeS3Client({"Contents": [{"Key": "share/data/file.txt"}]})
|
||||||
|
storage = S3FileStorage.__new__(S3FileStorage)
|
||||||
|
storage.bucket_name = "bucket"
|
||||||
|
storage._client = lambda: client
|
||||||
|
|
||||||
|
exists = asyncio.run(storage.file_exists("share/data/file.txt"))
|
||||||
|
|
||||||
|
self.assertTrue(exists)
|
||||||
|
self.assertEqual(client.head_calls, 3)
|
||||||
|
|
||||||
|
def test_file_exists_returns_false_when_missing(self):
|
||||||
|
client = FakeS3Client({"Contents": [{"Key": "share/data/other.txt"}]})
|
||||||
|
storage = S3FileStorage.__new__(S3FileStorage)
|
||||||
|
storage.bucket_name = "bucket"
|
||||||
|
storage._client = lambda: client
|
||||||
|
|
||||||
|
exists = asyncio.run(storage.file_exists("share/data/file.txt"))
|
||||||
|
|
||||||
|
self.assertFalse(exists)
|
||||||
Reference in new issue
Block a user