feat: 自动拼图失败三次后改为手动拖动
This commit is contained in:
+15
-3
@@ -11,7 +11,7 @@ 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
|
from euniv.service import fetch_home, login_and_store, submit_jigsaw
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
@@ -28,6 +28,11 @@ class LoginBody(BaseModel):
|
|||||||
password: str = Field(min_length=1, max_length=128)
|
password: str = Field(min_length=1, max_length=128)
|
||||||
|
|
||||||
|
|
||||||
|
class JigsawBody(BaseModel):
|
||||||
|
attempt_id: str = Field(min_length=8, max_length=64)
|
||||||
|
offset: int = Field(ge=0, le=2000)
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/health")
|
@app.get("/api/health")
|
||||||
def health() -> dict:
|
def health() -> dict:
|
||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
@@ -37,10 +42,17 @@ def health() -> dict:
|
|||||||
def login(body: LoginBody, db: Session = Depends(get_db)) -> dict:
|
def login(body: LoginBody, db: Session = Depends(get_db)) -> dict:
|
||||||
employee_id = body.employee_id.strip()
|
employee_id = body.employee_id.strip()
|
||||||
try:
|
try:
|
||||||
login_and_store(db, employee_id, body.password)
|
return login_and_store(db, employee_id, body.password)
|
||||||
|
except RuntimeError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/login/jigsaw")
|
||||||
|
def login_jigsaw(body: JigsawBody, db: Session = Depends(get_db)) -> dict:
|
||||||
|
try:
|
||||||
|
return 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 {"employee_id": employee_id}
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/home")
|
@app.get("/api/home")
|
||||||
|
|||||||
+84
-37
@@ -48,6 +48,12 @@ def decode_data_uri(value: str) -> bytes:
|
|||||||
return base64.b64decode(payload)
|
return base64.b64decode(payload)
|
||||||
|
|
||||||
|
|
||||||
|
def data_uri(value: str) -> str:
|
||||||
|
if value.startswith("data:"):
|
||||||
|
return value
|
||||||
|
return "data:image/png;base64," + value
|
||||||
|
|
||||||
|
|
||||||
def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
|
def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
|
||||||
"""返回滑块左边缘在底图上的横坐标。"""
|
"""返回滑块左边缘在底图上的横坐标。"""
|
||||||
big = Image.open(io.BytesIO(big_png)).convert("RGBA")
|
big = Image.open(io.BytesIO(big_png)).convert("RGBA")
|
||||||
@@ -80,6 +86,17 @@ class SessionExpired(RuntimeError):
|
|||||||
"""学习平台凭证失效,需要重新登录。"""
|
"""学习平台凭证失效,需要重新登录。"""
|
||||||
|
|
||||||
|
|
||||||
|
class JigsawRejected(RuntimeError):
|
||||||
|
"""这次拼图位置不对,可以换一张再试。"""
|
||||||
|
|
||||||
|
|
||||||
|
class ManualJigsaw(Exception):
|
||||||
|
"""自动拼图已用完,把新拼图交给人来拖。"""
|
||||||
|
|
||||||
|
def __init__(self, puzzle: dict) -> None:
|
||||||
|
self.puzzle = puzzle
|
||||||
|
|
||||||
|
|
||||||
class EunivClient:
|
class EunivClient:
|
||||||
def __init__(self, login_name: str, password: str) -> None:
|
def __init__(self, login_name: str, password: str) -> None:
|
||||||
self.login_name = login_name.strip()
|
self.login_name = login_name.strip()
|
||||||
@@ -87,6 +104,9 @@ class EunivClient:
|
|||||||
self.client = httpx.Client(timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT})
|
self.client = httpx.Client(timeout=30, follow_redirects=True, headers={"User-Agent": USER_AGENT})
|
||||||
self._profile: dict = {}
|
self._profile: dict = {}
|
||||||
self._yxt_token = ""
|
self._yxt_token = ""
|
||||||
|
self._cipher = ""
|
||||||
|
self._kid = ""
|
||||||
|
self._puzzle: dict = {}
|
||||||
|
|
||||||
def close(self) -> None:
|
def close(self) -> None:
|
||||||
self.client.close()
|
self.client.close()
|
||||||
@@ -147,45 +167,72 @@ class EunivClient:
|
|||||||
if check_code not in ("", "0000"):
|
if check_code not in ("", "0000"):
|
||||||
raise RuntimeError(f"安全码检查失败:{check_message}")
|
raise RuntimeError(f"安全码检查失败:{check_message}")
|
||||||
|
|
||||||
cipher = encrypt_password(public_key, self.password)
|
self._cipher = encrypt_password(public_key, self.password)
|
||||||
last_message = "登录未完成"
|
|
||||||
for _ in range(3):
|
for _ in range(3):
|
||||||
kid = make_kid("t")
|
big, small, top = self._load_jigsaw()
|
||||||
image_resp = self.client.get(
|
try:
|
||||||
f"{PORTAL}/zte-bmt-ucs-portalbff/srv/kaptcha/jigsaw",
|
return self.submit_jigsaw(jigsaw_offset(big, small, top))
|
||||||
params={"kid": kid, "_t": now_ms()},
|
except JigsawRejected:
|
||||||
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
|
continue
|
||||||
raise RuntimeError(f"登录失败:{last_message}")
|
self._load_jigsaw()
|
||||||
raise RuntimeError(f"登录失败:{last_message}")
|
raise ManualJigsaw(self.current_puzzle())
|
||||||
|
|
||||||
|
def _load_jigsaw(self) -> tuple[bytes, bytes, int]:
|
||||||
|
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("拼图返回无法识别")
|
||||||
|
big = decode_data_uri(image["bigImg"])
|
||||||
|
small = decode_data_uri(image["smallImg"])
|
||||||
|
big_size = Image.open(io.BytesIO(big)).size
|
||||||
|
small_size = Image.open(io.BytesIO(small)).size
|
||||||
|
top = int(image["yHeight"])
|
||||||
|
self._kid = kid
|
||||||
|
self._puzzle = {
|
||||||
|
"big_img": data_uri(image["bigImg"]),
|
||||||
|
"small_img": data_uri(image["smallImg"]),
|
||||||
|
"y": top,
|
||||||
|
"width": big_size[0],
|
||||||
|
"height": big_size[1],
|
||||||
|
"piece_width": small_size[0],
|
||||||
|
"piece_height": small_size[1],
|
||||||
|
}
|
||||||
|
return big, small, top
|
||||||
|
|
||||||
|
def next_jigsaw(self) -> dict:
|
||||||
|
self._load_jigsaw()
|
||||||
|
return self.current_puzzle()
|
||||||
|
|
||||||
|
def current_puzzle(self) -> dict:
|
||||||
|
return dict(self._puzzle)
|
||||||
|
|
||||||
|
def submit_jigsaw(self, offset: int) -> dict:
|
||||||
|
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": self._cipher,
|
||||||
|
"kid": self._kid,
|
||||||
|
"jigsawCode": int(offset),
|
||||||
|
"_t": now_ms(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
login_code, message, profile = self.code_of(login_resp.json())
|
||||||
|
if login_code == "0000" and isinstance(profile, dict):
|
||||||
|
return profile
|
||||||
|
if any(word in message for word in ("验证码", "拼图", "滑块")):
|
||||||
|
raise JigsawRejected(message or "拼图未通过")
|
||||||
|
raise RuntimeError(f"登录失败:{message}")
|
||||||
|
|
||||||
def authorize(self, profile: dict) -> None:
|
def authorize(self, profile: dict) -> None:
|
||||||
account_id = str(profile["accountId"])
|
account_id = str(profile["accountId"])
|
||||||
|
|||||||
+83
-14
@@ -3,35 +3,98 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import secrets
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from euniv.client import EunivClient, SessionExpired
|
from euniv.client import EunivClient, JigsawRejected, ManualJigsaw, SessionExpired
|
||||||
from euniv.crypto import decrypt_secret, encrypt_secret
|
from euniv.crypto import decrypt_secret, encrypt_secret
|
||||||
from euniv.models import Account
|
from euniv.models import Account
|
||||||
|
|
||||||
|
_PENDING_SECONDS = 180
|
||||||
|
_pending: dict[str, "PendingLogin"] = {}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PendingLogin:
|
||||||
|
client: EunivClient
|
||||||
|
employee_id: str
|
||||||
|
password: str
|
||||||
|
created: float
|
||||||
|
|
||||||
|
|
||||||
def _dump(credential: dict) -> str:
|
def _dump(credential: dict) -> str:
|
||||||
return json.dumps(credential, ensure_ascii=False, sort_keys=True)
|
return json.dumps(credential, ensure_ascii=False, sort_keys=True)
|
||||||
|
|
||||||
|
|
||||||
def login_and_store(db: Session, employee_id: str, password: str, client_factory=EunivClient) -> Account:
|
def _purge_pending() -> None:
|
||||||
client = client_factory(employee_id, password)
|
now = time.time()
|
||||||
try:
|
for attempt_id, pending in list(_pending.items()):
|
||||||
profile = client.login()
|
if now - pending.created > _PENDING_SECONDS:
|
||||||
client.authorize(profile)
|
pending.client.close()
|
||||||
credential = client.export_credential()
|
_pending.pop(attempt_id, None)
|
||||||
finally:
|
|
||||||
client.close()
|
|
||||||
|
def _drop_employee(employee_id: str) -> None:
|
||||||
|
for attempt_id, pending in list(_pending.items()):
|
||||||
|
if pending.employee_id == employee_id:
|
||||||
|
pending.client.close()
|
||||||
|
_pending.pop(attempt_id, None)
|
||||||
|
|
||||||
|
|
||||||
|
def _persist(db: Session, employee_id: str, password: str, client: EunivClient, profile: dict) -> None:
|
||||||
|
client.authorize(profile)
|
||||||
account = db.get(Account, employee_id)
|
account = db.get(Account, employee_id)
|
||||||
if account is None:
|
if account is None:
|
||||||
account = Account(employee_id=employee_id, password_cipher="", credential_cipher="")
|
account = Account(employee_id=employee_id, password_cipher="", credential_cipher="")
|
||||||
db.add(account)
|
db.add(account)
|
||||||
account.password_cipher = encrypt_secret(password)
|
account.password_cipher = encrypt_secret(password)
|
||||||
account.credential_cipher = encrypt_secret(_dump(credential))
|
account.credential_cipher = encrypt_secret(_dump(client.export_credential()))
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(account)
|
|
||||||
return account
|
|
||||||
|
def login_and_store(db: Session, employee_id: str, password: str, client_factory=EunivClient) -> dict:
|
||||||
|
_purge_pending()
|
||||||
|
_drop_employee(employee_id)
|
||||||
|
client = client_factory(employee_id, password)
|
||||||
|
held = False
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
profile = client.login()
|
||||||
|
except ManualJigsaw as exc:
|
||||||
|
attempt_id = secrets.token_urlsafe(18)
|
||||||
|
_pending[attempt_id] = PendingLogin(client, employee_id, password, time.time())
|
||||||
|
held = True
|
||||||
|
return {"attempt_id": attempt_id, "jigsaw": exc.puzzle}
|
||||||
|
_persist(db, employee_id, password, client, profile)
|
||||||
|
return {"employee_id": employee_id}
|
||||||
|
finally:
|
||||||
|
if not held:
|
||||||
|
client.close()
|
||||||
|
|
||||||
|
|
||||||
|
def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict:
|
||||||
|
_purge_pending()
|
||||||
|
pending = _pending.get(attempt_id)
|
||||||
|
if pending is None:
|
||||||
|
raise RuntimeError("请重新登录")
|
||||||
|
try:
|
||||||
|
profile = pending.client.submit_jigsaw(offset)
|
||||||
|
except JigsawRejected:
|
||||||
|
pending.created = time.time()
|
||||||
|
return {"attempt_id": attempt_id, "jigsaw": pending.client.next_jigsaw()}
|
||||||
|
except Exception:
|
||||||
|
_pending.pop(attempt_id, None)
|
||||||
|
pending.client.close()
|
||||||
|
raise
|
||||||
|
_pending.pop(attempt_id, None)
|
||||||
|
try:
|
||||||
|
_persist(db, pending.employee_id, pending.password, pending.client, profile)
|
||||||
|
return {"employee_id": pending.employee_id}
|
||||||
|
finally:
|
||||||
|
pending.client.close()
|
||||||
|
|
||||||
|
|
||||||
def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
|
def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dict:
|
||||||
@@ -45,11 +108,17 @@ def fetch_home(db: Session, employee_id: str, client_factory=EunivClient) -> dic
|
|||||||
if credential.get("yxt_token"):
|
if credential.get("yxt_token"):
|
||||||
client.restore(credential)
|
client.restore(credential)
|
||||||
else:
|
else:
|
||||||
client.authorize(client.login())
|
try:
|
||||||
|
client.authorize(client.login())
|
||||||
|
except ManualJigsaw:
|
||||||
|
raise RuntimeError("登录需要重新验证,请重新登录") from None
|
||||||
try:
|
try:
|
||||||
data = client.home_snapshot()
|
data = client.home_snapshot()
|
||||||
except SessionExpired:
|
except SessionExpired:
|
||||||
client.authorize(client.login())
|
try:
|
||||||
|
client.authorize(client.login())
|
||||||
|
except ManualJigsaw:
|
||||||
|
raise RuntimeError("登录需要重新验证,请重新登录") from None
|
||||||
data = client.home_snapshot()
|
data = client.home_snapshot()
|
||||||
updated = client.export_credential()
|
updated = client.export_credential()
|
||||||
if _dump(updated) != _dump(credential):
|
if _dump(updated) != _dump(credential):
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import json
|
|||||||
from fastapi.testclient import TestClient
|
from fastapi.testclient import TestClient
|
||||||
from sqlalchemy import text
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
from euniv.client import JigsawRejected, ManualJigsaw
|
||||||
from euniv.crypto import decrypt_secret
|
from euniv.crypto import decrypt_secret
|
||||||
from euniv.db import SessionLocal, engine, init_db
|
from euniv.db import SessionLocal, engine, init_db
|
||||||
from euniv.models import Account
|
from euniv.models import Account
|
||||||
@@ -110,3 +111,92 @@ def test_login_stores_password_and_credential_only() -> None:
|
|||||||
assert updated["yxt_token"] == "yxt-2"
|
assert updated["yxt_token"] == "yxt-2"
|
||||||
assert "测试用户" not in decrypt_secret(account.credential_cipher)
|
assert "测试用户" not in decrypt_secret(account.credential_cipher)
|
||||||
assert "测试用户" not in decrypt_secret(account.password_cipher)
|
assert "测试用户" not in decrypt_secret(account.password_cipher)
|
||||||
|
|
||||||
|
|
||||||
|
def test_manual_jigsaw_keeps_image_pixels_and_retries() -> None:
|
||||||
|
import euniv.api as api_module
|
||||||
|
import euniv.service as service_module
|
||||||
|
|
||||||
|
service_module._pending.clear()
|
||||||
|
|
||||||
|
class ManualClient:
|
||||||
|
def __init__(self, login_name: str, password: str) -> None:
|
||||||
|
self.login_name = login_name
|
||||||
|
self.password = password
|
||||||
|
self._profile = {
|
||||||
|
"token": "ucs-1",
|
||||||
|
"accountId": login_name,
|
||||||
|
"userId": "u1",
|
||||||
|
"ssoinfo": "sso",
|
||||||
|
"unionId": "",
|
||||||
|
}
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def login(self) -> dict:
|
||||||
|
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,
|
||||||
|
})
|
||||||
|
|
||||||
|
def next_jigsaw(self) -> dict:
|
||||||
|
return {
|
||||||
|
"big_img": "data:image/png;base64,Yw==",
|
||||||
|
"small_img": "data:image/png;base64,ZA==",
|
||||||
|
"y": 60,
|
||||||
|
"width": 280,
|
||||||
|
"height": 172,
|
||||||
|
"piece_width": 48,
|
||||||
|
"piece_height": 48,
|
||||||
|
}
|
||||||
|
|
||||||
|
def submit_jigsaw(self, offset: int) -> dict:
|
||||||
|
if offset != 157:
|
||||||
|
raise JigsawRejected("拼图未通过")
|
||||||
|
return dict(self._profile)
|
||||||
|
|
||||||
|
def authorize(self, profile: dict) -> None:
|
||||||
|
self._profile = dict(profile)
|
||||||
|
|
||||||
|
def export_credential(self) -> dict:
|
||||||
|
return {
|
||||||
|
"ucs_token": "ucs-1",
|
||||||
|
"ucs_account_id": self.login_name,
|
||||||
|
"ucs_user_id": "u1",
|
||||||
|
"ucs_ssoinfo": "sso",
|
||||||
|
"ucs_union_id": "",
|
||||||
|
"yxt_token": "yxt-manual",
|
||||||
|
}
|
||||||
|
|
||||||
|
api_module.login_and_store = lambda db, employee_id, password: service_module.login_and_store(
|
||||||
|
db, employee_id, password, ManualClient
|
||||||
|
)
|
||||||
|
api_module.submit_jigsaw = service_module.submit_jigsaw
|
||||||
|
client = TestClient(api_module.app)
|
||||||
|
started = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
|
||||||
|
assert started.status_code == 200
|
||||||
|
body = started.json()
|
||||||
|
assert body["jigsaw"]["width"] == 280
|
||||||
|
assert body["jigsaw"]["height"] == 172
|
||||||
|
assert body["jigsaw"]["y"] == 56
|
||||||
|
assert "password" not in body["jigsaw"]
|
||||||
|
with SessionLocal() as db:
|
||||||
|
assert db.get(Account, "6650000146") is None
|
||||||
|
|
||||||
|
missed = client.post("/api/login/jigsaw", json={"attempt_id": body["attempt_id"], "offset": 10})
|
||||||
|
assert missed.status_code == 200
|
||||||
|
assert missed.json()["jigsaw"]["y"] == 60
|
||||||
|
|
||||||
|
done = client.post("/api/login/jigsaw", json={"attempt_id": body["attempt_id"], "offset": 157})
|
||||||
|
assert done.status_code == 200
|
||||||
|
assert done.json() == {"employee_id": "6650000146"}
|
||||||
|
with SessionLocal() as db:
|
||||||
|
account = db.get(Account, "6650000146")
|
||||||
|
assert account is not None
|
||||||
|
assert decrypt_secret(account.password_cipher) == "secret-pass"
|
||||||
|
|||||||
@@ -1,14 +1,49 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref } from "vue";
|
import { computed, ref } from "vue";
|
||||||
import { NAlert, NButton, NIcon, NInput, NTooltip } from "naive-ui";
|
import { NAlert, NButton, NIcon, NInput, NTooltip } from "naive-ui";
|
||||||
import { MoonOutline, SunnyOutline } from "@vicons/ionicons5";
|
import { ChevronForward, MoonOutline, SunnyOutline } from "@vicons/ionicons5";
|
||||||
import { isDark, toggleTheme } from "../../shared/theme";
|
import { isDark, toggleTheme } from "../../shared/theme";
|
||||||
|
|
||||||
|
interface JigsawPuzzle {
|
||||||
|
big_img: string;
|
||||||
|
small_img: string;
|
||||||
|
y: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
piece_width: number;
|
||||||
|
piece_height: number;
|
||||||
|
}
|
||||||
|
|
||||||
const emit = defineEmits<{ success: [employeeId: string] }>();
|
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 errorText = ref("");
|
const errorText = ref("");
|
||||||
|
const attemptId = ref("");
|
||||||
|
const jigsaw = ref<JigsawPuzzle | null>(null);
|
||||||
|
const offset = ref(0);
|
||||||
|
const dragging = ref(false);
|
||||||
|
let startX = 0;
|
||||||
|
let startOffset = 0;
|
||||||
|
|
||||||
|
const maxOffset = computed(() => {
|
||||||
|
const puzzle = jigsaw.value;
|
||||||
|
if (!puzzle) return 0;
|
||||||
|
return Math.max(puzzle.width - puzzle.piece_width, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
function applyResult(payload: { employee_id?: string; attempt_id?: string; jigsaw?: JigsawPuzzle }) {
|
||||||
|
if (payload.jigsaw && payload.attempt_id) {
|
||||||
|
attemptId.value = payload.attempt_id;
|
||||||
|
jigsaw.value = payload.jigsaw;
|
||||||
|
offset.value = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
password.value = "";
|
||||||
|
attemptId.value = "";
|
||||||
|
jigsaw.value = null;
|
||||||
|
emit("success", String(payload.employee_id || employeeId.value.trim()));
|
||||||
|
}
|
||||||
|
|
||||||
async function submit() {
|
async function submit() {
|
||||||
errorText.value = "";
|
errorText.value = "";
|
||||||
@@ -24,12 +59,54 @@ async function submit() {
|
|||||||
errorText.value = typeof payload.detail === "string" ? payload.detail : "登录失败";
|
errorText.value = typeof payload.detail === "string" ? payload.detail : "登录失败";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
password.value = "";
|
applyResult(payload);
|
||||||
emit("success", String(payload.employee_id || employeeId.value.trim()));
|
|
||||||
} finally {
|
} finally {
|
||||||
submitting.value = false;
|
submitting.value = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function sendOffset() {
|
||||||
|
if (!attemptId.value || submitting.value) return;
|
||||||
|
submitting.value = true;
|
||||||
|
errorText.value = "";
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/login/jigsaw", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ attempt_id: attemptId.value, offset: offset.value }),
|
||||||
|
});
|
||||||
|
const payload = await response.json().catch(() => ({}));
|
||||||
|
if (!response.ok) {
|
||||||
|
jigsaw.value = null;
|
||||||
|
attemptId.value = "";
|
||||||
|
errorText.value = typeof payload.detail === "string" ? payload.detail : "登录失败";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
applyResult(payload);
|
||||||
|
} finally {
|
||||||
|
submitting.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onPointerDown(event: PointerEvent) {
|
||||||
|
if (!jigsaw.value || submitting.value) return;
|
||||||
|
dragging.value = true;
|
||||||
|
startX = event.clientX;
|
||||||
|
startOffset = offset.value;
|
||||||
|
(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onPointerMove(event: PointerEvent) {
|
||||||
|
if (!dragging.value) return;
|
||||||
|
const next = startOffset + (event.clientX - startX);
|
||||||
|
offset.value = Math.min(Math.max(Math.round(next), 0), maxOffset.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onPointerUp() {
|
||||||
|
if (!dragging.value) return;
|
||||||
|
dragging.value = false;
|
||||||
|
if (offset.value > 0) void sendOffset();
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -42,7 +119,7 @@ async function submit() {
|
|||||||
</template>
|
</template>
|
||||||
{{ isDark ? "切换到日间" : "切换到夜间" }}
|
{{ isDark ? "切换到日间" : "切换到夜间" }}
|
||||||
</n-tooltip>
|
</n-tooltip>
|
||||||
<section class="gate-card">
|
<section class="gate-card" :class="{ 'with-jigsaw': jigsaw }">
|
||||||
<div class="brand">
|
<div class="brand">
|
||||||
<div class="brand-mark" aria-hidden="true">E</div>
|
<div class="brand-mark" aria-hidden="true">E</div>
|
||||||
<div>
|
<div>
|
||||||
@@ -53,13 +130,43 @@ async function submit() {
|
|||||||
<form @submit.prevent="submit">
|
<form @submit.prevent="submit">
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<label for="employee-id">工号</label>
|
<label for="employee-id">工号</label>
|
||||||
<n-input id="employee-id" v-model:value="employeeId" placeholder="工号" autocomplete="username" />
|
<n-input id="employee-id" v-model:value="employeeId" placeholder="工号" autocomplete="username" :disabled="!!jigsaw || submitting" />
|
||||||
</div>
|
</div>
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<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" />
|
<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="gate-actions">
|
<div v-if="jigsaw" class="jigsaw-block">
|
||||||
|
<p>拖动滑块完成拼图</p>
|
||||||
|
<div class="jigsaw" :style="{ width: jigsaw.width + 'px', height: jigsaw.height + 'px' }">
|
||||||
|
<img class="board" :src="jigsaw.big_img" alt="" :width="jigsaw.width" :height="jigsaw.height" draggable="false" />
|
||||||
|
<img
|
||||||
|
class="piece"
|
||||||
|
:src="jigsaw.small_img"
|
||||||
|
alt=""
|
||||||
|
:width="jigsaw.piece_width"
|
||||||
|
:height="jigsaw.piece_height"
|
||||||
|
:style="{ top: jigsaw.y + 'px', left: offset + 'px' }"
|
||||||
|
draggable="false"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="jigsaw-track" :style="{ width: jigsaw.width + 'px' }">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="jigsaw-handle"
|
||||||
|
:style="{ left: offset + 'px' }"
|
||||||
|
aria-label="拼图滑块"
|
||||||
|
:disabled="submitting"
|
||||||
|
@pointerdown="onPointerDown"
|
||||||
|
@pointermove="onPointerMove"
|
||||||
|
@pointerup="onPointerUp"
|
||||||
|
@pointercancel="onPointerUp"
|
||||||
|
>
|
||||||
|
<n-icon><ChevronForward /></n-icon>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-else class="gate-actions">
|
||||||
<n-button type="primary" attr-type="submit" :loading="submitting" :disabled="!employeeId.trim() || !password">登录</n-button>
|
<n-button type="primary" attr-type="submit" :loading="submitting" :disabled="!employeeId.trim() || !password">登录</n-button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|||||||
@@ -134,6 +134,65 @@ select {
|
|||||||
color: var(--ink);
|
color: var(--ink);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.gate-card.with-jigsaw {
|
||||||
|
width: max-content;
|
||||||
|
max-width: calc(100% - 32px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.jigsaw-block {
|
||||||
|
margin-top: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jigsaw-block p {
|
||||||
|
margin: 0 0 8px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jigsaw {
|
||||||
|
position: relative;
|
||||||
|
margin: 0 auto;
|
||||||
|
user-select: none;
|
||||||
|
touch-action: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jigsaw .board,
|
||||||
|
.jigsaw .piece {
|
||||||
|
display: block;
|
||||||
|
max-width: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jigsaw .piece {
|
||||||
|
position: absolute;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jigsaw-track {
|
||||||
|
position: relative;
|
||||||
|
height: 36px;
|
||||||
|
margin: 8px auto 0;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
background: var(--elevated);
|
||||||
|
touch-action: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jigsaw-handle {
|
||||||
|
position: absolute;
|
||||||
|
top: -1px;
|
||||||
|
width: 40px;
|
||||||
|
height: 36px;
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
padding: 0;
|
||||||
|
border: 1px solid var(--accent);
|
||||||
|
background: var(--panel);
|
||||||
|
color: var(--accent);
|
||||||
|
cursor: grab;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jigsaw-handle:disabled {
|
||||||
|
cursor: wait;
|
||||||
|
}
|
||||||
|
|
||||||
.gate-actions {
|
.gate-actions {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
|
|||||||
Reference in New Issue
Block a user