feat: 保持浏览器登录,并显示我的学时里的本月学时
This commit is contained in:
+52
-9
@@ -2,22 +2,29 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from fastapi import Depends, FastAPI, HTTPException
|
from fastapi import Depends, FastAPI, HTTPException, Request, Response
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from euniv.db import get_db, init_db
|
from euniv.db import get_db, init_db
|
||||||
from euniv.service import fetch_home, login_and_store, submit_jigsaw
|
from euniv.service import fetch_home, login_and_store, revoke_credential, start_credential_refresh, submit_jigsaw
|
||||||
|
from euniv.session import clear_session, read_employee_id, write_session
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(_app: FastAPI):
|
async def lifespan(_app: FastAPI):
|
||||||
init_db()
|
init_db()
|
||||||
|
stop = None
|
||||||
|
if os.environ.get("EUNIV_DISABLE_REFRESH") != "1":
|
||||||
|
stop = start_credential_refresh()
|
||||||
yield
|
yield
|
||||||
|
if stop is not None:
|
||||||
|
stop.set()
|
||||||
|
|
||||||
|
|
||||||
app = FastAPI(title="EunivTools", lifespan=lifespan)
|
app = FastAPI(title="EunivTools", lifespan=lifespan)
|
||||||
@@ -26,6 +33,7 @@ app = FastAPI(title="EunivTools", lifespan=lifespan)
|
|||||||
class LoginBody(BaseModel):
|
class LoginBody(BaseModel):
|
||||||
employee_id: str = Field(min_length=1, max_length=32)
|
employee_id: str = Field(min_length=1, max_length=32)
|
||||||
password: str = Field(min_length=1, max_length=128)
|
password: str = Field(min_length=1, max_length=128)
|
||||||
|
manual_jigsaw: bool = False
|
||||||
|
|
||||||
|
|
||||||
class JigsawBody(BaseModel):
|
class JigsawBody(BaseModel):
|
||||||
@@ -38,27 +46,62 @@ def health() -> dict:
|
|||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
def _open_session(response: Response, payload: dict) -> dict:
|
||||||
|
employee_id = payload.get("employee_id")
|
||||||
|
if employee_id:
|
||||||
|
write_session(response, employee_id)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/session")
|
||||||
|
def session(request: Request) -> dict:
|
||||||
|
employee_id = read_employee_id(request.cookies)
|
||||||
|
if not employee_id:
|
||||||
|
raise HTTPException(status_code=401, detail="未登录")
|
||||||
|
return {"employee_id": employee_id}
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/login")
|
@app.post("/api/login")
|
||||||
def login(body: LoginBody, db: Session = Depends(get_db)) -> dict:
|
def login(body: LoginBody, response: Response, db: Session = Depends(get_db)) -> dict:
|
||||||
employee_id = body.employee_id.strip()
|
|
||||||
try:
|
try:
|
||||||
return login_and_store(db, employee_id, body.password)
|
payload = login_and_store(db, body.employee_id.strip(), body.password, manual=body.manual_jigsaw)
|
||||||
except RuntimeError as exc:
|
except RuntimeError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
return _open_session(response, payload)
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/login/jigsaw")
|
@app.post("/api/login/jigsaw")
|
||||||
def login_jigsaw(body: JigsawBody, db: Session = Depends(get_db)) -> dict:
|
def login_jigsaw(body: JigsawBody, response: Response, db: Session = Depends(get_db)) -> dict:
|
||||||
try:
|
try:
|
||||||
return submit_jigsaw(db, body.attempt_id, body.offset)
|
payload = submit_jigsaw(db, body.attempt_id, body.offset)
|
||||||
except RuntimeError as exc:
|
except RuntimeError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
return _open_session(response, payload)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/logout")
|
||||||
|
def logout(response: Response) -> dict:
|
||||||
|
clear_session(response)
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/revoke")
|
||||||
|
def revoke(request: Request, response: Response, db: Session = Depends(get_db)) -> dict:
|
||||||
|
employee_id = read_employee_id(request.cookies)
|
||||||
|
if not employee_id:
|
||||||
|
raise HTTPException(status_code=401, detail="未登录")
|
||||||
|
revoke_credential(db, employee_id)
|
||||||
|
clear_session(response)
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/home")
|
@app.get("/api/home")
|
||||||
def home(employee_id: str, db: Session = Depends(get_db)) -> dict:
|
def home(request: Request, db: Session = Depends(get_db)) -> dict:
|
||||||
|
employee_id = read_employee_id(request.cookies)
|
||||||
|
if not employee_id:
|
||||||
|
raise HTTPException(status_code=401, detail="未登录")
|
||||||
try:
|
try:
|
||||||
return fetch_home(db, employee_id.strip())
|
return fetch_home(db, employee_id)
|
||||||
except RuntimeError as exc:
|
except RuntimeError as exc:
|
||||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
|||||||
+34
-1
@@ -5,6 +5,7 @@ from __future__ import annotations
|
|||||||
import base64
|
import base64
|
||||||
import io
|
import io
|
||||||
import random
|
import random
|
||||||
|
import re
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
@@ -134,7 +135,7 @@ class EunivClient:
|
|||||||
block = payload.get("code") or {}
|
block = payload.get("code") or {}
|
||||||
return block.get("code") or "", block.get("msg") or "", payload.get("bo")
|
return block.get("code") or "", block.get("msg") or "", payload.get("bo")
|
||||||
|
|
||||||
def login(self) -> dict:
|
def login(self, manual: bool = False) -> dict:
|
||||||
self.client.get(EUNIV + "/")
|
self.client.get(EUNIV + "/")
|
||||||
self.client.post(
|
self.client.post(
|
||||||
f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/validate",
|
f"{PORTAL}/zte-bmt-ucs-portalbff/oauth/validate",
|
||||||
@@ -168,6 +169,9 @@ class EunivClient:
|
|||||||
raise RuntimeError(f"安全码检查失败:{check_message}")
|
raise RuntimeError(f"安全码检查失败:{check_message}")
|
||||||
|
|
||||||
self._cipher = encrypt_password(public_key, self.password)
|
self._cipher = encrypt_password(public_key, self.password)
|
||||||
|
if manual:
|
||||||
|
self._load_jigsaw()
|
||||||
|
raise ManualJigsaw(self.current_puzzle())
|
||||||
for _ in range(3):
|
for _ in range(3):
|
||||||
big, small, top = self._load_jigsaw()
|
big, small, top = self._load_jigsaw()
|
||||||
try:
|
try:
|
||||||
@@ -441,8 +445,37 @@ class EunivClient:
|
|||||||
"today_score": today.get("studyScore"),
|
"today_score": today.get("studyScore"),
|
||||||
"pending_exam_count": pending_count,
|
"pending_exam_count": pending_count,
|
||||||
"pending_exams": self._pending_exams(pending_count),
|
"pending_exams": self._pending_exams(pending_count),
|
||||||
|
"month_hours": self._month_study_hours(),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def _month_study_hours(self) -> str:
|
||||||
|
text = self._study_period_page()
|
||||||
|
match = re.search(r'id="spMonthlyPeriod" title="(\d+)分钟"', text)
|
||||||
|
return match.group(1) if match else ""
|
||||||
|
|
||||||
|
def _study_period_page(self) -> str:
|
||||||
|
response = self.client.get(
|
||||||
|
f"{EUNIV}/study/myperiod.htm",
|
||||||
|
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"},
|
||||||
|
)
|
||||||
|
if "spMonthlyPeriod" in response.text:
|
||||||
|
return response.text
|
||||||
|
if self._profile.get("token"):
|
||||||
|
self.authorize(self._profile)
|
||||||
|
response = self.client.get(
|
||||||
|
f"{EUNIV}/study/myperiod.htm",
|
||||||
|
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/sty/index.htm"},
|
||||||
|
)
|
||||||
|
return response.text
|
||||||
|
|
||||||
|
def credential_alive(self) -> bool:
|
||||||
|
try:
|
||||||
|
response = self._request("POST", f"{YXT_API}/v1/customdiy/user/getuserinfobyid", content=b"")
|
||||||
|
except SessionExpired:
|
||||||
|
return False
|
||||||
|
payload = response.json()
|
||||||
|
return isinstance(payload, dict) and bool(payload.get("cnName"))
|
||||||
|
|
||||||
def _pending_exams(self, count: int) -> list[dict]:
|
def _pending_exams(self, count: int) -> list[dict]:
|
||||||
if count <= 0:
|
if count <= 0:
|
||||||
return []
|
return []
|
||||||
|
|||||||
@@ -4,9 +4,11 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import json
|
import json
|
||||||
import secrets
|
import secrets
|
||||||
|
import threading
|
||||||
import time
|
import time
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from euniv.client import EunivClient, JigsawRejected, ManualJigsaw, SessionExpired
|
from euniv.client import EunivClient, JigsawRejected, ManualJigsaw, SessionExpired
|
||||||
@@ -55,14 +57,24 @@ def _persist(db: Session, employee_id: str, password: str, client: EunivClient,
|
|||||||
db.commit()
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
def login_and_store(db: Session, employee_id: str, password: str, client_factory=EunivClient) -> dict:
|
def login_and_store(
|
||||||
|
db: Session,
|
||||||
|
employee_id: str,
|
||||||
|
password: str,
|
||||||
|
client_factory=EunivClient,
|
||||||
|
manual: bool = False,
|
||||||
|
) -> dict:
|
||||||
_purge_pending()
|
_purge_pending()
|
||||||
|
account = db.get(Account, employee_id)
|
||||||
|
if account and account.password_cipher and account.credential_cipher:
|
||||||
|
if decrypt_secret(account.password_cipher) == password and _credential_still_valid(account, client_factory):
|
||||||
|
return {"employee_id": employee_id}
|
||||||
_drop_employee(employee_id)
|
_drop_employee(employee_id)
|
||||||
client = client_factory(employee_id, password)
|
client = client_factory(employee_id, password)
|
||||||
held = False
|
held = False
|
||||||
try:
|
try:
|
||||||
try:
|
try:
|
||||||
profile = client.login()
|
profile = client.login(manual=manual)
|
||||||
except ManualJigsaw as exc:
|
except ManualJigsaw as exc:
|
||||||
attempt_id = secrets.token_urlsafe(18)
|
attempt_id = secrets.token_urlsafe(18)
|
||||||
_pending[attempt_id] = PendingLogin(client, employee_id, password, time.time())
|
_pending[attempt_id] = PendingLogin(client, employee_id, password, time.time())
|
||||||
@@ -75,6 +87,17 @@ def login_and_store(db: Session, employee_id: str, password: str, client_factory
|
|||||||
client.close()
|
client.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _credential_still_valid(account: Account, client_factory) -> bool:
|
||||||
|
client = client_factory(account.employee_id, decrypt_secret(account.password_cipher))
|
||||||
|
try:
|
||||||
|
client.restore(json.loads(decrypt_secret(account.credential_cipher)))
|
||||||
|
return bool(client.credential_alive())
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
client.close()
|
||||||
|
|
||||||
|
|
||||||
def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
|
def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
|
||||||
_purge_pending()
|
_purge_pending()
|
||||||
pending = _pending.get(attempt_id)
|
pending = _pending.get(attempt_id)
|
||||||
@@ -129,5 +152,50 @@ def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dic
|
|||||||
client.close()
|
client.close()
|
||||||
|
|
||||||
|
|
||||||
|
def revoke_credential(db: Session, employee_id: str) -> None:
|
||||||
|
account = db.get(Account, employee_id)
|
||||||
|
if account is None:
|
||||||
|
return
|
||||||
|
account.credential_cipher = ""
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def refresh_stored_credentials(client_factory=EunivClient) -> None:
|
||||||
|
from euniv.db import SessionLocal
|
||||||
|
|
||||||
|
with SessionLocal() as db:
|
||||||
|
accounts = list(db.scalars(select(Account)))
|
||||||
|
for account in accounts:
|
||||||
|
if not account.credential_cipher:
|
||||||
|
continue
|
||||||
|
client = client_factory(account.employee_id, decrypt_secret(account.password_cipher))
|
||||||
|
try:
|
||||||
|
previous = json.loads(decrypt_secret(account.credential_cipher))
|
||||||
|
client.restore(previous)
|
||||||
|
if client.credential_alive():
|
||||||
|
updated = client.export_credential()
|
||||||
|
if _dump(updated) != _dump(previous):
|
||||||
|
account.credential_cipher = encrypt_secret(_dump(updated))
|
||||||
|
db.commit()
|
||||||
|
continue
|
||||||
|
profile = client.login()
|
||||||
|
_persist(db, account.employee_id, decrypt_secret(account.password_cipher), client, profile)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
finally:
|
||||||
|
client.close()
|
||||||
|
|
||||||
|
|
||||||
|
def start_credential_refresh(interval_seconds: int = 1800) -> threading.Event:
|
||||||
|
stop = threading.Event()
|
||||||
|
|
||||||
|
def loop() -> None:
|
||||||
|
while not stop.wait(interval_seconds):
|
||||||
|
refresh_stored_credentials()
|
||||||
|
|
||||||
|
threading.Thread(target=loop, name="euniv-credential-refresh", daemon=True).start()
|
||||||
|
return stop
|
||||||
|
|
||||||
|
|
||||||
def stored_password(account: Account) -> str:
|
def stored_password(account: Account) -> str:
|
||||||
return decrypt_secret(account.password_cipher)
|
return decrypt_secret(account.password_cipher)
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""浏览器登录状态。只标识是谁,不存放 e 学凭证。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import Response
|
||||||
|
|
||||||
|
from euniv.crypto import decrypt_secret, encrypt_secret
|
||||||
|
|
||||||
|
COOKIE_NAME = "euniv_session"
|
||||||
|
MAX_AGE = 30 * 24 * 60 * 60
|
||||||
|
|
||||||
|
|
||||||
|
def read_employee_id(cookies) -> str | None:
|
||||||
|
raw = cookies.get(COOKIE_NAME)
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
employee_id = decrypt_secret(raw)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
employee_id = employee_id.strip()
|
||||||
|
return employee_id or None
|
||||||
|
|
||||||
|
|
||||||
|
def write_session(response: Response, employee_id: str) -> None:
|
||||||
|
response.set_cookie(
|
||||||
|
COOKIE_NAME,
|
||||||
|
encrypt_secret(employee_id),
|
||||||
|
max_age=MAX_AGE,
|
||||||
|
httponly=True,
|
||||||
|
samesite="lax",
|
||||||
|
path="/",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def clear_session(response: Response) -> None:
|
||||||
|
response.delete_cookie(COOKIE_NAME, path="/")
|
||||||
@@ -8,3 +8,4 @@ _root = _backend.parent / "Temp" / "pytest"
|
|||||||
_root.mkdir(parents=True, exist_ok=True)
|
_root.mkdir(parents=True, exist_ok=True)
|
||||||
os.environ["EUNIV_SECRET_KEY"] = "test-secret-key"
|
os.environ["EUNIV_SECRET_KEY"] = "test-secret-key"
|
||||||
os.environ["EUNIV_DB_PATH"] = str(_root / "euniv.db")
|
os.environ["EUNIV_DB_PATH"] = str(_root / "euniv.db")
|
||||||
|
os.environ["EUNIV_DISABLE_REFRESH"] = "1"
|
||||||
|
|||||||
@@ -25,9 +25,22 @@ class FakeClient:
|
|||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def login(self) -> dict:
|
def login(self, manual: bool = False) -> dict:
|
||||||
|
if manual:
|
||||||
|
raise ManualJigsaw({
|
||||||
|
"big_img": "data:image/png;base64,YQ==",
|
||||||
|
"small_img": "data:image/png;base64,Yg==",
|
||||||
|
"y": 56,
|
||||||
|
"width": 280,
|
||||||
|
"height": 172,
|
||||||
|
"piece_width": 48,
|
||||||
|
"piece_height": 48,
|
||||||
|
})
|
||||||
return dict(self._profile)
|
return dict(self._profile)
|
||||||
|
|
||||||
|
def credential_alive(self) -> bool:
|
||||||
|
return True
|
||||||
|
|
||||||
def authorize(self, profile: dict) -> None:
|
def authorize(self, profile: dict) -> None:
|
||||||
self._profile = dict(profile)
|
self._profile = dict(profile)
|
||||||
|
|
||||||
@@ -82,8 +95,8 @@ def test_login_stores_password_and_credential_only() -> None:
|
|||||||
import euniv.api as api_module
|
import euniv.api as api_module
|
||||||
import euniv.service as service_module
|
import euniv.service as service_module
|
||||||
|
|
||||||
api_module.login_and_store = lambda db, employee_id, password: service_module.login_and_store(
|
api_module.login_and_store = lambda db, employee_id, password, manual=False: service_module.login_and_store(
|
||||||
db, employee_id, password, FakeClient
|
db, employee_id, password, FakeClient, manual=manual
|
||||||
)
|
)
|
||||||
api_module.fetch_home = lambda db, employee_id: service_module.fetch_home(db, employee_id, FakeClient)
|
api_module.fetch_home = lambda db, employee_id: service_module.fetch_home(db, employee_id, FakeClient)
|
||||||
client = TestClient(api_module.app)
|
client = TestClient(api_module.app)
|
||||||
@@ -99,7 +112,7 @@ def test_login_stores_password_and_credential_only() -> None:
|
|||||||
assert stored["ucs_token"] == "ucs-1"
|
assert stored["ucs_token"] == "ucs-1"
|
||||||
assert set(account.__table__.columns.keys()) == {"employee_id", "password_cipher", "credential_cipher"}
|
assert set(account.__table__.columns.keys()) == {"employee_id", "password_cipher", "credential_cipher"}
|
||||||
|
|
||||||
home = client.get("/api/home", params={"employee_id": "6650000146"})
|
home = client.get("/api/home")
|
||||||
assert home.status_code == 200
|
assert home.status_code == 200
|
||||||
body = home.json()
|
body = home.json()
|
||||||
assert body["name"] == "测试用户"
|
assert body["name"] == "测试用户"
|
||||||
@@ -134,7 +147,7 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
|
|||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def login(self) -> dict:
|
def login(self, manual: bool = False) -> dict:
|
||||||
raise ManualJigsaw({
|
raise ManualJigsaw({
|
||||||
"big_img": "data:image/png;base64,YQ==",
|
"big_img": "data:image/png;base64,YQ==",
|
||||||
"small_img": "data:image/png;base64,Yg==",
|
"small_img": "data:image/png;base64,Yg==",
|
||||||
@@ -174,8 +187,8 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
|
|||||||
"yxt_token": "yxt-manual",
|
"yxt_token": "yxt-manual",
|
||||||
}
|
}
|
||||||
|
|
||||||
api_module.login_and_store = lambda db, employee_id, password: service_module.login_and_store(
|
api_module.login_and_store = lambda db, employee_id, password, manual=False: service_module.login_and_store(
|
||||||
db, employee_id, password, ManualClient
|
db, employee_id, password, ManualClient, manual=manual
|
||||||
)
|
)
|
||||||
api_module.submit_jigsaw = service_module.submit_jigsaw
|
api_module.submit_jigsaw = service_module.submit_jigsaw
|
||||||
client = TestClient(api_module.app)
|
client = TestClient(api_module.app)
|
||||||
@@ -200,3 +213,50 @@ def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
|
|||||||
account = db.get(Account, "6650000146")
|
account = db.get(Account, "6650000146")
|
||||||
assert account is not None
|
assert account is not None
|
||||||
assert decrypt_secret(account.password_cipher) == "secret-pass"
|
assert decrypt_secret(account.password_cipher) == "secret-pass"
|
||||||
|
|
||||||
|
|
||||||
|
def test_browser_session_logout_and_revoke() -> None:
|
||||||
|
import euniv.api as api_module
|
||||||
|
import euniv.service as service_module
|
||||||
|
|
||||||
|
calls = {"login": 0}
|
||||||
|
|
||||||
|
class RememberClient(FakeClient):
|
||||||
|
def login(self, manual: bool = False) -> dict:
|
||||||
|
calls["login"] += 1
|
||||||
|
return super().login(manual=manual)
|
||||||
|
|
||||||
|
api_module.login_and_store = lambda db, employee_id, password, manual=False: service_module.login_and_store(
|
||||||
|
db, employee_id, password, RememberClient, manual=manual
|
||||||
|
)
|
||||||
|
client = TestClient(api_module.app)
|
||||||
|
first = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
|
||||||
|
assert first.status_code == 200
|
||||||
|
with SessionLocal() as db:
|
||||||
|
account = db.get(Account, "6650000146")
|
||||||
|
assert account is not None
|
||||||
|
before = decrypt_secret(account.credential_cipher)
|
||||||
|
second = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
|
||||||
|
assert second.json() == {"employee_id": "6650000146"}
|
||||||
|
assert calls["login"] == 1
|
||||||
|
with SessionLocal() as db:
|
||||||
|
account = db.get(Account, "6650000146")
|
||||||
|
assert account is not None
|
||||||
|
assert decrypt_secret(account.credential_cipher) == before
|
||||||
|
assert client.get("/api/session").json() == {"employee_id": "6650000146"}
|
||||||
|
assert client.post("/api/logout").status_code == 200
|
||||||
|
assert client.get("/api/session").status_code == 401
|
||||||
|
with SessionLocal() as db:
|
||||||
|
account = db.get(Account, "6650000146")
|
||||||
|
assert account is not None
|
||||||
|
assert account.credential_cipher
|
||||||
|
again = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
|
||||||
|
assert again.status_code == 200
|
||||||
|
assert calls["login"] == 1
|
||||||
|
assert client.post("/api/revoke").status_code == 200
|
||||||
|
assert client.get("/api/session").status_code == 401
|
||||||
|
with SessionLocal() as db:
|
||||||
|
account = db.get(Account, "6650000146")
|
||||||
|
assert account is not None
|
||||||
|
assert account.credential_cipher == ""
|
||||||
|
assert decrypt_secret(account.password_cipher) == "secret-pass"
|
||||||
|
|||||||
+26
-3
@@ -1,20 +1,43 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref } from "vue";
|
import { onMounted, ref } from "vue";
|
||||||
import { darkTheme, dateZhCN, NConfigProvider, NDialogProvider, NMessageProvider, zhCN } from "naive-ui";
|
import { darkTheme, dateZhCN, NConfigProvider, NDialogProvider, NMessageProvider, zhCN } from "naive-ui";
|
||||||
import LoginView from "./features/auth/LoginView.vue";
|
import LoginView from "./features/auth/LoginView.vue";
|
||||||
import Shell from "./shell/Shell.vue";
|
import Shell from "./shell/Shell.vue";
|
||||||
import { isDark, themeOverrides } from "./shared/theme";
|
import { isDark, themeOverrides } from "./shared/theme";
|
||||||
|
|
||||||
|
const ready = ref(false);
|
||||||
const employeeId = ref("");
|
const employeeId = ref("");
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/session");
|
||||||
|
if (response.ok) {
|
||||||
|
const payload = await response.json();
|
||||||
|
employeeId.value = String(payload.employee_id || "");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
ready.value = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function exitSystem() {
|
||||||
|
await fetch("/api/logout", { method: "POST" });
|
||||||
|
employeeId.value = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function revokeAccount() {
|
||||||
|
await fetch("/api/revoke", { method: "POST" });
|
||||||
|
employeeId.value = "";
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<n-config-provider class="app-root" :locale="zhCN" :date-locale="dateZhCN" :theme="isDark ? darkTheme : null" :theme-overrides="themeOverrides">
|
<n-config-provider class="app-root" :locale="zhCN" :date-locale="dateZhCN" :theme="isDark ? darkTheme : null" :theme-overrides="themeOverrides">
|
||||||
<n-message-provider class="app-root">
|
<n-message-provider class="app-root">
|
||||||
<n-dialog-provider>
|
<n-dialog-provider>
|
||||||
<div class="app-root">
|
<div v-if="ready" class="app-root">
|
||||||
<LoginView v-if="!employeeId" @success="employeeId = $event" />
|
<LoginView v-if="!employeeId" @success="employeeId = $event" />
|
||||||
<Shell v-else :employee-id="employeeId" @logout="employeeId = ''" />
|
<Shell v-else :employee-id="employeeId" @logout="exitSystem" @revoke="revokeAccount" />
|
||||||
</div>
|
</div>
|
||||||
</n-dialog-provider>
|
</n-dialog-provider>
|
||||||
</n-message-provider>
|
</n-message-provider>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, ref } from "vue";
|
import { computed, ref } from "vue";
|
||||||
import { NAlert, NButton, NIcon, NInput, NTooltip } from "naive-ui";
|
import { NAlert, NButton, NCheckbox, NIcon, NInput, NTooltip } from "naive-ui";
|
||||||
import { ChevronForward, MoonOutline, SunnyOutline } from "@vicons/ionicons5";
|
import { ChevronForward, MoonOutline, SunnyOutline } from "@vicons/ionicons5";
|
||||||
import { isDark, toggleTheme } from "../../shared/theme";
|
import { isDark, toggleTheme } from "../../shared/theme";
|
||||||
|
|
||||||
@@ -18,6 +18,7 @@ const emit = defineEmits<{ success: [employeeId: string] }>();
|
|||||||
const employeeId = ref("");
|
const employeeId = ref("");
|
||||||
const password = ref("");
|
const password = ref("");
|
||||||
const submitting = ref(false);
|
const submitting = ref(false);
|
||||||
|
const manualJigsaw = ref(false);
|
||||||
const errorText = ref("");
|
const errorText = ref("");
|
||||||
const attemptId = ref("");
|
const attemptId = ref("");
|
||||||
const jigsaw = ref<JigsawPuzzle | null>(null);
|
const jigsaw = ref<JigsawPuzzle | null>(null);
|
||||||
@@ -52,7 +53,11 @@ async function submit() {
|
|||||||
const response = await fetch("/api/login", {
|
const response = await fetch("/api/login", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ employee_id: employeeId.value.trim(), password: password.value }),
|
body: JSON.stringify({
|
||||||
|
employee_id: employeeId.value.trim(),
|
||||||
|
password: password.value,
|
||||||
|
manual_jigsaw: manualJigsaw.value,
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
const payload = await response.json().catch(() => ({}));
|
const payload = await response.json().catch(() => ({}));
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
@@ -136,6 +141,10 @@ function onPointerUp() {
|
|||||||
<label for="password">密码</label>
|
<label for="password">密码</label>
|
||||||
<n-input id="password" v-model:value="password" type="password" show-password-on="click" placeholder="密码" autocomplete="current-password" :disabled="!!jigsaw || submitting" />
|
<n-input id="password" v-model:value="password" type="password" show-password-on="click" placeholder="密码" autocomplete="current-password" :disabled="!!jigsaw || submitting" />
|
||||||
</div>
|
</div>
|
||||||
|
<div class="form-row">
|
||||||
|
<span></span>
|
||||||
|
<n-checkbox v-model:checked="manualJigsaw" :disabled="!!jigsaw || submitting">手动滑动验证码</n-checkbox>
|
||||||
|
</div>
|
||||||
<div v-if="jigsaw" class="jigsaw-block">
|
<div v-if="jigsaw" class="jigsaw-block">
|
||||||
<p>拖动滑块完成拼图</p>
|
<p>拖动滑块完成拼图</p>
|
||||||
<div class="jigsaw" :style="{ width: jigsaw.width + 'px', height: jigsaw.height + 'px' }">
|
<div class="jigsaw" :style="{ width: jigsaw.width + 'px', height: jigsaw.height + 'px' }">
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ interface HomeProfile {
|
|||||||
level: string;
|
level: string;
|
||||||
year_score: string;
|
year_score: string;
|
||||||
month_score: string;
|
month_score: string;
|
||||||
|
month_hours: string;
|
||||||
total_hours: string;
|
total_hours: string;
|
||||||
total_score: string;
|
total_score: string;
|
||||||
today_hours: string | number | null;
|
today_hours: string | number | null;
|
||||||
@@ -35,6 +36,7 @@ const facts = computed(() => {
|
|||||||
return [
|
return [
|
||||||
{ label: "本年学分", value: current.year_score },
|
{ label: "本年学分", value: current.year_score },
|
||||||
{ label: "本月学分", value: current.month_score },
|
{ label: "本月学分", value: current.month_score },
|
||||||
|
{ label: "本月学时", value: current.month_hours },
|
||||||
{ label: "累计学时", value: current.total_hours },
|
{ label: "累计学时", value: current.total_hours },
|
||||||
{ label: "累计学分", value: current.total_score },
|
{ label: "累计学分", value: current.total_score },
|
||||||
{ label: "今日学时", value: current.today_hours ?? "—" },
|
{ label: "今日学时", value: current.today_hours ?? "—" },
|
||||||
@@ -51,7 +53,7 @@ async function load() {
|
|||||||
const current = ++requestId;
|
const current = ++requestId;
|
||||||
loading.value = profile.value === null;
|
loading.value = profile.value === null;
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/home?employee_id=${encodeURIComponent(props.employeeId)}`);
|
const response = await fetch("/api/home");
|
||||||
const payload = await response.json().catch(() => ({}));
|
const payload = await response.json().catch(() => ({}));
|
||||||
if (current !== requestId) return;
|
if (current !== requestId) return;
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
|||||||
+15
-8
@@ -1,13 +1,13 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted, onUnmounted, ref } from "vue";
|
import { onMounted, onUnmounted, ref } from "vue";
|
||||||
import { NButton, NIcon, NLayout, NLayoutSider, NMenu, NTooltip } from "naive-ui";
|
import { NButton, NDropdown, NIcon, NLayout, NLayoutSider, NMenu, NTooltip } from "naive-ui";
|
||||||
import { LogOutOutline, MoonOutline, PersonOutline, SunnyOutline } from "@vicons/ionicons5";
|
import { LogOutOutline, MoonOutline, PersonOutline, SunnyOutline } from "@vicons/ionicons5";
|
||||||
import { isDark, toggleTheme } from "../shared/theme";
|
import { isDark, toggleTheme } from "../shared/theme";
|
||||||
import { navOptions, type PageKey } from "./navigation";
|
import { navOptions, type PageKey } from "./navigation";
|
||||||
import HomeView from "../features/home/HomeView.vue";
|
import HomeView from "../features/home/HomeView.vue";
|
||||||
|
|
||||||
const props = defineProps<{ employeeId: string }>();
|
const props = defineProps<{ employeeId: string }>();
|
||||||
const emit = defineEmits<{ logout: [] }>();
|
const emit = defineEmits<{ logout: []; revoke: [] }>();
|
||||||
const page = ref<PageKey>("home");
|
const page = ref<PageKey>("home");
|
||||||
const collapsed = ref(window.innerWidth < 800);
|
const collapsed = ref(window.innerWidth < 800);
|
||||||
|
|
||||||
@@ -18,9 +18,19 @@ function onResize() {
|
|||||||
onMounted(() => window.addEventListener("resize", onResize));
|
onMounted(() => window.addEventListener("resize", onResize));
|
||||||
onUnmounted(() => window.removeEventListener("resize", onResize));
|
onUnmounted(() => window.removeEventListener("resize", onResize));
|
||||||
|
|
||||||
|
const logoutOptions = [
|
||||||
|
{ label: "退出当前系统", key: "logout" },
|
||||||
|
{ label: "注销当前账号", key: "revoke" },
|
||||||
|
];
|
||||||
|
|
||||||
function onMenu(key: string) {
|
function onMenu(key: string) {
|
||||||
if (key === "home") page.value = key;
|
if (key === "home") page.value = key;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function onLogout(key: string) {
|
||||||
|
if (key === "revoke") emit("revoke");
|
||||||
|
else emit("logout");
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -64,14 +74,11 @@ function onMenu(key: string) {
|
|||||||
</template>
|
</template>
|
||||||
{{ isDark ? "切换到日间" : "切换到夜间" }}
|
{{ isDark ? "切换到日间" : "切换到夜间" }}
|
||||||
</n-tooltip>
|
</n-tooltip>
|
||||||
<n-tooltip>
|
<n-dropdown trigger="hover" placement="top-end" :options="logoutOptions" @select="onLogout">
|
||||||
<template #trigger>
|
<n-button class="logout-btn" quaternary circle size="small" aria-label="退出">
|
||||||
<n-button class="logout-btn" quaternary circle size="small" aria-label="退出" @click="emit('logout')">
|
|
||||||
<template #icon><n-icon><LogOutOutline /></n-icon></template>
|
<template #icon><n-icon><LogOutOutline /></n-icon></template>
|
||||||
</n-button>
|
</n-button>
|
||||||
</template>
|
</n-dropdown>
|
||||||
退出
|
|
||||||
</n-tooltip>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</n-layout-sider>
|
</n-layout-sider>
|
||||||
|
|||||||
Reference in New Issue
Block a user