Files
ClassManager/backend/utils/security.py
T
canglan 1068bc6def 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
2026-09-20 20:35:13 +08:00

193 lines
6.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ===========================================
# 班级操行分管理系统 - 后端服务
#
# 开发者: Canglan
# 联系方式: admin@sea-studio.top
# 版权归属: Sea Network Technology Studio
# 许可证: MIT License
#
# 版权所有 © Sea Network Technology Studio
# ===========================================
import hashlib
import secrets
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:
"""安全工具类"""
@staticmethod
def sha1_md5_password(password: str) -> str:
"""
双重加密:sha1 + md5
流程:原始密码 -> sha1 -> 加盐 -> md5
"""
# 第一层:SHA1
sha1_hash = hashlib.sha1(password.encode('utf-8')).hexdigest()
# 加盐
salted = sha1_hash + settings.PASSWORD_SALT
# 第二层:MD5
md5_hash = hashlib.md5(salted.encode('utf-8')).hexdigest()
return md5_hash
@staticmethod
def bcrypt_password(password: str) -> str:
"""使用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
def verify_password_v2(plain_password: str, hashed_password: str) -> tuple:
"""
验证密码(支持bcrypt和旧哈希)
返回: (是否验证成功, 是否需要升级哈希)
"""
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
return False, False
@staticmethod
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""验证密码"""
return SecurityUtils.sha1_md5_password(plain_password) == hashed_password
@staticmethod
def generate_random_password(length: int = 8) -> str:
"""生成随机密码"""
alphabet = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'
return ''.join(secrets.choice(alphabet) for _ in range(length))
@staticmethod
def validate_password_strength(password: str) -> tuple:
"""
验证密码强度
要求:大小写字母、数字、特殊符号 至少包含其中3种
返回: (是否有效, 错误信息)
"""
if len(password) < 6:
return False, "密码长度至少6位"
if len(password) > 20:
return False, "密码长度不能超过20位"
# 检查四种字符类型
has_upper = any(c.isupper() for c in password) # 大写字母
has_lower = any(c.islower() for c in password) # 小写字母
has_digit = any(c.isdigit() for c in password) # 数字
has_special = any(not c.isalnum() for c in password) # 特殊符号
# 统计满足的字符类型数量
char_types = sum([has_upper, has_lower, has_digit, has_special])
if char_types < 3:
return False, "密码必须包含大写字母、小写字母、数字、特殊符号中的至少3种"
return True, ""
@staticmethod
def sanitize_string(value: str, max_length: int = 255) -> 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) > max_length:
value = value[:max_length]
# 转义HTML特殊字符(防止XSS)
html_chars = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#x27;',
'/': '&#x2F;'
}
for char, escape in html_chars.items():
value = value.replace(char, escape)
return value
@staticmethod
def validate_student_no(student_no: str) -> bool:
"""验证学号格式(数字+字母,长度4-20)"""
if not student_no:
return False
if len(student_no) < 4 or len(student_no) > 20:
return False
# 字母数字组合
return student_no.isalnum()
@staticmethod
def validate_phone(phone: str) -> bool:
"""验证手机号格式(中国手机号)"""
if not phone:
return False
pattern = r'^1[3-9]\d{9}$'
return bool(re.match(pattern, phone))
@staticmethod
def validate_points_change(points: int, max_abs: int = 100) -> tuple:
"""
验证分值变动
返回: (是否有效, 错误信息)
"""
if points == 0:
return False, "分值不能为0"
if abs(points) > max_abs:
return False, f"单次分值变动不能超过{max_abs}分"
return True, ""
# 单例导出
security = SecurityUtils()