refactor: 本地只保存工号和加密密码,并整理后端目录
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
"""中兴 e 学客户端和本机账号库。"""
|
||||
|
||||
from euniv.client import EunivClient
|
||||
|
||||
__all__ = ["EunivClient"]
|
||||
@@ -0,0 +1,53 @@
|
||||
"""登录接口。本地只保存工号和加密密码。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import Depends, FastAPI, HTTPException
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from euniv.db import get_db, init_db
|
||||
from euniv.service import list_accounts, login_and_store
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
init_db()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="EunivTools", lifespan=lifespan)
|
||||
|
||||
|
||||
class LoginBody(BaseModel):
|
||||
employee_id: str = Field(min_length=1, max_length=32)
|
||||
password: str = Field(min_length=1, max_length=128)
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def health() -> dict:
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.post("/api/login")
|
||||
def login(body: LoginBody, db: Session = Depends(get_db)) -> dict:
|
||||
employee_id = body.employee_id.strip()
|
||||
try:
|
||||
login_and_store(db, employee_id, body.password)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
return {"employee_id": employee_id}
|
||||
|
||||
|
||||
@app.get("/api/accounts")
|
||||
def accounts(db: Session = Depends(get_db)) -> list[dict]:
|
||||
return [{"employee_id": item.employee_id} for item in list_accounts(db)]
|
||||
|
||||
|
||||
_dist = Path(__file__).resolve().parents[2] / "web" / "dist"
|
||||
if _dist.is_dir():
|
||||
app.mount("/", StaticFiles(directory=_dist, html=True), name="web")
|
||||
@@ -0,0 +1,298 @@
|
||||
"""登录中兴 e 学并查询学时、学分汇总。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
import random
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
import httpx
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from PIL import Image
|
||||
|
||||
PORTAL = "https://bmtucportal.zte.com.cn"
|
||||
EUNIV = "https://euniv.zte.com.cn"
|
||||
YXT_API = "https://api-qidacustomc1.yunxuetang.cn"
|
||||
STUDY_API = "https://api-qidac1.yunxuetang.cn"
|
||||
CLASS_API = "https://sdcs-api-ztec1.yunxuetang.cn"
|
||||
REDIRECT_URI = f"{YXT_API}/v1/ztctech/sso"
|
||||
CLIENT_ID = "30051"
|
||||
TENANT_ID = "10001"
|
||||
APP_ID = "10051"
|
||||
USER_AGENT = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:158.0) "
|
||||
"Gecko/20100101 Firefox/158.0"
|
||||
)
|
||||
|
||||
|
||||
def now_ms() -> int:
|
||||
return int(time.time() * 1000)
|
||||
|
||||
|
||||
def make_kid(prefix: str = "t") -> str:
|
||||
return prefix + "".join(random.choice("1234567890") for _ in range(4))
|
||||
|
||||
|
||||
def encrypt_password(public_key_b64: str, password: str) -> str:
|
||||
key = serialization.load_der_public_key(base64.b64decode(public_key_b64))
|
||||
cipher = key.encrypt(password.encode("utf-8"), padding.PKCS1v15())
|
||||
return base64.b64encode(cipher).decode("ascii")
|
||||
|
||||
|
||||
def decode_data_uri(value: str) -> bytes:
|
||||
payload = value.split(",", 1)[1] if "," in value else value
|
||||
return base64.b64decode(payload)
|
||||
|
||||
|
||||
def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
|
||||
"""返回滑块左边缘在底图上的横坐标。"""
|
||||
big = Image.open(io.BytesIO(big_png)).convert("RGBA")
|
||||
small = Image.open(io.BytesIO(small_png)).convert("RGBA")
|
||||
width, height = big.size
|
||||
piece_w, piece_h = small.size
|
||||
mask: list[tuple[int, int, tuple[int, int, int]]] = []
|
||||
for y in range(piece_h):
|
||||
for x in range(piece_w):
|
||||
red, green, blue, alpha = small.getpixel((x, y))
|
||||
if alpha > 128:
|
||||
mask.append((x, y, (red, green, blue)))
|
||||
best_x = 0
|
||||
best_score = None
|
||||
limit = width - piece_w
|
||||
for origin in range(max(limit, 0)):
|
||||
score = 0
|
||||
for x, y, color in mask:
|
||||
pixel = big.getpixel((origin + x, top + y))
|
||||
score += abs(pixel[0] - color[0]) + abs(pixel[1] - color[1]) + abs(pixel[2] - color[2])
|
||||
if best_score is None or score < best_score:
|
||||
best_score = score
|
||||
best_x = origin
|
||||
if top + piece_h > height:
|
||||
raise RuntimeError("拼图纵坐标超出底图高度")
|
||||
return best_x
|
||||
|
||||
|
||||
class EunivClient:
|
||||
def __init__(self, login_name: str, password: str) -> None:
|
||||
self.login_name = login_name.strip()
|
||||
self.password = password
|
||||
self.client = httpx.Client(timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT})
|
||||
|
||||
def close(self) -> None:
|
||||
self.client.close()
|
||||
|
||||
def portal_headers(self) -> dict[str, str]:
|
||||
referer = (
|
||||
f"{PORTAL}/uc/{TENANT_ID}/oauthLogin?client_id={CLIENT_ID}"
|
||||
f"&scope=profile&redirect_uri={quote(REDIRECT_URI, safe='')}"
|
||||
"&response_type=code"
|
||||
)
|
||||
return {
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Content-Type": "application/json;charset=UTF-8",
|
||||
"Origin": PORTAL,
|
||||
"Referer": referer,
|
||||
"X-App-Id": APP_ID,
|
||||
"X-Device-Type": "pc",
|
||||
"X-Itp-Value": "from=ucs-portal;client=pc;platform=portal",
|
||||
"X-Lang-Id": "zh_CN",
|
||||
"X-Tenant-Id": TENANT_ID,
|
||||
"x_uuid": str(uuid.uuid4()),
|
||||
}
|
||||
|
||||
def code_of(self, payload: dict) -> tuple[str, str, object]:
|
||||
block = payload.get("code") or {}
|
||||
return block.get("code") or "", block.get("msg") or "", payload.get("bo")
|
||||
|
||||
def login(self) -> dict:
|
||||
self.client.get(EUNIV + "/")
|
||||
self.client.post(
|
||||
f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/validate",
|
||||
headers=self.portal_headers(),
|
||||
json={
|
||||
"clientId": CLIENT_ID,
|
||||
"redirectUri": REDIRECT_URI,
|
||||
"responseType": "code",
|
||||
"scope": "profile",
|
||||
"_t": now_ms(),
|
||||
},
|
||||
)
|
||||
key_resp = self.client.post(
|
||||
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/password/publicKey/{TENANT_ID}",
|
||||
headers=self.portal_headers(),
|
||||
json={"_t": now_ms()},
|
||||
)
|
||||
key_code, key_message, public_key = self.code_of(key_resp.json())
|
||||
if key_code != "0000" or not isinstance(public_key, str):
|
||||
raise RuntimeError(f"获取密码公钥失败:{key_message or key_resp.status_code}")
|
||||
|
||||
check_resp = self.client.post(
|
||||
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/pas/securitycode/check",
|
||||
headers=self.portal_headers(),
|
||||
json={"accountId": self.login_name, "callerId": APP_ID, "_t": now_ms()},
|
||||
)
|
||||
check_code, check_message, needs_security_code = self.code_of(check_resp.json())
|
||||
if check_code == "0000" and needs_security_code is True:
|
||||
raise RuntimeError("这个账号开启了动态安全码,当前登录流程还不能提交安全码")
|
||||
if check_code not in ("", "0000"):
|
||||
raise RuntimeError(f"安全码检查失败:{check_message}")
|
||||
|
||||
cipher = encrypt_password(public_key, self.password)
|
||||
last_message = "登录未完成"
|
||||
for _ in range(3):
|
||||
kid = make_kid("t")
|
||||
image_resp = self.client.get(
|
||||
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/kaptcha/jigsaw",
|
||||
params={"kid": kid, "_t": now_ms()},
|
||||
headers=self.portal_headers(),
|
||||
)
|
||||
image_code, image_message, image = self.code_of(image_resp.json())
|
||||
if image_code != "0000":
|
||||
raise RuntimeError(f"获取拼图失败:{image_message}")
|
||||
if not isinstance(image, dict):
|
||||
raise RuntimeError("拼图返回无法识别")
|
||||
offset = jigsaw_offset(
|
||||
decode_data_uri(image["bigImg"]),
|
||||
decode_data_uri(image["smallImg"]),
|
||||
int(image["yHeight"]),
|
||||
)
|
||||
headers = self.portal_headers()
|
||||
headers.update({"kcode": "", "kid": make_kid(""), "kskip": "true", "source": APP_ID})
|
||||
login_resp = self.client.post(
|
||||
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/login",
|
||||
headers=headers,
|
||||
json={
|
||||
"loginName": self.login_name,
|
||||
"password": cipher,
|
||||
"kid": kid,
|
||||
"jigsawCode": offset,
|
||||
"_t": now_ms(),
|
||||
},
|
||||
)
|
||||
login_code, last_message, profile = self.code_of(login_resp.json())
|
||||
if login_code == "0000" and isinstance(profile, dict):
|
||||
return profile
|
||||
if any(word in last_message for word in ("验证码", "拼图", "滑块")):
|
||||
continue
|
||||
raise RuntimeError(f"登录失败:{last_message}")
|
||||
raise RuntimeError(f"登录失败:{last_message}")
|
||||
|
||||
def authorize(self, profile: dict) -> None:
|
||||
account_id = str(profile["accountId"])
|
||||
user_id = str(profile["userId"])
|
||||
token = str(profile["token"])
|
||||
domain = "zte.com.cn"
|
||||
jar = {
|
||||
"UCSLoginName": account_id,
|
||||
"UCSSSOAccount": account_id,
|
||||
"UCSSSOUser": user_id,
|
||||
"UCSSSOToken": token,
|
||||
"UCSSSOInfo": str(profile.get("ssoinfo") or ""),
|
||||
"UCSSSOLanguage": "zh_CN",
|
||||
"UCSLoginTime": str(now_ms()),
|
||||
"iAuthTenantId_prod": TENANT_ID,
|
||||
"iAuthUserId_prod": user_id,
|
||||
"iAuthUid_prod": account_id,
|
||||
"iAuthTid_prod": token,
|
||||
"iAuthLanguage_prod": "zh_CN",
|
||||
}
|
||||
if profile.get("unionId"):
|
||||
jar["iuacUnionId"] = str(profile["unionId"])
|
||||
for name, value in jar.items():
|
||||
self.client.cookies.set(name, value, domain=domain, path="/")
|
||||
|
||||
response = self.client.post(
|
||||
f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/authorize",
|
||||
params={
|
||||
"redirect_uri": REDIRECT_URI,
|
||||
"client_id": CLIENT_ID,
|
||||
"response_type": "code",
|
||||
"scope": "profile",
|
||||
},
|
||||
headers=self.portal_headers(),
|
||||
json={"accountId": account_id, "token": token, "userId": user_id, "_t": now_ms()},
|
||||
)
|
||||
code, message, redirect_url = self.code_of(response.json())
|
||||
if code != "0000" or not isinstance(redirect_url, str):
|
||||
raise RuntimeError(f"申请学习平台授权码失败:{message}")
|
||||
self.client.get(redirect_url, headers={"Referer": PORTAL + "/", "User-Agent": USER_AGENT})
|
||||
|
||||
def session_token(self) -> str:
|
||||
for cookie in self.client.cookies.jar:
|
||||
if cookie.name == "ELEARNING_00024" and cookie.value:
|
||||
return cookie.value
|
||||
names = sorted({cookie.name for cookie in self.client.cookies.jar})
|
||||
raise RuntimeError("学习平台没有返回登录会话,现有 Cookie 名称:" + ", ".join(names))
|
||||
|
||||
def user_info(self) -> dict:
|
||||
response = self.client.post(
|
||||
f"{YXT_API}/v1/customdiy/user/getuserinfobyid",
|
||||
content=b"",
|
||||
headers=self.api_headers(),
|
||||
)
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
if not isinstance(payload, dict) or "cnName" not in payload:
|
||||
raise RuntimeError("用户信息返回无法识别")
|
||||
return payload
|
||||
|
||||
def api_headers(self) -> dict[str, str]:
|
||||
return {
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Content-Type": "application/json",
|
||||
"Origin": EUNIV,
|
||||
"Referer": EUNIV + "/",
|
||||
"source": "501",
|
||||
"token": self.session_token(),
|
||||
"User-Agent": USER_AGENT,
|
||||
}
|
||||
|
||||
def study_snapshot(self) -> dict:
|
||||
"""查询学时、学分和积分汇总,以及今日数据、我的班级数量。"""
|
||||
headers = self.api_headers()
|
||||
score_resp = self.client.post(
|
||||
f"{YXT_API}/v1/customapiforweb/getscoreorpointorhour",
|
||||
json={},
|
||||
headers=headers,
|
||||
)
|
||||
score_resp.raise_for_status()
|
||||
score_payload = score_resp.json()
|
||||
data = score_payload.get("data") or {}
|
||||
if score_payload.get("code") not in (None, "0", 0):
|
||||
raise RuntimeError(score_payload.get("message") or "学时学分查询失败")
|
||||
|
||||
today_resp = self.client.get(
|
||||
f"{STUDY_API}/v1/studyapi/studyhour/todayscorehours",
|
||||
headers=headers,
|
||||
)
|
||||
today_resp.raise_for_status()
|
||||
today = today_resp.json()
|
||||
|
||||
class_count = None
|
||||
class_resp = self.client.get(
|
||||
f"{CLASS_API}/v1/zte/my/class",
|
||||
params={"limit": 10, "offset": 0, "lang": 0},
|
||||
headers=headers,
|
||||
)
|
||||
if class_resp.status_code == 200:
|
||||
paging = ((class_resp.json().get("data") or {}).get("paging") or {})
|
||||
class_count = paging.get("totalCount")
|
||||
|
||||
return {
|
||||
"actual_study_hour": data.get("actualStudyHour"),
|
||||
"actual_study_score": data.get("actualStudyScore"),
|
||||
"points": data.get("totalUserPoint") or data.get("ablePoint"),
|
||||
"today_hours": today.get("studyHours"),
|
||||
"today_score": today.get("studyScore"),
|
||||
"today": today.get("toDate"),
|
||||
"class_count": class_count,
|
||||
}
|
||||
|
||||
def open_session(self) -> dict:
|
||||
profile = self.login()
|
||||
self.authorize(profile)
|
||||
return {"profile": self.user_info(), "summary": self.study_snapshot()}
|
||||
@@ -0,0 +1,25 @@
|
||||
"""用服务端密钥对 e 学密码做可逆加密。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
|
||||
def _fernet() -> Fernet:
|
||||
secret = os.environ.get("EUNIV_SECRET_KEY", "")
|
||||
if not secret:
|
||||
raise RuntimeError("请设置环境变量 EUNIV_SECRET_KEY")
|
||||
digest = hashlib.sha256(secret.encode("utf-8")).digest()
|
||||
return Fernet(base64.urlsafe_b64encode(digest))
|
||||
|
||||
|
||||
def encrypt_secret(value: str) -> str:
|
||||
return _fernet().encrypt(value.encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
def decrypt_secret(value: str) -> str:
|
||||
return _fernet().decrypt(value.encode("ascii")).decode("utf-8")
|
||||
@@ -0,0 +1,47 @@
|
||||
"""SQLite 连接。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
|
||||
def database_url() -> str:
|
||||
path = os.environ.get("EUNIV_DB_PATH", "data/euniv.db")
|
||||
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||
return "sqlite:///" + path.replace("\\", "/")
|
||||
|
||||
|
||||
engine = create_engine(database_url(), connect_args={"check_same_thread": False})
|
||||
SessionLocal = sessionmaker(bind=engine, autoflush=False, expire_on_commit=False)
|
||||
|
||||
|
||||
@event.listens_for(engine, "connect")
|
||||
def _enable_wal(dbapi_connection, _connection_record) -> None:
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
cursor.execute("PRAGMA busy_timeout=5000")
|
||||
cursor.close()
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
config = Config(str(root / "alembic.ini"))
|
||||
config.set_main_option("script_location", str(root / "alembic"))
|
||||
config.set_main_option("sqlalchemy.url", database_url())
|
||||
command.upgrade(config, "head")
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,17 @@
|
||||
"""本地只保存工号和加密后的密码。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import String, Text
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class Account(Base):
|
||||
__tablename__ = "accounts"
|
||||
|
||||
employee_id: Mapped[str] = mapped_column(String(32), primary_key=True)
|
||||
password_cipher: Mapped[str] = mapped_column(Text)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""校验 e 学登录,并只把工号和加密密码写入本地库。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from euniv.client import EunivClient
|
||||
from euniv.crypto import decrypt_secret, encrypt_secret
|
||||
from euniv.models import Account
|
||||
|
||||
|
||||
def login_and_store(db: Session, employee_id: str, password: str, client_factory=EunivClient) -> Account:
|
||||
client = client_factory(employee_id, password)
|
||||
try:
|
||||
client.login()
|
||||
finally:
|
||||
client.close()
|
||||
account = db.get(Account, employee_id)
|
||||
if account is None:
|
||||
account = Account(employee_id=employee_id, password_cipher=encrypt_secret(password))
|
||||
db.add(account)
|
||||
else:
|
||||
account.password_cipher = encrypt_secret(password)
|
||||
db.commit()
|
||||
db.refresh(account)
|
||||
return account
|
||||
|
||||
|
||||
def list_accounts(db: Session) -> list[Account]:
|
||||
return list(db.scalars(select(Account).order_by(Account.employee_id)))
|
||||
|
||||
|
||||
def stored_password(account: Account) -> str:
|
||||
return decrypt_secret(account.password_cipher)
|
||||
Reference in New Issue
Block a user