refactor: 统一日志管理 + 数据库索引优化
- db/schema.py: 添加 4 个复合索引优化查询性能 - idx_user_schedules_user_enabled - idx_schedule_execution_logs_schedule_id/user_id/status - db/users.py: print → logger,密码升级日志改为记录 user_id - crypto_utils.py: print → logger - password_utils.py: print → logger 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -12,6 +12,8 @@ from pathlib import Path
|
||||
from cryptography.fernet import Fernet
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
||||
from app_logger import get_logger
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# 安全修复: 支持通过环境变量配置密钥文件路径
|
||||
@@ -65,7 +67,7 @@ def get_encryption_key():
|
||||
os.makedirs(key_path.parent, exist_ok=True)
|
||||
with open(key_path, 'wb') as f:
|
||||
f.write(key)
|
||||
print(f"[安全] 已生成新的加密密钥并保存到 {ENCRYPTION_KEY_FILE}")
|
||||
logger.info(f"已生成新的加密密钥并保存到 {ENCRYPTION_KEY_FILE}")
|
||||
return key
|
||||
|
||||
|
||||
@@ -119,7 +121,7 @@ def decrypt_password(encrypted_password: str) -> str:
|
||||
return decrypted.decode('utf-8')
|
||||
except Exception as e:
|
||||
# 解密失败,可能是旧的明文密码
|
||||
print(f"[警告] 密码解密失败,可能是未加密的旧数据: {e}")
|
||||
logger.warning(f"密码解密失败,可能是未加密的旧数据: {e}")
|
||||
return encrypted_password
|
||||
|
||||
|
||||
|
||||
@@ -260,6 +260,11 @@ def ensure_schema(conn) -> None:
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_user_schedules_user_id ON user_schedules(user_id)")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_user_schedules_enabled ON user_schedules(enabled)")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_user_schedules_next_run ON user_schedules(next_run_at)")
|
||||
# 复合索引优化
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_user_schedules_user_enabled ON user_schedules(user_id, enabled)")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_schedule_execution_logs_schedule_id ON schedule_execution_logs(schedule_id)")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_schedule_execution_logs_user_id ON schedule_execution_logs(user_id)")
|
||||
cursor.execute("CREATE INDEX IF NOT EXISTS idx_schedule_execution_logs_status ON schedule_execution_logs(status)")
|
||||
|
||||
# 初始化VIP配置(幂等)
|
||||
try:
|
||||
|
||||
10
db/users.py
10
db/users.py
@@ -6,6 +6,7 @@ import sqlite3
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytz
|
||||
from app_logger import get_logger
|
||||
|
||||
import db_pool
|
||||
from db.utils import get_cst_now_str
|
||||
@@ -15,6 +16,7 @@ from password_utils import (
|
||||
verify_password_bcrypt,
|
||||
verify_password_sha256,
|
||||
)
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def get_vip_config():
|
||||
@@ -79,7 +81,7 @@ def extend_user_vip(user_id, days):
|
||||
expire_time = now
|
||||
new_expire = (expire_time + timedelta(days=days)).strftime("%Y-%m-%d %H:%M:%S")
|
||||
except (ValueError, AttributeError) as e:
|
||||
print(f"解析VIP过期时间失败: {e}, 使用当前时间")
|
||||
logger.warning(f"解析VIP过期时间失败: {e}, 使用当前时间")
|
||||
new_expire = (datetime.now(cst_tz) + timedelta(days=days)).strftime("%Y-%m-%d %H:%M:%S")
|
||||
else:
|
||||
new_expire = (datetime.now(cst_tz) + timedelta(days=days)).strftime("%Y-%m-%d %H:%M:%S")
|
||||
@@ -115,7 +117,7 @@ def is_user_vip(user_id):
|
||||
now = datetime.now(cst_tz)
|
||||
return now < expire_time
|
||||
except (ValueError, AttributeError) as e:
|
||||
print(f"检查VIP状态失败 (user_id={user_id}): {e}")
|
||||
logger.warning(f"检查VIP状态失败 (user_id={user_id}): {e}")
|
||||
return False
|
||||
|
||||
|
||||
@@ -140,7 +142,7 @@ def get_user_vip_info(user_id):
|
||||
|
||||
return {"username": user.get("username", ""), "is_vip": is_vip, "expire_time": vip_expire_time, "days_left": max(0, days_left)}
|
||||
except Exception as e:
|
||||
print(f"VIP信息获取错误: {e}")
|
||||
logger.warning(f"VIP信息获取错误: {e}")
|
||||
return {"is_vip": False, "expire_time": None, "days_left": 0, "username": user.get("username", "")}
|
||||
|
||||
|
||||
@@ -197,7 +199,7 @@ def verify_user(username, password):
|
||||
new_hash = hash_password_bcrypt(password)
|
||||
cursor.execute("UPDATE users SET password_hash = ? WHERE id = ?", (new_hash, user_dict["id"]))
|
||||
conn.commit()
|
||||
print(f"用户 {username} 密码已自动升级到bcrypt")
|
||||
logger.info(f"用户密码已自动升级到bcrypt (user_id={user_dict['id']})")
|
||||
return user_dict
|
||||
return None
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
"""
|
||||
import bcrypt
|
||||
import hashlib
|
||||
from app_logger import get_logger
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def hash_password_bcrypt(password):
|
||||
@@ -35,7 +37,7 @@ def verify_password_bcrypt(password, password_hash):
|
||||
return bcrypt.checkpw(password.encode('utf-8'),
|
||||
password_hash.encode('utf-8'))
|
||||
except Exception as e:
|
||||
print(f"bcrypt验证异常: {e}")
|
||||
logger.error(f"bcrypt验证异常: {e}")
|
||||
return False
|
||||
|
||||
|
||||
@@ -70,5 +72,5 @@ def verify_password_sha256(password, password_hash):
|
||||
computed_hash = hashlib.sha256(password.encode()).hexdigest()
|
||||
return computed_hash == password_hash
|
||||
except Exception as e:
|
||||
print(f"SHA256验证异常: {e}")
|
||||
logger.error(f"SHA256验证异常: {e}")
|
||||
return False
|
||||
|
||||
Reference in New Issue
Block a user