style: code format
This commit is contained in:
+17
-14
@@ -18,16 +18,15 @@ def create_token(data: dict, expires_in: int = 3600 * 24) -> str:
|
||||
:param data: 数据负载
|
||||
:param expires_in: 过期时间(秒)
|
||||
"""
|
||||
header = base64.b64encode(json.dumps({"alg": "HS256", "typ": "JWT"}).encode()).decode()
|
||||
payload = base64.b64encode(json.dumps({
|
||||
**data,
|
||||
"exp": int(time.time()) + expires_in
|
||||
}).encode()).decode()
|
||||
header = base64.b64encode(
|
||||
json.dumps({"alg": "HS256", "typ": "JWT"}).encode()
|
||||
).decode()
|
||||
payload = base64.b64encode(
|
||||
json.dumps({**data, "exp": int(time.time()) + expires_in}).encode()
|
||||
).decode()
|
||||
|
||||
signature = hmac.new(
|
||||
settings.admin_token.encode(),
|
||||
f"{header}.{payload}".encode(),
|
||||
'sha256'
|
||||
settings.admin_token.encode(), f"{header}.{payload}".encode(), "sha256"
|
||||
).digest()
|
||||
signature = base64.b64encode(signature).decode()
|
||||
|
||||
@@ -41,13 +40,13 @@ def verify_token(token: str) -> dict:
|
||||
:return: 解码后的数据
|
||||
"""
|
||||
try:
|
||||
header_b64, payload_b64, signature_b64 = token.split('.')
|
||||
header_b64, payload_b64, signature_b64 = token.split(".")
|
||||
|
||||
# 验证签名
|
||||
expected_signature = hmac.new(
|
||||
settings.admin_token.encode(),
|
||||
f"{header_b64}.{payload_b64}".encode(),
|
||||
'sha256'
|
||||
"sha256",
|
||||
).digest()
|
||||
expected_signature_b64 = base64.b64encode(expected_signature).decode()
|
||||
|
||||
@@ -66,7 +65,9 @@ def verify_token(token: str) -> dict:
|
||||
raise ValueError(f"token验证失败: {str(e)}")
|
||||
|
||||
|
||||
async def admin_required(authorization: str = Header(default=None), request: Request = None):
|
||||
async def admin_required(
|
||||
authorization: str = Header(default=None), request: Request = None
|
||||
):
|
||||
"""
|
||||
验证管理员权限
|
||||
"""
|
||||
@@ -81,12 +82,14 @@ async def admin_required(authorization: str = Header(default=None), request: Req
|
||||
except ValueError as e:
|
||||
is_admin = False
|
||||
|
||||
if request.url.path.startswith('/share/'):
|
||||
if request.url.path.startswith("/share/"):
|
||||
if not settings.openUpload and not is_admin:
|
||||
raise HTTPException(status_code=403, detail='本站未开启游客上传,如需上传请先登录后台')
|
||||
raise HTTPException(
|
||||
status_code=403, detail="本站未开启游客上传,如需上传请先登录后台"
|
||||
)
|
||||
else:
|
||||
if not is_admin:
|
||||
raise HTTPException(status_code=401, detail='未授权或授权校验失败')
|
||||
raise HTTPException(status_code=401, detail="未授权或授权校验失败")
|
||||
return is_admin
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=401, detail=str(e))
|
||||
|
||||
@@ -7,7 +7,7 @@ class IDData(BaseModel):
|
||||
|
||||
class ShareItem(BaseModel):
|
||||
expire_value: int
|
||||
expire_style: str = 'day'
|
||||
expire_style: str = "day"
|
||||
filename: str
|
||||
|
||||
|
||||
|
||||
+39
-22
@@ -19,16 +19,18 @@ class FileService:
|
||||
await self.file_storage.delete_file(file_code)
|
||||
await file_code.delete()
|
||||
|
||||
async def list_files(self, page: int, size: int, keyword: str = ''):
|
||||
async def list_files(self, page: int, size: int, keyword: str = ""):
|
||||
offset = (page - 1) * size
|
||||
files = await FileCodes.filter(prefix__icontains=keyword).limit(size).offset(offset)
|
||||
files = (
|
||||
await FileCodes.filter(prefix__icontains=keyword).limit(size).offset(offset)
|
||||
)
|
||||
total = await FileCodes.filter(prefix__icontains=keyword).count()
|
||||
return files, total
|
||||
|
||||
async def download_file(self, file_id: int):
|
||||
file_code = await FileCodes.filter(id=file_id).first()
|
||||
if not file_code:
|
||||
raise HTTPException(status_code=404, detail='文件不存在')
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
if file_code.text:
|
||||
return APIResponse(detail=file_code.text)
|
||||
else:
|
||||
@@ -37,10 +39,12 @@ class FileService:
|
||||
async def share_local_file(self, item):
|
||||
local_file = LocalFileClass(item.filename)
|
||||
if not await local_file.exists():
|
||||
raise HTTPException(status_code=404, detail='文件不存在')
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
|
||||
text = await local_file.read()
|
||||
expired_at, expired_count, used_count, code = await get_expire_info(item.expire_value, item.expire_style)
|
||||
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)
|
||||
@@ -58,8 +62,8 @@ class FileService:
|
||||
)
|
||||
|
||||
return {
|
||||
'code': code,
|
||||
'name': local_file.file,
|
||||
"code": code,
|
||||
"name": local_file.file,
|
||||
}
|
||||
|
||||
|
||||
@@ -68,21 +72,32 @@ class ConfigService:
|
||||
return settings.items()
|
||||
|
||||
async def update_config(self, data: dict):
|
||||
admin_token = data.get('admin_token')
|
||||
if admin_token is None or admin_token == '':
|
||||
raise HTTPException(status_code=400, detail='管理员密码不能为空')
|
||||
admin_token = data.get("admin_token")
|
||||
if admin_token is None or admin_token == "":
|
||||
raise HTTPException(status_code=400, detail="管理员密码不能为空")
|
||||
|
||||
for key, value in data.items():
|
||||
if key not in settings.default_config:
|
||||
continue
|
||||
if key in ['errorCount', 'errorMinute', 'max_save_seconds', 'onedrive_proxy', 'openUpload', 'port', 's3_proxy', 'uploadCount', 'uploadMinute', 'uploadSize']:
|
||||
if key in [
|
||||
"errorCount",
|
||||
"errorMinute",
|
||||
"max_save_seconds",
|
||||
"onedrive_proxy",
|
||||
"openUpload",
|
||||
"port",
|
||||
"s3_proxy",
|
||||
"uploadCount",
|
||||
"uploadMinute",
|
||||
"uploadSize",
|
||||
]:
|
||||
data[key] = int(value)
|
||||
elif key in ['opacity']:
|
||||
elif key in ["opacity"]:
|
||||
data[key] = float(value)
|
||||
else:
|
||||
data[key] = value
|
||||
|
||||
await KeyValue.filter(key='settings').update(value=data)
|
||||
await KeyValue.filter(key="settings").update(value=data)
|
||||
for k, v in data.items():
|
||||
settings.__setattr__(k, v)
|
||||
|
||||
@@ -90,9 +105,9 @@ class ConfigService:
|
||||
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'):
|
||||
if not os.path.exists(data_root / "local"):
|
||||
os.makedirs(data_root / "local")
|
||||
for file in os.listdir(data_root / "local"):
|
||||
files.append(LocalFileClass(file))
|
||||
return files
|
||||
|
||||
@@ -100,22 +115,24 @@ class LocalFileService:
|
||||
file = LocalFileClass(filename)
|
||||
if await file.exists():
|
||||
await file.delete()
|
||||
return '删除成功'
|
||||
raise HTTPException(status_code=404, detail='文件不存在')
|
||||
return "删除成功"
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
|
||||
|
||||
class LocalFileClass:
|
||||
def __init__(self, file):
|
||||
self.file = file
|
||||
self.path = data_root / 'local' / file
|
||||
self.ctime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.path.getctime(self.path)))
|
||||
self.path = data_root / "local" / 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)
|
||||
|
||||
async def read(self):
|
||||
return open(self.path, 'rb')
|
||||
return open(self.path, "rb")
|
||||
|
||||
async def write(self, data):
|
||||
with open(self.path, 'w') as f:
|
||||
with open(self.path, "w") as f:
|
||||
f.write(data)
|
||||
|
||||
async def delete(self):
|
||||
|
||||
+65
-62
@@ -6,35 +6,37 @@ import datetime
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from apps.admin.services import FileService, ConfigService, LocalFileService
|
||||
from apps.admin.dependencies import admin_required, get_file_service, get_config_service, get_local_file_service
|
||||
from apps.admin.dependencies import (
|
||||
admin_required,
|
||||
get_file_service,
|
||||
get_config_service,
|
||||
get_local_file_service,
|
||||
)
|
||||
from apps.admin.schemas import IDData, ShareItem, DeleteItem, LoginData
|
||||
from core.response import APIResponse
|
||||
from apps.base.models import FileCodes, KeyValue
|
||||
from apps.admin.dependencies import create_token
|
||||
from core.settings import settings
|
||||
|
||||
admin_api = APIRouter(prefix='/admin', tags=['管理'])
|
||||
admin_api = APIRouter(prefix="/admin", tags=["管理"])
|
||||
|
||||
|
||||
@admin_api.post('/login')
|
||||
@admin_api.post("/login")
|
||||
async def login(data: LoginData):
|
||||
# 验证管理员密码
|
||||
if data.password != settings.admin_token:
|
||||
raise HTTPException(status_code=401, detail="密码错误")
|
||||
|
||||
|
||||
# 生成包含管理员身份的token
|
||||
token = create_token({"is_admin": True})
|
||||
return APIResponse(detail={
|
||||
"token": token,
|
||||
"token_type": "Bearer"
|
||||
})
|
||||
return APIResponse(detail={"token": token, "token_type": "Bearer"})
|
||||
|
||||
|
||||
@admin_api.get('/dashboard')
|
||||
@admin_api.get("/dashboard")
|
||||
async def dashboard(admin: bool = Depends(admin_required)):
|
||||
all_codes = await FileCodes.all()
|
||||
all_size = str(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 = datetime.datetime.now()
|
||||
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
@@ -42,104 +44,105 @@ async def dashboard(admin: bool = Depends(admin_required)):
|
||||
yesterday_end = today_start - datetime.timedelta(microseconds=1)
|
||||
# 统计昨天一整天的记录数(从昨天0点到23:59:59)
|
||||
yesterday_codes = FileCodes.filter(
|
||||
created_at__gte=yesterday_start,
|
||||
created_at__lte=yesterday_end
|
||||
created_at__gte=yesterday_start, created_at__lte=yesterday_end
|
||||
)
|
||||
# 统计今天到现在的记录数(从今天0点到现在)
|
||||
today_codes = FileCodes.filter(
|
||||
created_at__gte=today_start
|
||||
today_codes = FileCodes.filter(created_at__gte=today_start)
|
||||
return APIResponse(
|
||||
detail={
|
||||
"totalFiles": len(all_codes),
|
||||
"storageUsed": all_size,
|
||||
"sysUptime": sys_start.value,
|
||||
"yesterdayCount": await yesterday_codes.count(),
|
||||
"yesterdaySize": str(sum([code.size for code in await yesterday_codes])),
|
||||
"todayCount": await today_codes.count(),
|
||||
"todaySize": str(sum([code.size for code in await today_codes])),
|
||||
}
|
||||
)
|
||||
return APIResponse(detail={
|
||||
'totalFiles': len(all_codes),
|
||||
'storageUsed': all_size,
|
||||
'sysUptime': sys_start.value,
|
||||
'yesterdayCount': await yesterday_codes.count(),
|
||||
'yesterdaySize': str(sum([code.size for code in await yesterday_codes])),
|
||||
'todayCount': await today_codes.count(),
|
||||
'todaySize': str(sum([code.size for code in await today_codes])),
|
||||
})
|
||||
|
||||
|
||||
@admin_api.delete('/file/delete')
|
||||
@admin_api.delete("/file/delete")
|
||||
async def file_delete(
|
||||
data: IDData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required)
|
||||
data: IDData,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
):
|
||||
await file_service.delete_file(data.id)
|
||||
return APIResponse()
|
||||
|
||||
|
||||
@admin_api.get('/file/list')
|
||||
@admin_api.get("/file/list")
|
||||
async def file_list(
|
||||
page: int = 1,
|
||||
size: int = 10,
|
||||
keyword: str = '',
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required)
|
||||
page: int = 1,
|
||||
size: int = 10,
|
||||
keyword: str = "",
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
):
|
||||
files, total = await file_service.list_files(page, size, keyword)
|
||||
return APIResponse(detail={
|
||||
'page': page,
|
||||
'size': size,
|
||||
'data': files,
|
||||
'total': total,
|
||||
})
|
||||
return APIResponse(
|
||||
detail={
|
||||
"page": page,
|
||||
"size": size,
|
||||
"data": files,
|
||||
"total": total,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@admin_api.get('/config/get')
|
||||
@admin_api.get("/config/get")
|
||||
async def get_config(
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
admin: bool = Depends(admin_required)
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
):
|
||||
return APIResponse(detail=config_service.get_config())
|
||||
|
||||
|
||||
@admin_api.patch('/config/update')
|
||||
@admin_api.patch("/config/update")
|
||||
async def update_config(
|
||||
data: dict,
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
admin: bool = Depends(admin_required)
|
||||
data: dict,
|
||||
config_service: ConfigService = Depends(get_config_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
):
|
||||
data.pop('themesChoices')
|
||||
data.pop("themesChoices")
|
||||
await config_service.update_config(data)
|
||||
return APIResponse()
|
||||
|
||||
|
||||
@admin_api.get('/file/download')
|
||||
@admin_api.get("/file/download")
|
||||
async def file_download(
|
||||
id: int,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required)
|
||||
id: int,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
):
|
||||
file_content = await file_service.download_file(id)
|
||||
return file_content
|
||||
|
||||
|
||||
@admin_api.get('/local/lists')
|
||||
@admin_api.get("/local/lists")
|
||||
async def get_local_lists(
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
admin: bool = Depends(admin_required)
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
):
|
||||
files = await local_file_service.list_files()
|
||||
return APIResponse(detail=files)
|
||||
|
||||
|
||||
@admin_api.delete('/local/delete')
|
||||
@admin_api.delete("/local/delete")
|
||||
async def delete_local_file(
|
||||
item: DeleteItem,
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
admin: bool = Depends(admin_required)
|
||||
item: DeleteItem,
|
||||
local_file_service: LocalFileService = Depends(get_local_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
):
|
||||
result = await local_file_service.delete_file(item.filename)
|
||||
return APIResponse(detail=result)
|
||||
|
||||
|
||||
@admin_api.post('/local/share')
|
||||
@admin_api.post("/local/share")
|
||||
async def share_local_file(
|
||||
item: ShareItem,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required)
|
||||
item: ShareItem,
|
||||
file_service: FileService = Depends(get_file_service),
|
||||
admin: bool = Depends(admin_required),
|
||||
):
|
||||
share_info = await file_service.share_local_file(item)
|
||||
return APIResponse(detail=share_info)
|
||||
|
||||
Reference in New Issue
Block a user