v4.2 科目管理优化与多项修复清理
1. 科目管理:代码长度放宽至50(含数据库升级v4.2)、编辑可清空代码、重命名查重、新增 ↑↓ 快捷排序(批量重排接口)、空代码不再显示占位 2. 修复单人加减分提交空名单:showSinglePointsModal 三处重复定义收口到 points-mgmt 并共享选中状态 3. SMTP:SMTP_FROM 默认取 SMTP_USER、SMTP_ENABLED 兼容 1/yes/on、启动日志打印邮件状态、新增邮件测试接口与按钮(返回真实 SMTP 错误) 4. 密码:加密改为 bcrypt 库直连(修复 passlib 兼容问题)、重置密码不再依赖影响行数、前端统一展示422校验错误 5. 冗余清理:删除未用导入/Schema/函数、死文件 admin.js 与 sanitize.py、重复 escapeHtml、重复CSS、重复脚本加载 6. 修复11个文件被写入的 UTF-8 BOM 7. 文档与版本同步至4.2
This commit is contained in:
1 parent
990f44bf22
commit
1068bc6def
58 files changed
+366
-533
No files matched your search
+5
-4
@@ -53,12 +53,13 @@ class Settings:
|
||||
# ========== 站点地址与邮件(找回密码) ==========
|
||||
# 前端站点地址,用于生成密码重置链接,如 https://class.example.com
|
||||
FRONTEND_URL: str = os.getenv("FRONTEND_URL", "").rstrip("/")
|
||||
SMTP_ENABLED: bool = os.getenv("SMTP_ENABLED", "False").lower() == "true"
|
||||
SMTP_HOST: str = os.getenv("SMTP_HOST", "")
|
||||
SMTP_ENABLED: bool = os.getenv("SMTP_ENABLED", "False").strip().lower() in ("true", "1", "yes", "on")
|
||||
SMTP_HOST: str = os.getenv("SMTP_HOST", "").strip()
|
||||
SMTP_PORT: int = int(os.getenv("SMTP_PORT", "465"))
|
||||
SMTP_USER: str = os.getenv("SMTP_USER", "")
|
||||
SMTP_USER: str = os.getenv("SMTP_USER", "").strip()
|
||||
SMTP_PASSWORD: str = os.getenv("SMTP_PASSWORD", "")
|
||||
SMTP_FROM: str = os.getenv("SMTP_FROM", "")
|
||||
# 发件人邮箱默认与登录账号一致
|
||||
SMTP_FROM: str = os.getenv("SMTP_FROM", "").strip() or SMTP_USER
|
||||
SMTP_FROM_NAME: str = os.getenv("SMTP_FROM_NAME", os.getenv("APP_NAME", "班级操行分管理系统"))
|
||||
SMTP_SSL: bool = os.getenv("SMTP_SSL", "True").lower() == "true"
|
||||
SMTP_STARTTLS: bool = os.getenv("SMTP_STARTTLS", "False").lower() == "true"
|
||||
|
||||
@@ -37,6 +37,13 @@ async def lifespan(app: FastAPI):
|
||||
await init_db_pool()
|
||||
await init_redis_pool()
|
||||
logger.info(f"CORS 允许域名: {settings.CORS_ORIGINS}")
|
||||
if settings.SMTP_ENABLED and settings.SMTP_HOST and settings.SMTP_USER and settings.SMTP_PASSWORD:
|
||||
logger.info(
|
||||
f"邮件服务: 已启用 {settings.SMTP_HOST}:{settings.SMTP_PORT} "
|
||||
f"(账号 {settings.SMTP_USER}, 发件人 {settings.SMTP_FROM})"
|
||||
)
|
||||
else:
|
||||
logger.info("邮件服务: 未启用或配置不完整(SMTP_ENABLED=true 且需填写 HOST/USER/PASSWORD)")
|
||||
logger.info(f"{settings.APP_NAME} 启动完成")
|
||||
|
||||
yield
|
||||
|
||||
@@ -11,19 +11,15 @@
|
||||
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
from fastapi.responses import JSONResponse
|
||||
from typing import Optional, Dict, Any
|
||||
import re
|
||||
|
||||
from config import settings
|
||||
from utils.jwt_handler import jwt_handler
|
||||
from utils.redis_client import RedisClient
|
||||
from utils.response import unauthorized_response
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# 不需要认证的路由
|
||||
PUBLIC_PATHS = [
|
||||
r'^/$',
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 后端服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
# 联系方式: admin@sea-studio.top
|
||||
# 版权归属: Sea Network Technology Studio
|
||||
# 许可证: MIT License
|
||||
#
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from fastapi import Request
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from typing import Dict, Any
|
||||
import re
|
||||
|
||||
|
||||
class SanitizeMiddleware(BaseHTTPMiddleware):
|
||||
"""输入过滤中间件"""
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
# 只处理POST、PUT、PATCH请求
|
||||
if request.method in ["POST", "PUT", "PATCH"]:
|
||||
# 获取请求体
|
||||
body = await request.body()
|
||||
if body:
|
||||
import json
|
||||
try:
|
||||
data = json.loads(body)
|
||||
# 清理数据
|
||||
cleaned_data = self._sanitize_data(data)
|
||||
# 替换请求体
|
||||
request._body = json.dumps(cleaned_data).encode()
|
||||
except:
|
||||
pass
|
||||
|
||||
response = await call_next(request)
|
||||
return response
|
||||
|
||||
def _sanitize_data(self, data: Any) -> Any:
|
||||
"""递归清理数据"""
|
||||
if isinstance(data, dict):
|
||||
return {k: self._sanitize_data(v) for k, v in data.items()}
|
||||
elif isinstance(data, list):
|
||||
return [self._sanitize_data(item) for item in data]
|
||||
elif isinstance(data, str):
|
||||
return self._sanitize_string(data)
|
||||
else:
|
||||
return data
|
||||
|
||||
def _sanitize_string(self, value: str) -> str:
|
||||
"""清理字符串"""
|
||||
if not value:
|
||||
return ""
|
||||
|
||||
# 去除首尾空格
|
||||
value = value.strip()
|
||||
|
||||
# SQL注入模式检测
|
||||
sql_patterns = [
|
||||
r'(?i)(\bunion\b\s+\bselect\b)',
|
||||
r'(?i)(\bor\b\s+\d+\s*=\s*\d+)',
|
||||
r'(?i)(\bdrop\b\s+\btable\b)',
|
||||
r'(?i)(\bdelete\b\s+\bfrom\b)',
|
||||
r'(?i)(\binsert\b\s+\binto\b)',
|
||||
r'(?i)(\bupdate\b\s+\w+\s+\bset\b)',
|
||||
]
|
||||
for pattern in sql_patterns:
|
||||
value = re.sub(pattern, '', value)
|
||||
|
||||
# 路径遍历检测
|
||||
value = value.replace('../', '').replace('..\\', '')
|
||||
|
||||
# 限制长度
|
||||
if len(value) > 1000:
|
||||
value = value[:1000]
|
||||
|
||||
# 转义HTML特殊字符
|
||||
html_chars = {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
'/': '/'
|
||||
}
|
||||
for char, escape in html_chars.items():
|
||||
value = value.replace(char, escape)
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def sanitize_input(value: str, max_length: int = 255) -> str:
|
||||
"""清理单个输入值"""
|
||||
if not value:
|
||||
return ""
|
||||
|
||||
value = value.strip()
|
||||
if len(value) > max_length:
|
||||
value = value[:max_length]
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def validate_points(points: int, min_val: int = -100, max_val: int = 100) -> tuple:
|
||||
"""
|
||||
验证分值
|
||||
返回: (是否有效, 错误信息)
|
||||
"""
|
||||
if points == 0:
|
||||
return False, "分值不能为0"
|
||||
if points < min_val or points > max_val:
|
||||
return False, f"分值必须在{min_val}到{max_val}之间"
|
||||
return True, ""
|
||||
|
||||
|
||||
def validate_reason(reason: str) -> tuple:
|
||||
"""
|
||||
验证原因
|
||||
返回: (是否有效, 错误信息)
|
||||
"""
|
||||
if not reason or not reason.strip():
|
||||
return False, "原因不能为空"
|
||||
# 计算可见字符长度(不含换行符),支持多行输入
|
||||
visible_length = len(reason.replace('\n', ''))
|
||||
if visible_length > 255:
|
||||
return False, "原因长度不能超过255个字符"
|
||||
return True, ""
|
||||
|
||||
|
||||
def validate_date(date_str: str) -> bool:
|
||||
"""验证日期格式 YYYY-MM-DD"""
|
||||
if not date_str:
|
||||
return False
|
||||
pattern = r'^\d{4}-\d{2}-\d{2}$'
|
||||
if not re.match(pattern, date_str):
|
||||
return False
|
||||
return True
|
||||
@@ -89,12 +89,6 @@ class AdminRoleModel:
|
||||
"""
|
||||
return await execute_insert(sql, (user_id, role_type, group_id, subject_id))
|
||||
|
||||
@staticmethod
|
||||
async def delete(user_id: int) -> bool:
|
||||
sql = "DELETE FROM admin_roles WHERE user_id = %s"
|
||||
result = await execute_update(sql, (user_id,))
|
||||
return result > 0
|
||||
|
||||
@staticmethod
|
||||
async def update_role(
|
||||
user_id: int,
|
||||
|
||||
@@ -9,8 +9,7 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Optional, Dict, Any, List
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any, List
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update
|
||||
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
# ===========================================
|
||||
|
||||
from typing import Optional, List, Dict, Any
|
||||
from datetime import datetime
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update
|
||||
from utils.logger import get_logger
|
||||
|
||||
@@ -455,36 +454,3 @@ class ConductModel:
|
||||
except Exception as e:
|
||||
logger.error(f"恢复记录失败: {e}")
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
async def batch_create_records(records_data: List[Dict]) -> List[Dict]:
|
||||
"""批量创建操行分记录"""
|
||||
results = []
|
||||
for record in records_data:
|
||||
try:
|
||||
record_id = await ConductModel.create_record(
|
||||
student_id=record.get('student_id'),
|
||||
points_change=record.get('points_change'),
|
||||
reason=record.get('reason'),
|
||||
recorder_id=record.get('recorder_id'),
|
||||
recorder_name=record.get('recorder_name')
|
||||
)
|
||||
results.append({
|
||||
'student_id': record.get('student_id'),
|
||||
'success': True,
|
||||
'record_id': record_id
|
||||
})
|
||||
except Exception as e:
|
||||
results.append({
|
||||
'student_id': record.get('student_id'),
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
})
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
async def get_student_total_points(student_id: int) -> int:
|
||||
"""获取学生当前总分"""
|
||||
sql = "SELECT total_points FROM students WHERE student_id = %s"
|
||||
result = await execute_one(sql, (student_id,))
|
||||
return result['total_points'] if result else 100
|
||||
@@ -10,8 +10,7 @@
|
||||
# ===========================================
|
||||
|
||||
from typing import Optional, List, Dict, Any
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update, execute_many
|
||||
from utils.security import security
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
# ===========================================
|
||||
|
||||
from typing import Optional, Dict, Any, List
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update
|
||||
from utils.database import execute_one, execute_query, execute_insert, execute_update, execute_many
|
||||
|
||||
|
||||
class SubjectModel:
|
||||
@@ -67,8 +67,21 @@ class SubjectModel:
|
||||
params.append(subject_id)
|
||||
sql = f"UPDATE subjects SET {', '.join(updates)} WHERE subject_id = %s"
|
||||
result = await execute_update(sql, tuple(params))
|
||||
return result > 0
|
||||
if result > 0:
|
||||
return True
|
||||
# 内容未变化时 rowcount 为 0,确认科目仍存在即视为成功
|
||||
exists = await execute_one("SELECT 1 FROM subjects WHERE subject_id = %s", (subject_id,))
|
||||
return exists is not None
|
||||
|
||||
@staticmethod
|
||||
async def reorder(subject_ids: List[int]) -> bool:
|
||||
"""按给定顺序批量更新排序序号(按10递增)"""
|
||||
if not subject_ids:
|
||||
return False
|
||||
params_list = [(index * 10, subject_id) for index, subject_id in enumerate(subject_ids)]
|
||||
await execute_many("UPDATE subjects SET sort_order = %s WHERE subject_id = %s", params_list)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
async def has_related_data(subject_id: int) -> bool:
|
||||
"""检查科目是否有关联的作业数据"""
|
||||
|
||||
+11
-11
@@ -1,4 +1,4 @@
|
||||
# ===========================================
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 后端服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
@@ -86,15 +86,22 @@ class UserModel:
|
||||
|
||||
@staticmethod
|
||||
async def update_password(user_id: int, new_password: str) -> bool:
|
||||
"""更新密码"""
|
||||
password_hash = security.bcrypt_password(new_password)
|
||||
"""更新密码(加密失败会抛出异常;rowcount 为 0 时再确认用户是否存在)"""
|
||||
try:
|
||||
password_hash = security.bcrypt_password(new_password)
|
||||
except Exception as e:
|
||||
logger.error(f"密码加密失败: {e}")
|
||||
raise
|
||||
sql = """
|
||||
UPDATE users
|
||||
SET password_hash = %s, need_change_password = 0
|
||||
WHERE user_id = %s
|
||||
"""
|
||||
result = await execute_update(sql, (password_hash, user_id))
|
||||
return result > 0
|
||||
if result > 0:
|
||||
return True
|
||||
exists = await execute_one("SELECT 1 FROM users WHERE user_id = %s", (user_id,))
|
||||
return exists is not None
|
||||
|
||||
@staticmethod
|
||||
async def update_last_login(user_id: int, ip: str) -> None:
|
||||
@@ -117,13 +124,6 @@ class UserModel:
|
||||
"""
|
||||
return await execute_one(sql, (username,))
|
||||
|
||||
@staticmethod
|
||||
async def check_username_exists(username: str) -> bool:
|
||||
"""检查用户名是否存在"""
|
||||
sql = "SELECT 1 FROM users WHERE username = %s"
|
||||
result = await execute_one(sql, (username,))
|
||||
return result is not None
|
||||
|
||||
@staticmethod
|
||||
async def update_status(user_id: int, status: int) -> bool:
|
||||
"""更新用户状态(0=禁用,1=启用)"""
|
||||
|
||||
+38
-10
@@ -10,7 +10,7 @@
|
||||
# ===========================================
|
||||
|
||||
from fastapi import APIRouter, Request, Query, UploadFile, File
|
||||
from typing import Optional, List
|
||||
from typing import Optional
|
||||
import json
|
||||
|
||||
from middleware.permission import (
|
||||
@@ -26,10 +26,11 @@ from schemas.admin import (
|
||||
AddPointsRequest, RevokeRequest, AddAdminRequest,
|
||||
AddStudentRequest, UpdateStudentRequest,
|
||||
AddAttendanceRequest,
|
||||
UpdateAdminRequest, DeleteAdminRequest, ResetPasswordRequest,
|
||||
UnlockUserRequest, PermissionGroupRequest
|
||||
UpdateAdminRequest, ResetPasswordRequest,
|
||||
UnlockUserRequest, PermissionGroupRequest, EmailTestRequest
|
||||
)
|
||||
from utils.response import success_response, error_response
|
||||
from utils.validators import is_valid_email
|
||||
from utils.logger import get_logger
|
||||
from config import settings
|
||||
|
||||
@@ -645,21 +646,44 @@ async def delete_permission_group(request: Request, group_id: int):
|
||||
return error_response(message=result["message"])
|
||||
|
||||
|
||||
@router.put("/update/{user_id}")
|
||||
async def update_admin(request: Request, user_id: int, req: UpdateAdminRequest):
|
||||
"""更新管理员信息"""
|
||||
@router.post("/email/test")
|
||||
async def send_test_email(request: Request, req: EmailTestRequest):
|
||||
"""发送测试邮件(验证 SMTP 配置)"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||
return error_response(message="无管理员管理权限", code=403)
|
||||
if user_id == user["user_id"]:
|
||||
return error_response(message="不能修改当前登录管理员的权限组", code=400)
|
||||
from utils.email_sender import EmailSender
|
||||
if not EmailSender.is_configured():
|
||||
return error_response(
|
||||
message="邮件服务未配置:请检查 SMTP_ENABLED=true 且已填写 SMTP_HOST/SMTP_USER/SMTP_PASSWORD"
|
||||
)
|
||||
if not is_valid_email(req.email):
|
||||
return error_response(message="邮箱格式不正确")
|
||||
ok, message = await EmailSender.send(
|
||||
req.email,
|
||||
f"{settings.APP_NAME} - 邮件测试",
|
||||
"<p>这是一封来自班级操行分管理系统的测试邮件,收到即表示 SMTP 配置可用。</p>"
|
||||
)
|
||||
if ok:
|
||||
return success_response(message=f"测试邮件已发送至 {req.email},请查收")
|
||||
return error_response(message=f"发送失败:{message}")
|
||||
|
||||
|
||||
@router.put("/update/{user_id}")
|
||||
async def update_admin(request: Request, user_id: int, req: UpdateAdminRequest):
|
||||
"""更新管理员信息(本人可改姓名/邮箱,权限组保持不变)"""
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_admins"):
|
||||
return error_response(message="无管理员管理权限", code=403)
|
||||
is_self = (user_id == user["user_id"])
|
||||
|
||||
result = await AdminService.update_admin(
|
||||
user_id=user_id,
|
||||
real_name=req.real_name,
|
||||
group_id=req.group_id,
|
||||
operator_id=user["user_id"],
|
||||
email=req.email
|
||||
email=req.email,
|
||||
keep_group=is_self
|
||||
)
|
||||
if result["success"]:
|
||||
await LogService.write_operation_log(
|
||||
@@ -667,7 +691,11 @@ async def update_admin(request: Request, user_id: int, req: UpdateAdminRequest):
|
||||
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
||||
operation_type="update_admin",
|
||||
target_type="admin", target_id=user_id,
|
||||
details=f"更新管理员姓名: {req.real_name}, 权限组ID: {req.group_id}",
|
||||
details=(
|
||||
f"更新管理员姓名: {req.real_name}(本人账号,权限组不变)"
|
||||
if is_self else
|
||||
f"更新管理员姓名: {req.real_name}, 权限组ID: {req.group_id}"
|
||||
),
|
||||
ip=request.client.host
|
||||
)
|
||||
return success_response(message="管理员更新成功")
|
||||
|
||||
@@ -9,8 +9,7 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from fastapi import APIRouter, Request, HTTPException
|
||||
from typing import Dict, Any
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from schemas.auth import (
|
||||
LoginRequest, ChangePasswordRequest,
|
||||
@@ -19,7 +18,7 @@ from schemas.auth import (
|
||||
)
|
||||
from services.auth_service import AuthService
|
||||
from middleware.permission import get_current_user
|
||||
from utils.response import success_response, error_response, unauthorized_response
|
||||
from utils.response import success_response, error_response
|
||||
from utils.logger import get_logger
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional, List
|
||||
from typing import Optional
|
||||
|
||||
from config import settings
|
||||
from services.admin_service import AdminService
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
# ===========================================
|
||||
|
||||
from fastapi import APIRouter, Request, Query
|
||||
from typing import Optional
|
||||
|
||||
from middleware.permission import get_current_user
|
||||
from services.parent_service import ParentService
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
# ===========================================
|
||||
|
||||
from fastapi import APIRouter, Request, Query
|
||||
from typing import Optional
|
||||
|
||||
from middleware.permission import (
|
||||
get_current_user,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# ===========================================
|
||||
# ===========================================
|
||||
# 班级操行分管理系统 - 后端服务
|
||||
#
|
||||
# 开发者: Canglan
|
||||
@@ -13,7 +13,7 @@ from fastapi import APIRouter, Request
|
||||
from typing import Optional
|
||||
from middleware.permission import get_current_user, PermissionChecker
|
||||
from services.subject_service import SubjectService
|
||||
from schemas.subject import CreateSubjectRequest, UpdateSubjectRequest
|
||||
from schemas.subject import CreateSubjectRequest, UpdateSubjectRequest, ReorderSubjectsRequest
|
||||
from utils.response import success_response, error_response
|
||||
from utils.logger import get_logger
|
||||
|
||||
@@ -46,6 +46,14 @@ async def update_subject(request: Request, subject_id: int, req: UpdateSubjectRe
|
||||
result = await SubjectService.update_subject(subject_id, **req.dict(exclude_none=True))
|
||||
return success_response(message="科目更新成功") if result["success"] else error_response(message=result["message"])
|
||||
|
||||
@router.put("/reorder")
|
||||
async def reorder_subjects(request: Request, req: ReorderSubjectsRequest):
|
||||
user = await get_current_user(request)
|
||||
if not await PermissionChecker.check_permission(user["user_id"], "manage_subjects"):
|
||||
return error_response(message="无权限", code=403)
|
||||
result = await SubjectService.reorder_subjects(req.subject_ids)
|
||||
return success_response(message="排序已更新") if result["success"] else error_response(message=result["message"])
|
||||
|
||||
@router.delete("/delete/{subject_id}")
|
||||
async def delete_subject(request: Request, subject_id: int):
|
||||
user = await get_current_user(request)
|
||||
|
||||
@@ -45,6 +45,7 @@ ALL_VERSIONS = {
|
||||
'3.0': 'v3.0.sql',
|
||||
'4.0': 'v4.0.sql',
|
||||
'4.1': 'v4.1.sql',
|
||||
'4.2': 'v4.2.sql',
|
||||
}
|
||||
# 版本特征标记(按优先级从高到低)
|
||||
VERSION_MARKERS = [
|
||||
|
||||
+23
-51
@@ -11,7 +11,7 @@
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, List
|
||||
from datetime import date, datetime
|
||||
from datetime import date
|
||||
|
||||
|
||||
class AddPointsRequest(BaseModel):
|
||||
@@ -22,31 +22,11 @@ class AddPointsRequest(BaseModel):
|
||||
related_type: Optional[str] = Field(default='manual', pattern=r'^(manual|homework|attendance)$', description="关联类型: manual/homework/attendance")
|
||||
|
||||
|
||||
class AddPointsResponse(BaseModel):
|
||||
"""加减分响应"""
|
||||
success_count: int
|
||||
fail_count: int
|
||||
details: List[dict]
|
||||
|
||||
|
||||
class RevokeRequest(BaseModel):
|
||||
"""撤销请求"""
|
||||
record_id: int = Field(..., description="记录ID")
|
||||
|
||||
|
||||
class ImportStudentsRequest(BaseModel):
|
||||
"""导入学生请求"""
|
||||
students: List[dict] = Field(..., description="学生列表")
|
||||
|
||||
|
||||
class ImportResult(BaseModel):
|
||||
"""导入结果"""
|
||||
total: int
|
||||
success: int
|
||||
failed: int
|
||||
errors: List[str]
|
||||
|
||||
|
||||
class AddAdminRequest(BaseModel):
|
||||
"""添加管理员请求"""
|
||||
username: str = Field(..., min_length=2, max_length=50, pattern=r'^[a-zA-Z0-9_\u4e00-\u9fa5]+$', description="登录账号")
|
||||
@@ -57,12 +37,22 @@ class AddAdminRequest(BaseModel):
|
||||
subject_id: Optional[int] = Field(None, gt=0, description="科目ID(科代表需要)")
|
||||
|
||||
|
||||
class AddAdminResponse(BaseModel):
|
||||
"""添加管理员响应"""
|
||||
success: bool
|
||||
username: str
|
||||
password: Optional[str] = None
|
||||
message: str
|
||||
class UpdateAdminRequest(BaseModel):
|
||||
"""更新管理员请求"""
|
||||
real_name: str = Field(..., min_length=1, max_length=50, description="真实姓名")
|
||||
group_id: int = Field(..., gt=0, description="权限组ID")
|
||||
email: Optional[str] = Field(None, max_length=100, description="绑定邮箱(留空解除绑定)")
|
||||
|
||||
|
||||
class PermissionGroupRequest(BaseModel):
|
||||
"""权限组创建/编辑请求"""
|
||||
group_name: str = Field(..., min_length=1, max_length=50, description="权限组名称")
|
||||
description: Optional[str] = Field(None, max_length=255, description="说明")
|
||||
permissions: List[str] = Field(default_factory=list, description="权限项列表")
|
||||
can_add_points: bool = Field(True, description="是否允许加分")
|
||||
max_add_points: Optional[int] = Field(None, ge=1, le=100, description="单次加分上限,不填为无限制")
|
||||
can_subtract_points: bool = Field(True, description="是否允许扣分")
|
||||
max_subtract_points: Optional[int] = Field(None, ge=1, le=100, description="单次扣分上限,不填为无限制")
|
||||
|
||||
|
||||
class AddStudentRequest(BaseModel):
|
||||
@@ -84,29 +74,6 @@ class AddAttendanceRequest(BaseModel):
|
||||
custom_deduction: Optional[int] = Field(default=None, gt=0, le=20, description="自定义扣分值")
|
||||
|
||||
|
||||
class UpdateAdminRequest(BaseModel):
|
||||
"""更新管理员请求"""
|
||||
real_name: str = Field(..., min_length=1, max_length=50, description="真实姓名")
|
||||
group_id: int = Field(..., gt=0, description="权限组ID")
|
||||
email: Optional[str] = Field(None, max_length=100, description="绑定邮箱(留空解除绑定)")
|
||||
|
||||
|
||||
class PermissionGroupRequest(BaseModel):
|
||||
"""权限组创建/编辑请求"""
|
||||
group_name: str = Field(..., min_length=1, max_length=50, description="权限组名称")
|
||||
description: Optional[str] = Field(None, max_length=255, description="说明")
|
||||
permissions: List[str] = Field(default_factory=list, description="权限项列表")
|
||||
can_add_points: bool = Field(True, description="是否允许加分")
|
||||
max_add_points: Optional[int] = Field(None, ge=1, le=100, description="单次加分上限,不填为无限制")
|
||||
can_subtract_points: bool = Field(True, description="是否允许扣分")
|
||||
max_subtract_points: Optional[int] = Field(None, ge=1, le=100, description="单次扣分上限,不填为无限制")
|
||||
|
||||
|
||||
class DeleteAdminRequest(BaseModel):
|
||||
"""删除管理员请求"""
|
||||
user_id: int = Field(..., description="用户ID")
|
||||
|
||||
|
||||
class ResetPasswordRequest(BaseModel):
|
||||
"""重置密码请求"""
|
||||
new_password: str = Field(..., min_length=6, max_length=50, description="新密码")
|
||||
@@ -121,4 +88,9 @@ class UpdateStudentRequest(BaseModel):
|
||||
|
||||
class UnlockUserRequest(BaseModel):
|
||||
"""解除用户登录锁定请求"""
|
||||
username: str = Field(..., min_length=1, max_length=50, description="用户名")
|
||||
username: str = Field(..., min_length=1, max_length=50, description="用户名")
|
||||
|
||||
|
||||
class EmailTestRequest(BaseModel):
|
||||
"""邮件测试请求"""
|
||||
email: str = Field(..., min_length=3, max_length=100, description="接收测试邮件的邮箱")
|
||||
@@ -10,7 +10,6 @@
|
||||
# ===========================================
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
@@ -19,18 +18,6 @@ class LoginRequest(BaseModel):
|
||||
password: str = Field(..., min_length=1, max_length=50, description="密码")
|
||||
|
||||
|
||||
class LoginResponse(BaseModel):
|
||||
"""登录响应"""
|
||||
success: bool
|
||||
token: str
|
||||
user_id: int
|
||||
username: str
|
||||
real_name: str
|
||||
user_type: str
|
||||
need_change_password: bool
|
||||
redirect: str
|
||||
|
||||
|
||||
class ChangePasswordRequest(BaseModel):
|
||||
"""修改密码请求"""
|
||||
old_password: str = Field(default="", max_length=50, description="原密码")
|
||||
@@ -38,24 +25,6 @@ class ChangePasswordRequest(BaseModel):
|
||||
force: bool = Field(default=False, description="是否强制修改(首次登录)")
|
||||
|
||||
|
||||
class ChangePasswordResponse(BaseModel):
|
||||
"""修改密码响应"""
|
||||
success: bool
|
||||
message: str
|
||||
|
||||
|
||||
class UserInfo(BaseModel):
|
||||
"""用户信息"""
|
||||
user_id: int
|
||||
username: str
|
||||
real_name: str
|
||||
user_type: str
|
||||
student_id: Optional[int] = None
|
||||
role: Optional[str] = None
|
||||
email: Optional[str] = None
|
||||
need_change_password: bool
|
||||
|
||||
|
||||
class ForgotPasswordRequest(BaseModel):
|
||||
"""忘记密码请求"""
|
||||
username: str = Field(..., min_length=1, max_length=50, description="用户名")
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
# ===========================================
|
||||
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
class DeductionConfigResponse(BaseModel):
|
||||
"""扣分规则配置响应"""
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional, List
|
||||
from datetime import date, datetime
|
||||
|
||||
|
||||
@@ -25,14 +25,14 @@ class SubjectInfo(BaseModel):
|
||||
class CreateSubjectRequest(BaseModel):
|
||||
"""创建科目请求"""
|
||||
subject_name: str = Field(..., min_length=1, max_length=50, description="科目名称")
|
||||
subject_code: Optional[str] = Field(None, max_length=20, description="科目代码")
|
||||
subject_code: Optional[str] = Field(None, max_length=50, description="科目代码")
|
||||
sort_order: int = Field(0, description="排序序号")
|
||||
|
||||
|
||||
class UpdateSubjectRequest(BaseModel):
|
||||
"""更新科目请求"""
|
||||
subject_name: Optional[str] = Field(None, max_length=50, description="科目名称")
|
||||
subject_code: Optional[str] = Field(None, max_length=20, description="科目代码")
|
||||
subject_name: Optional[str] = Field(None, min_length=1, max_length=50, description="科目名称")
|
||||
subject_code: Optional[str] = Field(None, max_length=50, description="科目代码(传空字符串表示清空)")
|
||||
is_active: Optional[bool] = Field(None, description="是否启用")
|
||||
sort_order: Optional[int] = Field(None, description="排序序号")
|
||||
|
||||
@@ -40,4 +40,9 @@ class UpdateSubjectRequest(BaseModel):
|
||||
class SubjectListResponse(BaseModel):
|
||||
"""科目列表响应"""
|
||||
subjects: List[SubjectInfo]
|
||||
total: int
|
||||
total: int
|
||||
|
||||
|
||||
class ReorderSubjectsRequest(BaseModel):
|
||||
"""科目排序请求"""
|
||||
subject_ids: List[int] = Field(..., min_length=1, max_length=100, description="按新顺序排列的科目ID列表")
|
||||
@@ -396,13 +396,21 @@ class AdminService:
|
||||
real_name: str,
|
||||
group_id: int,
|
||||
operator_id: int,
|
||||
email: Optional[str] = None
|
||||
email: Optional[str] = None,
|
||||
keep_group: bool = False
|
||||
) -> Dict[str, Any]:
|
||||
"""更新管理员姓名、权限组与绑定邮箱"""
|
||||
"""更新管理员姓名、权限组与绑定邮箱(keep_group=True 时仅改姓名/邮箱,权限组保持不变)"""
|
||||
target_user = await UserModel.get_by_user_id(user_id)
|
||||
if not target_user or target_user.get("user_type") != "admin":
|
||||
return {"success": False, "message": "管理员不存在"}
|
||||
|
||||
if keep_group:
|
||||
# 本人账号:保留原权限组,避免误操作把自己锁死
|
||||
current_role = await AdminRoleModel.get_by_user_id(user_id)
|
||||
if not current_role or not current_role.get("group_id"):
|
||||
return {"success": False, "message": "无法确定当前账号的权限组,请先完成系统升级"}
|
||||
group_id = current_role["group_id"]
|
||||
|
||||
try:
|
||||
group = await PermissionGroupModel.get_by_id(group_id)
|
||||
except Exception as e:
|
||||
@@ -419,7 +427,8 @@ class AdminService:
|
||||
return {"success": False, "message": "邮箱格式不正确"}
|
||||
|
||||
try:
|
||||
await AdminRoleModel.update_role(user_id, group["group_name"], group_id=group_id)
|
||||
if not keep_group:
|
||||
await AdminRoleModel.update_role(user_id, group["group_name"], group_id=group_id)
|
||||
if real_name:
|
||||
await UserModel.update_real_name(user_id, real_name)
|
||||
if email is not None:
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
# ===========================================
|
||||
|
||||
from typing import Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
|
||||
from models.attendance import AttendanceModel
|
||||
from models.student import StudentModel
|
||||
|
||||
@@ -10,14 +10,12 @@
|
||||
# ===========================================
|
||||
|
||||
from typing import Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
from html import escape as html_escape
|
||||
import secrets
|
||||
|
||||
from config import settings
|
||||
from models.user import UserModel
|
||||
from models.student import StudentModel
|
||||
from models.admin_role import AdminRoleModel
|
||||
from middleware.permission import PermissionChecker
|
||||
from services.log_service import LogService
|
||||
from utils.security import security
|
||||
@@ -25,7 +23,6 @@ from utils.validators import is_valid_email
|
||||
from utils.email_sender import EmailSender
|
||||
from utils.jwt_handler import jwt_handler
|
||||
from utils.redis_client import RedisClient
|
||||
from utils.database import execute_update
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -14,7 +14,6 @@ from datetime import datetime
|
||||
|
||||
from models.student import StudentModel
|
||||
from models.conduct import ConductModel, _append_semester_filter
|
||||
from models.user import UserModel
|
||||
from models.semester import SemesterModel
|
||||
from middleware.permission import PermissionChecker
|
||||
from config import settings
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
# ===========================================
|
||||
|
||||
from models.log import LoginLogModel, OperationLogModel
|
||||
from middleware.permission import PermissionChecker
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
# ===========================================
|
||||
|
||||
import math
|
||||
from typing import Dict, Any, Optional, List
|
||||
from typing import Dict, Any
|
||||
|
||||
from models.user import UserModel
|
||||
from models.student import StudentModel
|
||||
|
||||
@@ -10,14 +10,12 @@
|
||||
# ===========================================
|
||||
|
||||
import datetime
|
||||
from typing import Dict, Any, List, Optional
|
||||
from typing import Dict, Any
|
||||
|
||||
from models.semester import SemesterModel, SemesterArchiveModel
|
||||
from models.student import StudentModel
|
||||
from middleware.permission import PermissionChecker
|
||||
from config import settings
|
||||
from utils.logger import get_logger
|
||||
from utils.database import execute_query
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
@@ -9,13 +9,11 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Dict, Any, List, Optional
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, Any, Optional
|
||||
|
||||
from models.student import StudentModel
|
||||
from models.conduct import ConductModel
|
||||
from models.attendance import AttendanceModel
|
||||
from middleware.permission import PermissionChecker
|
||||
from utils.database import execute_query
|
||||
from utils.logger import get_logger
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Dict, Any, List, Optional
|
||||
from typing import Dict, Any, Optional, List
|
||||
|
||||
from models.subject import SubjectModel
|
||||
from utils.logger import get_logger
|
||||
@@ -36,27 +36,47 @@ class SubjectService:
|
||||
subject_code: Optional[str],
|
||||
sort_order: int = 0
|
||||
) -> Dict[str, Any]:
|
||||
"""创建科目"""
|
||||
"""创建科目(科目代码留空存 NULL)"""
|
||||
name = (subject_name or "").strip()
|
||||
if not name:
|
||||
return {"success": False, "message": "科目名称不能为空"}
|
||||
code = (subject_code or "").strip() or None
|
||||
|
||||
# 检查是否已存在
|
||||
existing = await SubjectModel.get_by_name(subject_name)
|
||||
existing = await SubjectModel.get_by_name(name)
|
||||
if existing:
|
||||
return {"success": False, "message": "科目名称已存在"}
|
||||
|
||||
subject_id = await SubjectModel.create(
|
||||
subject_name=subject_name,
|
||||
subject_code=subject_code,
|
||||
subject_name=name,
|
||||
subject_code=code,
|
||||
sort_order=sort_order
|
||||
)
|
||||
|
||||
if subject_id:
|
||||
logger.info(f"创建科目: {subject_name}")
|
||||
logger.info(f"创建科目: {name}")
|
||||
return {"success": True, "subject_id": subject_id}
|
||||
else:
|
||||
return {"success": False, "message": "创建科目失败"}
|
||||
|
||||
@staticmethod
|
||||
async def update_subject(subject_id: int, **kwargs) -> Dict[str, Any]:
|
||||
"""更新科目"""
|
||||
"""更新科目(科目代码传空字符串表示清空)"""
|
||||
subject = await SubjectModel.get_by_id(subject_id)
|
||||
if not subject:
|
||||
return {"success": False, "message": "科目不存在"}
|
||||
|
||||
if "subject_name" in kwargs:
|
||||
name = (kwargs.get("subject_name") or "").strip()
|
||||
if not name:
|
||||
return {"success": False, "message": "科目名称不能为空"}
|
||||
existing = await SubjectModel.get_by_name(name)
|
||||
if existing and existing["subject_id"] != subject_id:
|
||||
return {"success": False, "message": "科目名称已存在"}
|
||||
kwargs["subject_name"] = name
|
||||
if "subject_code" in kwargs:
|
||||
kwargs["subject_code"] = (kwargs.get("subject_code") or "").strip() or None
|
||||
|
||||
result = await SubjectModel.update(subject_id, **kwargs)
|
||||
|
||||
if result:
|
||||
@@ -65,6 +85,15 @@ class SubjectService:
|
||||
else:
|
||||
return {"success": False, "message": "更新科目失败"}
|
||||
|
||||
@staticmethod
|
||||
async def reorder_subjects(subject_ids: List[int]) -> Dict[str, Any]:
|
||||
"""按新顺序批量更新科目排序"""
|
||||
if not subject_ids:
|
||||
return {"success": False, "message": "排序列表不能为空"}
|
||||
await SubjectModel.reorder(subject_ids)
|
||||
logger.info(f"科目排序已更新: {subject_ids}")
|
||||
return {"success": True}
|
||||
|
||||
@staticmethod
|
||||
async def delete_subject(subject_id: int) -> Dict[str, Any]:
|
||||
"""删除科目(真正删除记录)"""
|
||||
|
||||
@@ -83,20 +83,6 @@ async def get_connection():
|
||||
await conn.commit()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def get_transaction():
|
||||
"""获取事务连接"""
|
||||
pool = get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
async with conn.cursor() as cursor:
|
||||
try:
|
||||
yield cursor
|
||||
await conn.commit()
|
||||
except Exception:
|
||||
await conn.rollback()
|
||||
raise
|
||||
|
||||
|
||||
async def execute_query(sql: str, params: tuple = None) -> List[Dict[str, Any]]:
|
||||
"""执行查询SQL"""
|
||||
async with get_connection() as cursor:
|
||||
@@ -132,19 +118,3 @@ async def execute_many(sql: str, params_list: list) -> int:
|
||||
async with get_connection() as cursor:
|
||||
await cursor.executemany(sql, params_list)
|
||||
return cursor.rowcount
|
||||
|
||||
|
||||
async def call_procedure(proc_name: str, args: tuple = None) -> List[Dict[str, Any]]:
|
||||
"""调用存储过程"""
|
||||
async with get_connection() as cursor:
|
||||
if args:
|
||||
await cursor.callproc(proc_name, args)
|
||||
else:
|
||||
await cursor.callproc(proc_name)
|
||||
|
||||
# 获取结果
|
||||
result = []
|
||||
for result_set in cursor.fetchall():
|
||||
if result_set:
|
||||
result.extend(result_set)
|
||||
return result
|
||||
@@ -9,7 +9,7 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from jose import jwt, JWTError
|
||||
from jose import jwt
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
# 版权所有 © Sea Network Technology Studio
|
||||
# ===========================================
|
||||
|
||||
from typing import Any, Optional, Dict, List
|
||||
from typing import Any
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
@@ -54,53 +54,3 @@ def error_response(
|
||||
"data": data
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def unauthorized_response(message: str = "未授权,请重新登录") -> JSONResponse:
|
||||
"""未授权响应"""
|
||||
return JSONResponse(
|
||||
status_code=ResponseCode.UNAUTHORIZED,
|
||||
content={
|
||||
"success": False,
|
||||
"code": ResponseCode.UNAUTHORIZED,
|
||||
"message": message,
|
||||
"data": None
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def forbidden_response(message: str = "权限不足") -> JSONResponse:
|
||||
"""禁止访问响应"""
|
||||
return JSONResponse(
|
||||
status_code=ResponseCode.FORBIDDEN,
|
||||
content={
|
||||
"success": False,
|
||||
"code": ResponseCode.FORBIDDEN,
|
||||
"message": message,
|
||||
"data": None
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def not_found_response(message: str = "资源不存在") -> JSONResponse:
|
||||
"""资源不存在响应"""
|
||||
return JSONResponse(
|
||||
status_code=ResponseCode.NOT_FOUND,
|
||||
content={
|
||||
"success": False,
|
||||
"code": ResponseCode.NOT_FOUND,
|
||||
"message": message,
|
||||
"data": None
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def paginated_response(items: List[Any], total: int, page: int, page_size: int) -> Dict:
|
||||
"""分页响应数据"""
|
||||
return {
|
||||
"items": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total_pages": (total + page_size - 1) // page_size
|
||||
}
|
||||
@@ -15,6 +15,16 @@ import re
|
||||
from passlib.hash import bcrypt as bcrypt_hash
|
||||
from config import settings
|
||||
|
||||
try:
|
||||
import bcrypt as _bcrypt_lib
|
||||
except Exception:
|
||||
_bcrypt_lib = None
|
||||
|
||||
|
||||
def _bcrypt_bytes(password: str) -> bytes:
|
||||
"""bcrypt 仅使用前 72 字节(与历史行为一致)"""
|
||||
return password.encode('utf-8')[:72]
|
||||
|
||||
|
||||
class SecurityUtils:
|
||||
"""安全工具类"""
|
||||
@@ -35,7 +45,9 @@ class SecurityUtils:
|
||||
|
||||
@staticmethod
|
||||
def bcrypt_password(password: str) -> str:
|
||||
"""使用bcrypt加密密码"""
|
||||
"""使用bcrypt加密密码(优先使用 bcrypt 库,回退 passlib,避免版本兼容问题)"""
|
||||
if _bcrypt_lib is not None:
|
||||
return _bcrypt_lib.hashpw(_bcrypt_bytes(password), _bcrypt_lib.gensalt(rounds=12)).decode('utf-8')
|
||||
return bcrypt_hash.using(rounds=12).hash(password)
|
||||
|
||||
@staticmethod
|
||||
@@ -44,11 +56,19 @@ class SecurityUtils:
|
||||
验证密码(支持bcrypt和旧哈希)
|
||||
返回: (是否验证成功, 是否需要升级哈希)
|
||||
"""
|
||||
try:
|
||||
if bcrypt_hash.verify(plain_password, hashed_password):
|
||||
return True, False
|
||||
except Exception:
|
||||
pass
|
||||
if hashed_password and hashed_password.startswith(('$2a$', '$2b$', '$2y$')):
|
||||
if _bcrypt_lib is not None:
|
||||
try:
|
||||
if _bcrypt_lib.checkpw(_bcrypt_bytes(plain_password), hashed_password.encode('utf-8')):
|
||||
return True, False
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
if bcrypt_hash.verify(plain_password, hashed_password):
|
||||
return True, False
|
||||
except Exception:
|
||||
pass
|
||||
# 回退到旧的sha1_md5验证
|
||||
if SecurityUtils.sha1_md5_password(plain_password) == hashed_password:
|
||||
return True, True
|
||||
|
||||
Reference in new issue
Block a user