feat: 整合官方 2.7.0 安全修复与本地文件分享
This commit is contained in:
1 parent
b10113e5ab
commit
9e9571b031
42 files changed
+2824
-268
No files matched your search
+244
-222
@@ -1,13 +1,17 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
from apps.base.local_share import (
|
||||
LOCAL_REF_MARKER, MAX_LIST_ENTRIES, build_local_ref_download,
|
||||
format_local_ctime, get_local_root, is_local_ref, normalize_local_relpath,
|
||||
resolve_under_local, should_skip_storage_delete,
|
||||
)
|
||||
from core.response import APIResponse
|
||||
from core.storage import FileStorageInterface, storages
|
||||
from core.settings import (
|
||||
@@ -19,16 +23,18 @@ from core.config import refresh_settings
|
||||
from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret
|
||||
from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats, file_codes_pydantic
|
||||
|
||||
from apps.base.utils import get_expire_info, get_file_path_name, get_random_code
|
||||
from apps.base.quota import release_storage, reserve_storage
|
||||
from apps.base.utils import get_expire_info, get_random_code
|
||||
from fastapi import HTTPException
|
||||
from core.settings import data_root
|
||||
from core.utils import get_now, hash_password, is_password_hashed
|
||||
from core.utils import get_now, hash_password, is_password_hashed, validate_background_url
|
||||
|
||||
|
||||
from apps.admin.trash_management import TrashManagementMixin
|
||||
|
||||
|
||||
# Single-worker deployments serialize JSON read/modify/write operations.
|
||||
keyvalue_write_lock = asyncio.Lock()
|
||||
|
||||
|
||||
class FileService(TrashManagementMixin):
|
||||
FILE_METADATA_KEY_PREFIX = "admin_file_metadata:"
|
||||
FILE_VIEW_PRESETS_KEY = "admin_file_view_presets"
|
||||
@@ -140,7 +146,7 @@ class FileService(TrashManagementMixin):
|
||||
return file_code
|
||||
now = await get_now()
|
||||
original_path = await file_code.get_file_path() if file_code.text is None else ""
|
||||
if file_code.text is None:
|
||||
if not should_skip_storage_delete(file_code):
|
||||
await self.file_storage.move_file(file_code, self._trash_path(file_code))
|
||||
await file_code.update_from_dict(
|
||||
{
|
||||
@@ -172,7 +178,7 @@ class FileService(TrashManagementMixin):
|
||||
if file_code.trash_purged_at is not None:
|
||||
raise HTTPException(status_code=409, detail="文件本体已永久清理,仅保留审计记录")
|
||||
original_path = file_code.trash_original_path or ""
|
||||
if file_code.text is None:
|
||||
if not should_skip_storage_delete(file_code):
|
||||
if not original_path:
|
||||
raise HTTPException(status_code=409, detail="缺少原始文件路径,无法恢复")
|
||||
destination_dir, filename = os.path.split(original_path)
|
||||
@@ -226,7 +232,7 @@ class FileService(TrashManagementMixin):
|
||||
async def purge_trashed_file(self, file_code: FileCodes) -> None:
|
||||
if file_code.trash_purged_at is not None:
|
||||
return
|
||||
if file_code.text is None:
|
||||
if not should_skip_storage_delete(file_code):
|
||||
trash_path = self._trash_path(file_code)
|
||||
await self.file_storage.delete_file(
|
||||
FileCodes(
|
||||
@@ -456,44 +462,45 @@ class FileService(TrashManagementMixin):
|
||||
name: str,
|
||||
filters: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
presets = await self._get_file_view_presets()
|
||||
normalized_name = self._normalize_file_view_preset_name(name)
|
||||
normalized_filters = self._normalize_file_view_preset_filters(filters)
|
||||
now = await get_now()
|
||||
updated_at = now.isoformat()
|
||||
async with keyvalue_write_lock:
|
||||
presets = await self._get_file_view_presets()
|
||||
normalized_name = self._normalize_file_view_preset_name(name)
|
||||
normalized_filters = self._normalize_file_view_preset_filters(filters)
|
||||
now = await get_now()
|
||||
updated_at = now.isoformat()
|
||||
|
||||
target_index = next(
|
||||
(index for index, preset in enumerate(presets) if preset["id"] == preset_id),
|
||||
-1,
|
||||
)
|
||||
is_update = target_index >= 0
|
||||
if is_update:
|
||||
preset = presets[target_index]
|
||||
next_preset = {
|
||||
**preset,
|
||||
"name": normalized_name,
|
||||
"filters": normalized_filters,
|
||||
"params": normalized_filters,
|
||||
"updatedAt": updated_at,
|
||||
"updated_at": updated_at,
|
||||
}
|
||||
presets[target_index] = next_preset
|
||||
else:
|
||||
if len(presets) >= self.MAX_VIEW_PRESETS:
|
||||
raise HTTPException(status_code=400, detail="视图预设数量已达上限")
|
||||
next_preset = {
|
||||
"id": preset_id or self._build_file_view_preset_id(normalized_name, now),
|
||||
"name": normalized_name,
|
||||
"filters": normalized_filters,
|
||||
"params": normalized_filters,
|
||||
"createdAt": updated_at,
|
||||
"created_at": updated_at,
|
||||
"updatedAt": updated_at,
|
||||
"updated_at": updated_at,
|
||||
}
|
||||
presets.append(next_preset)
|
||||
target_index = next(
|
||||
(index for index, preset in enumerate(presets) if preset["id"] == preset_id),
|
||||
-1,
|
||||
)
|
||||
is_update = target_index >= 0
|
||||
if is_update:
|
||||
preset = presets[target_index]
|
||||
next_preset = {
|
||||
**preset,
|
||||
"name": normalized_name,
|
||||
"filters": normalized_filters,
|
||||
"params": normalized_filters,
|
||||
"updatedAt": updated_at,
|
||||
"updated_at": updated_at,
|
||||
}
|
||||
presets[target_index] = next_preset
|
||||
else:
|
||||
if len(presets) >= self.MAX_VIEW_PRESETS:
|
||||
raise HTTPException(status_code=400, detail="视图预设数量已达上限")
|
||||
next_preset = {
|
||||
"id": preset_id or self._build_file_view_preset_id(normalized_name, now),
|
||||
"name": normalized_name,
|
||||
"filters": normalized_filters,
|
||||
"params": normalized_filters,
|
||||
"createdAt": updated_at,
|
||||
"created_at": updated_at,
|
||||
"updatedAt": updated_at,
|
||||
"updated_at": updated_at,
|
||||
}
|
||||
presets.append(next_preset)
|
||||
|
||||
await self._save_file_view_presets(presets)
|
||||
await self._save_file_view_presets(presets)
|
||||
await self.record_admin_activity(
|
||||
action="file.view_preset_update" if is_update else "file.view_preset_create",
|
||||
target_type="view_preset",
|
||||
@@ -509,16 +516,17 @@ class FileService(TrashManagementMixin):
|
||||
if not preset_id:
|
||||
raise HTTPException(status_code=400, detail="请选择要删除的视图预设")
|
||||
|
||||
presets = await self._get_file_view_presets()
|
||||
deleted_preset = next(
|
||||
(preset for preset in presets if preset["id"] == preset_id),
|
||||
None,
|
||||
)
|
||||
next_presets = [preset for preset in presets if preset["id"] != preset_id]
|
||||
if len(next_presets) == len(presets):
|
||||
raise HTTPException(status_code=404, detail="视图预设不存在")
|
||||
async with keyvalue_write_lock:
|
||||
presets = await self._get_file_view_presets()
|
||||
deleted_preset = next(
|
||||
(preset for preset in presets if preset["id"] == preset_id),
|
||||
None,
|
||||
)
|
||||
next_presets = [preset for preset in presets if preset["id"] != preset_id]
|
||||
if len(next_presets) == len(presets):
|
||||
raise HTTPException(status_code=404, detail="视图预设不存在")
|
||||
|
||||
await self._save_file_view_presets(next_presets)
|
||||
await self._save_file_view_presets(next_presets)
|
||||
await self.record_admin_activity(
|
||||
action="file.view_preset_delete",
|
||||
target_type="view_preset",
|
||||
@@ -635,7 +643,7 @@ class FileService(TrashManagementMixin):
|
||||
"fileCount": 0,
|
||||
"chunkedCount": 0,
|
||||
**self._empty_health_summary(),
|
||||
"storageUsed": sum(file_code.size for file_code in all_files),
|
||||
"storageUsed": sum(file_code.size for file_code in all_files if not is_local_ref(file_code)),
|
||||
"usedCount": sum(file_code.used_count for file_code in all_files),
|
||||
}
|
||||
|
||||
@@ -1009,12 +1017,13 @@ class FileService(TrashManagementMixin):
|
||||
if not activity:
|
||||
return None
|
||||
|
||||
activities = await self._get_admin_activities()
|
||||
next_activities = [
|
||||
activity,
|
||||
*[item for item in activities if item["id"] != activity["id"]],
|
||||
][: self.MAX_ADMIN_ACTIVITIES]
|
||||
await self._save_admin_activities(next_activities)
|
||||
async with keyvalue_write_lock:
|
||||
activities = await self._get_admin_activities()
|
||||
next_activities = [
|
||||
activity,
|
||||
*[item for item in activities if item["id"] != activity["id"]],
|
||||
][: self.MAX_ADMIN_ACTIVITIES]
|
||||
await self._save_admin_activities(next_activities)
|
||||
return activity
|
||||
except Exception:
|
||||
return None
|
||||
@@ -1632,6 +1641,8 @@ class FileService(TrashManagementMixin):
|
||||
if file_code.text:
|
||||
return APIResponse(detail=file_code.text)
|
||||
else:
|
||||
if is_local_ref(file_code):
|
||||
return build_local_ref_download(file_code)
|
||||
return await self.file_storage.get_file_response(file_code)
|
||||
|
||||
async def preview_file(self, file_id: int, max_chars: int = 4000):
|
||||
@@ -1667,40 +1678,28 @@ class FileService(TrashManagementMixin):
|
||||
if not await local_file.exists():
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
|
||||
reservation_token = f"local:{uuid.uuid4().hex}"
|
||||
await reserve_storage(reservation_token, local_file.size, ttl_seconds=3600)
|
||||
try:
|
||||
text = await local_file.read()
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
item.expire_value, item.expire_style
|
||||
)
|
||||
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(
|
||||
item
|
||||
)
|
||||
await self.file_storage.save_file(text, save_path)
|
||||
try:
|
||||
await FileCodes.create(
|
||||
code=code,
|
||||
prefix=prefix,
|
||||
suffix=suffix,
|
||||
uuid_file_name=uuid_file_name,
|
||||
file_path=path,
|
||||
size=local_file.size,
|
||||
expired_at=expired_at,
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
)
|
||||
except Exception:
|
||||
await self.file_storage.delete_file(
|
||||
FileCodes(file_path=path, uuid_file_name=uuid_file_name)
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
await release_storage(reservation_token)
|
||||
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(
|
||||
item.expire_value, item.expire_style
|
||||
)
|
||||
name = local_file.name
|
||||
suffix = Path(name).suffix
|
||||
prefix = name[: len(name) - len(suffix)] if suffix else name
|
||||
record = await FileCodes.create(
|
||||
code=code,
|
||||
prefix=prefix,
|
||||
suffix=suffix,
|
||||
uuid_file_name=local_file.file,
|
||||
file_path=LOCAL_REF_MARKER,
|
||||
size=local_file.size or 0,
|
||||
expired_at=expired_at,
|
||||
expired_count=expired_count,
|
||||
used_count=used_count,
|
||||
)
|
||||
return {
|
||||
"code": code,
|
||||
"name": local_file.file,
|
||||
"name": name,
|
||||
"path": local_file.file,
|
||||
"id": record.id,
|
||||
}
|
||||
|
||||
|
||||
@@ -1737,112 +1736,158 @@ class ConfigService:
|
||||
return config
|
||||
|
||||
async def update_config(self, data: dict):
|
||||
current_config = dict(settings.items())
|
||||
next_config = dict(current_config)
|
||||
update_data = {
|
||||
key: value
|
||||
for key, value in data.items()
|
||||
if key in settings.default_config and key not in INTERNAL_CONFIG_KEYS
|
||||
}
|
||||
async with keyvalue_write_lock:
|
||||
await refresh_settings(force=True)
|
||||
current_config = dict(settings.items())
|
||||
next_config = dict(current_config)
|
||||
update_data = {
|
||||
key: value
|
||||
for key, value in data.items()
|
||||
if key in settings.default_config and key not in INTERNAL_CONFIG_KEYS
|
||||
}
|
||||
|
||||
admin_token = update_data.get("admin_token")
|
||||
admin_password_changed = False
|
||||
if admin_token is None or admin_token == "":
|
||||
update_data.pop("admin_token", None)
|
||||
elif not is_password_hashed(admin_token):
|
||||
update_data["admin_token"] = hash_password(admin_token)
|
||||
admin_password_changed = True
|
||||
else:
|
||||
admin_password_changed = True
|
||||
admin_token = update_data.get("admin_token")
|
||||
admin_password_changed = False
|
||||
if admin_token is None or admin_token == "":
|
||||
update_data.pop("admin_token", None)
|
||||
elif not is_password_hashed(admin_token):
|
||||
update_data["admin_token"] = hash_password(admin_token)
|
||||
admin_password_changed = True
|
||||
else:
|
||||
admin_password_changed = True
|
||||
|
||||
for key, value in update_data.items():
|
||||
if value == "" and key in self.INT_FIELDS | self.FLOAT_FIELDS:
|
||||
continue
|
||||
for key, value in update_data.items():
|
||||
if value == "" and key in self.INT_FIELDS | self.FLOAT_FIELDS:
|
||||
continue
|
||||
|
||||
try:
|
||||
if key in self.INT_FIELDS:
|
||||
next_config[key] = int(value)
|
||||
elif key in self.FLOAT_FIELDS:
|
||||
next_config[key] = float(value)
|
||||
else:
|
||||
next_config[key] = value
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail=f"{key} 配置值格式错误")
|
||||
|
||||
try:
|
||||
if key in self.INT_FIELDS:
|
||||
next_config[key] = int(value)
|
||||
elif key in self.FLOAT_FIELDS:
|
||||
next_config[key] = float(value)
|
||||
else:
|
||||
next_config[key] = value
|
||||
session_expire = int(next_config.get("adminSessionExpire"))
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(status_code=400, detail=f"{key} 配置值格式错误")
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="adminSessionExpire 配置值格式错误",
|
||||
)
|
||||
if (
|
||||
not ADMIN_SESSION_EXPIRE_MIN <= session_expire <= ADMIN_SESSION_EXPIRE_MAX
|
||||
or session_expire % ADMIN_SESSION_EXPIRE_MIN != 0
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="adminSessionExpire 必须是 1 到 365 个整天",
|
||||
)
|
||||
next_config["adminSessionExpire"] = session_expire
|
||||
|
||||
try:
|
||||
session_expire = int(next_config.get("adminSessionExpire"))
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="adminSessionExpire 配置值格式错误",
|
||||
)
|
||||
if (
|
||||
not ADMIN_SESSION_EXPIRE_MIN <= session_expire <= ADMIN_SESSION_EXPIRE_MAX
|
||||
or session_expire % ADMIN_SESSION_EXPIRE_MIN != 0
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="adminSessionExpire 必须是 1 到 365 个整天",
|
||||
)
|
||||
next_config["adminSessionExpire"] = session_expire
|
||||
|
||||
try:
|
||||
trash_retention_days = int(
|
||||
next_config.get("trashRetentionDays", FileService.TRASH_DEFAULT_RETENTION_DAYS)
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="trashRetentionDays 配置值格式错误",
|
||||
)
|
||||
if not 1 <= trash_retention_days <= FileService.TRASH_MAX_RETENTION_DAYS:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="trashRetentionDays 必须是 1 到 365 个整天",
|
||||
)
|
||||
next_config["trashRetentionDays"] = trash_retention_days
|
||||
retention_changed = (
|
||||
"trashRetentionDays" in update_data
|
||||
and trash_retention_days != int(
|
||||
current_config.get("trashRetentionDays", FileService.TRASH_DEFAULT_RETENTION_DAYS)
|
||||
)
|
||||
)
|
||||
|
||||
if int(next_config.get("storageLimit", 0)) < 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="storageLimit 不能小于 0",
|
||||
try:
|
||||
trash_retention_days = int(
|
||||
next_config.get("trashRetentionDays", FileService.TRASH_DEFAULT_RETENTION_DAYS)
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="trashRetentionDays 配置值格式错误",
|
||||
)
|
||||
if not 1 <= trash_retention_days <= FileService.TRASH_MAX_RETENTION_DAYS:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="trashRetentionDays 必须是 1 到 365 个整天",
|
||||
)
|
||||
next_config["trashRetentionDays"] = trash_retention_days
|
||||
retention_changed = (
|
||||
"trashRetentionDays" in update_data
|
||||
and trash_retention_days != int(
|
||||
current_config.get("trashRetentionDays", FileService.TRASH_DEFAULT_RETENTION_DAYS)
|
||||
)
|
||||
)
|
||||
|
||||
if admin_password_changed:
|
||||
next_config["jwt_secret"] = generate_jwt_secret()
|
||||
if int(next_config.get("storageLimit", 0)) < 0:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="storageLimit 不能小于 0",
|
||||
)
|
||||
|
||||
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
|
||||
await refresh_settings()
|
||||
if str(next_config.get("background") or "") != str(current_config.get("background") or ""):
|
||||
try:
|
||||
validate_background_url(next_config.get("background"))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
if retention_changed:
|
||||
retention_now = await get_now()
|
||||
retention_expiry = FileService._trash_expiry(retention_now, trash_retention_days)
|
||||
await FileCodes.filter(
|
||||
is_trashed=True,
|
||||
trash_purged_at__isnull=True,
|
||||
trash_expires_at__isnull=False,
|
||||
).update(trash_expires_at=retention_expiry)
|
||||
if admin_password_changed:
|
||||
next_config["jwt_secret"] = generate_jwt_secret()
|
||||
|
||||
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
|
||||
await refresh_settings(force=True)
|
||||
|
||||
if retention_changed:
|
||||
retention_now = await get_now()
|
||||
retention_expiry = FileService._trash_expiry(retention_now, trash_retention_days)
|
||||
await FileCodes.filter(
|
||||
is_trashed=True,
|
||||
trash_purged_at__isnull=True,
|
||||
trash_expires_at__isnull=False,
|
||||
).update(trash_expires_at=retention_expiry)
|
||||
|
||||
class LocalFileService:
|
||||
async def list_files(self):
|
||||
files = []
|
||||
if not os.path.exists(data_root / "local"):
|
||||
os.makedirs(data_root / "local")
|
||||
for file in os.listdir(data_root / "local"):
|
||||
local_file = LocalFileClass(file)
|
||||
files.append({
|
||||
"file": local_file.file,
|
||||
"ctime": local_file.ctime,
|
||||
"size": local_file.size,
|
||||
})
|
||||
return files
|
||||
async def list_files(self, path: str = "", *, legacy: bool = False):
|
||||
relpath = normalize_local_relpath(path, allow_empty=True)
|
||||
directory = resolve_under_local(relpath)
|
||||
if not directory.exists() or not directory.is_dir():
|
||||
raise HTTPException(status_code=404, detail="目录不存在")
|
||||
|
||||
root = get_local_root()
|
||||
items = []
|
||||
try:
|
||||
children = list(directory.iterdir())
|
||||
except OSError as exc:
|
||||
raise HTTPException(status_code=500, detail="无法读取目录") from exc
|
||||
|
||||
children.sort(key=lambda p: (not p.is_dir(), p.name.lower()))
|
||||
truncated = False
|
||||
for child in children:
|
||||
if not legacy and len(items) >= MAX_LIST_ENTRIES:
|
||||
truncated = True
|
||||
break
|
||||
try:
|
||||
resolved = child.resolve()
|
||||
resolved.relative_to(root)
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
if not resolved.is_file() and not resolved.is_dir():
|
||||
continue
|
||||
if legacy and not resolved.is_file():
|
||||
continue
|
||||
child_rel = child.name if not relpath else f"{relpath}/{child.name}"
|
||||
is_dir = resolved.is_dir()
|
||||
items.append(
|
||||
{
|
||||
"file": child.name,
|
||||
"name": child.name,
|
||||
"path": child_rel,
|
||||
"type": "dir" if is_dir else "file",
|
||||
"ctime": format_local_ctime(resolved),
|
||||
"size": None if is_dir else resolved.stat().st_size,
|
||||
}
|
||||
)
|
||||
|
||||
parent = ""
|
||||
if relpath:
|
||||
parent_path = Path(relpath).parent.as_posix()
|
||||
parent = "" if parent_path == "." else parent_path
|
||||
return {
|
||||
"path": relpath,
|
||||
"parent": parent,
|
||||
"truncated": truncated,
|
||||
"items": items,
|
||||
}
|
||||
|
||||
async def delete_file(self, filename: str):
|
||||
file = LocalFileClass(filename)
|
||||
@@ -1854,52 +1899,29 @@ class LocalFileService:
|
||||
|
||||
class LocalFileClass:
|
||||
def __init__(self, file):
|
||||
# 仅允许 data/local 目录下的单层文件名,阻断路径穿越与绝对路径访问。
|
||||
raw_name = str(file or "")
|
||||
normalized = Path(raw_name).as_posix()
|
||||
# 输入本身不得包含路径分隔符或绝对路径形态。
|
||||
if (
|
||||
not raw_name
|
||||
or raw_name in {".", ".."}
|
||||
or normalized in {".", ".."}
|
||||
or "/" in normalized
|
||||
or normalized.startswith("~")
|
||||
or Path(raw_name).is_absolute()
|
||||
or Path(raw_name).name != raw_name
|
||||
):
|
||||
raise HTTPException(status_code=400, detail="非法文件名")
|
||||
|
||||
safe_name = Path(raw_name).name
|
||||
if not safe_name or safe_name in {".", ".."}:
|
||||
raise HTTPException(status_code=400, detail="非法文件名")
|
||||
|
||||
local_root = (data_root / "local").resolve()
|
||||
candidate = (local_root / safe_name).resolve()
|
||||
try:
|
||||
candidate.relative_to(local_root)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="非法文件路径")
|
||||
|
||||
self.file = safe_name
|
||||
self.path = candidate
|
||||
relpath = normalize_local_relpath(file)
|
||||
self.file = relpath
|
||||
self.name = Path(relpath).name
|
||||
self.path = resolve_under_local(relpath)
|
||||
if self.path.is_file():
|
||||
self.ctime = time.strftime(
|
||||
"%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(self.path))
|
||||
)
|
||||
self.size = os.path.getsize(self.path)
|
||||
self.ctime = format_local_ctime(self.path)
|
||||
self.size = self.path.stat().st_size
|
||||
else:
|
||||
self.ctime = None
|
||||
self.size = None
|
||||
|
||||
async def read(self):
|
||||
return open(self.path, "rb")
|
||||
async def read(self) -> bytes:
|
||||
with open(self.path, "rb") as fh:
|
||||
return fh.read()
|
||||
|
||||
async def write(self, data):
|
||||
with open(self.path, "w") as f:
|
||||
with open(self.path, "wb") as f:
|
||||
f.write(data)
|
||||
|
||||
async def delete(self):
|
||||
os.remove(self.path)
|
||||
if not self.path.is_file():
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
self.path.unlink()
|
||||
|
||||
async def exists(self):
|
||||
return self.path.is_file()
|
||||
+36
-19
@@ -7,6 +7,7 @@ from collections import Counter
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from apps.admin import services as admin_services
|
||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||
from apps.admin.dependencies import (
|
||||
admin_required,
|
||||
@@ -31,6 +32,7 @@ from apps.admin.schemas import (
|
||||
LoginData,
|
||||
UpdateFileData,
|
||||
)
|
||||
from apps.base.local_share import is_local_ref
|
||||
from core.response import APIResponse
|
||||
from apps.base.models import FileCodes, KeyValue, ShareCodeReservations, TransferStats
|
||||
from apps.admin.dependencies import (
|
||||
@@ -40,7 +42,8 @@ from apps.admin.dependencies import (
|
||||
)
|
||||
|
||||
from core.settings import settings
|
||||
from core.utils import get_now, verify_password
|
||||
from core.utils import get_now, hash_password, password_needs_rehash, verify_password
|
||||
from core.config import refresh_settings
|
||||
from apps.base.utils import ip_limit
|
||||
|
||||
admin_api = APIRouter(
|
||||
@@ -58,23 +61,34 @@ def _pick_query_text(*values: Optional[str]) -> Optional[str]:
|
||||
|
||||
@admin_api.post("/login")
|
||||
async def login(data: LoginData, ip: str = Depends(ip_limit["login"])):
|
||||
# 登录失败计入 IP 频率限制,超过 loginCount/loginMinute 后暂时锁定
|
||||
if not verify_password(data.password, settings.admin_token):
|
||||
ip_limit["login"].add_ip(ip)
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
# Check and issue the token under the same lock used for password changes.
|
||||
async with admin_services.keyvalue_write_lock:
|
||||
await refresh_settings(force=True)
|
||||
if not verify_password(data.password, settings.admin_token):
|
||||
ip_limit["login"].add_ip(ip)
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
|
||||
expires_in = get_admin_session_expire_seconds()
|
||||
token = create_token({"is_admin": True}, expires_in=expires_in)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"id": "admin",
|
||||
"username": "admin",
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": verify_token(token)["exp"],
|
||||
"expires_in": expires_in,
|
||||
}
|
||||
)
|
||||
if password_needs_rehash(settings.admin_token):
|
||||
record = await KeyValue.filter(key="settings").first()
|
||||
if record:
|
||||
stored = dict(record.value or {})
|
||||
stored["admin_token"] = hash_password(data.password)
|
||||
record.value = stored
|
||||
await record.save()
|
||||
await refresh_settings(force=True)
|
||||
|
||||
expires_in = get_admin_session_expire_seconds()
|
||||
token = create_token({"is_admin": True}, expires_in=expires_in)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"id": "admin",
|
||||
"username": "admin",
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": verify_token(token)["exp"],
|
||||
"expires_in": expires_in,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_api.get("/verify")
|
||||
@@ -107,7 +121,7 @@ async def build_dashboard_recent_file(file_code: FileCodes) -> dict:
|
||||
@admin_api.get("/dashboard")
|
||||
async def dashboard(file_service: FileService = Depends(get_file_service)):
|
||||
all_codes = await FileCodes.filter(is_trashed=False).all()
|
||||
all_size = sum([code.size for code in all_codes])
|
||||
all_size = sum(code.size for code in all_codes if not is_local_ref(code))
|
||||
sys_start = await KeyValue.filter(key="sys_start").first()
|
||||
now = await get_now()
|
||||
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
@@ -816,9 +830,12 @@ async def file_preview(
|
||||
|
||||
@admin_api.get("/local/lists")
|
||||
async def get_local_lists(
|
||||
path: Optional[str] = None,
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
):
|
||||
files = await local_file_service.list_files()
|
||||
listing = await local_file_service.list_files(path or "", legacy=path is None)
|
||||
# 无 path 参数保留旧主题的数组响应;显式 path 支持目录导航。
|
||||
files = listing if path is not None else [item for item in listing["items"] if item["type"] == "file"]
|
||||
return APIResponse(detail=files)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user