213 lines
7.3 KiB
Python
213 lines
7.3 KiB
Python
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
账号管理器 - 分离网站账号和教务系统账号
|
|
|
|
网站账号:存储在数据库 (User模型)
|
|
教务系统账号:存储在 accounts.json
|
|
|
|
映射关系:通过 user_id 或 username 关联
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import threading
|
|
from pathlib import Path
|
|
from typing import Optional, Dict, List, Tuple
|
|
|
|
BASE_DIR = Path(__file__).parent.parent
|
|
ACCOUNTS_FILE = BASE_DIR / "accounts.json"
|
|
|
|
|
|
def _file_lock_wrapper(method):
|
|
"""串行化 accounts.json 读改写"""
|
|
import functools
|
|
@functools.wraps(method)
|
|
def wrapper(*args, **kwargs):
|
|
with AccountManager._file_lock:
|
|
return method(*args, **kwargs)
|
|
return wrapper
|
|
|
|
|
|
class AccountManager:
|
|
"""账号管理器"""
|
|
|
|
# 串行化 accounts.json 读改写(注册并发/后台刷新读并发会互相覆盖)
|
|
_file_lock = threading.Lock()
|
|
|
|
@staticmethod
|
|
def _load_accounts() -> List[Dict]:
|
|
"""加载所有账号配置;解析失败时备份损坏文件,防止下次保存静默清空全部账号"""
|
|
if not ACCOUNTS_FILE.exists():
|
|
return []
|
|
try:
|
|
data = json.loads(ACCOUNTS_FILE.read_text(encoding="utf-8"))
|
|
return data if isinstance(data, list) else []
|
|
except Exception as e:
|
|
try:
|
|
backup = ACCOUNTS_FILE.with_suffix('.json.corrupt')
|
|
if ACCOUNTS_FILE.exists():
|
|
backup.write_text(ACCOUNTS_FILE.read_text(encoding="utf-8"), encoding="utf-8")
|
|
print(f"[account_manager] accounts.json 解析失败({e}),已备份到 {backup.name};返回空列表")
|
|
except Exception:
|
|
pass
|
|
return []
|
|
|
|
@staticmethod
|
|
def _save_accounts(accounts: List[Dict]):
|
|
"""保存账号配置(原子写,防读到半截)"""
|
|
import os, tempfile
|
|
fd, tmp = tempfile.mkstemp(dir=str(ACCOUNTS_FILE.parent), suffix=".tmp")
|
|
try:
|
|
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
json.dump(accounts, f, ensure_ascii=False, indent=2)
|
|
os.replace(tmp, ACCOUNTS_FILE)
|
|
except Exception:
|
|
try:
|
|
os.unlink(tmp)
|
|
except OSError:
|
|
pass
|
|
raise
|
|
|
|
@classmethod
|
|
def get_jwxt_account(cls, user_id: int = None, username: str = None) -> Optional[Dict]:
|
|
"""
|
|
获取教务系统账号
|
|
|
|
Args:
|
|
user_id: 网站用户ID
|
|
username: 网站用户名(学号)
|
|
|
|
Returns:
|
|
{"username": "...", "password": "..."} 或 None
|
|
"""
|
|
accounts = cls._load_accounts()
|
|
|
|
for acc in accounts:
|
|
# 优先匹配 user_id
|
|
if user_id and acc.get("user_id") == user_id:
|
|
return {
|
|
"username": acc.get("jwxt_username", acc.get("username")),
|
|
"password": acc.get("jwxt_password", acc.get("password"))
|
|
}
|
|
# 其次匹配 username
|
|
if username and acc.get("username") == username:
|
|
return {
|
|
"username": acc.get("jwxt_username", acc.get("username")),
|
|
"password": acc.get("jwxt_password", acc.get("password"))
|
|
}
|
|
# 兼容旧格式
|
|
if username and acc.get("jwxt_username") == username:
|
|
return {
|
|
"username": acc.get("jwxt_username"),
|
|
"password": acc.get("jwxt_password")
|
|
}
|
|
|
|
return None
|
|
|
|
@classmethod
|
|
@_file_lock_wrapper
|
|
def set_jwxt_account(cls, user_id: int, username: str,
|
|
jwxt_username: str, jwxt_password: str,
|
|
jwxt_name: str = "", school_id: str = None) -> bool:
|
|
"""
|
|
设置/更新教务系统账号
|
|
|
|
Args:
|
|
user_id: 网站用户ID
|
|
username: 网站用户名
|
|
jwxt_username: 教务系统学号
|
|
jwxt_password: 教务系统密码
|
|
jwxt_name: 姓名
|
|
|
|
Returns:
|
|
bool: 是否成功
|
|
"""
|
|
try:
|
|
accounts = cls._load_accounts()
|
|
|
|
# 查找是否已存在
|
|
found = False
|
|
for acc in accounts:
|
|
if acc.get("user_id") == user_id or acc.get("username") == username:
|
|
acc["user_id"] = user_id
|
|
acc["username"] = username
|
|
acc["jwxt_username"] = jwxt_username
|
|
acc["jwxt_password"] = jwxt_password
|
|
if school_id:
|
|
acc["school_id"] = school_id
|
|
if jwxt_name:
|
|
acc["jwxt_name"] = jwxt_name
|
|
found = True
|
|
break
|
|
|
|
# 不存在则添加
|
|
if not found:
|
|
accounts.append({
|
|
"user_id": user_id,
|
|
"username": username,
|
|
"jwxt_username": jwxt_username,
|
|
"jwxt_password": jwxt_password,
|
|
"jwxt_name": jwxt_name,
|
|
"school_id": school_id or 'sdmu'
|
|
})
|
|
|
|
cls._save_accounts(accounts)
|
|
return True
|
|
except Exception as e:
|
|
print(f"[ERROR] 保存账号失败: {e}")
|
|
return False
|
|
|
|
@classmethod
|
|
@_file_lock_wrapper
|
|
def delete_jwxt_account(cls, user_id: int = None, username: str = None) -> bool:
|
|
"""删除教务系统账号配置"""
|
|
try:
|
|
accounts = cls._load_accounts()
|
|
|
|
# 过滤掉要删除的账号
|
|
new_accounts = [
|
|
acc for acc in accounts
|
|
if not (
|
|
(user_id and acc.get("user_id") == user_id) or
|
|
(username and acc.get("username") == username)
|
|
)
|
|
]
|
|
|
|
cls._save_accounts(new_accounts)
|
|
return len(new_accounts) < len(accounts)
|
|
except Exception as e:
|
|
print(f"[ERROR] 删除账号失败: {e}")
|
|
return False
|
|
|
|
@classmethod
|
|
def get_all_accounts(cls) -> List[Dict]:
|
|
"""获取所有账号配置(管理员用)"""
|
|
return cls._load_accounts()
|
|
|
|
@classmethod
|
|
def get_jwxt_username(cls, user_id: int = None, username: str = None) -> Optional[str]:
|
|
"""获取教务系统学号"""
|
|
account = cls.get_jwxt_account(user_id, username)
|
|
return account["username"] if account else None
|
|
|
|
@classmethod
|
|
def has_jwxt_account(cls, user_id: int = None, username: str = None) -> bool:
|
|
"""检查是否配置了教务系统账号"""
|
|
return cls.get_jwxt_account(user_id, username) is not None
|
|
|
|
|
|
# 便捷函数
|
|
def get_jwxt_account(user_id: int = None, username: str = None) -> Optional[Dict]:
|
|
"""获取教务系统账号"""
|
|
return AccountManager.get_jwxt_account(user_id, username)
|
|
|
|
|
|
def set_jwxt_account(user_id: int, username: str,
|
|
jwxt_username: str, jwxt_password: str,
|
|
jwxt_name: str = "", school_id: str = None) -> bool:
|
|
"""设置教务系统账号"""
|
|
return AccountManager.set_jwxt_account(
|
|
user_id, username, jwxt_username, jwxt_password, jwxt_name, school_id
|
|
)
|