170 lines
4.9 KiB
Python
170 lines
4.9 KiB
Python
"""本地用户的列表、检查、暂停和删除。按请求读数据库,不缓存用户或凭证。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from datetime import datetime, timezone
|
|
|
|
from fastapi import HTTPException
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from euniv.crypto import decrypt_secret
|
|
from euniv.models import Account
|
|
|
|
_TOKEN_KEYS = (
|
|
"ucs_token",
|
|
"ucs_account_id",
|
|
"ucs_user_id",
|
|
"ucs_ssoinfo",
|
|
"ucs_union_id",
|
|
"yxt_token",
|
|
)
|
|
|
|
|
|
def build_client(login_name: str, password: str):
|
|
from euniv.client import EunivClient
|
|
|
|
return EunivClient(login_name, password)
|
|
|
|
|
|
def record_outcome(account: Account, valid: bool | None) -> None:
|
|
account.last_refresh_at = datetime.now(timezone.utc)
|
|
account.credential_valid = valid
|
|
|
|
|
|
def _optional_bool(value: object) -> bool | None:
|
|
if value is None:
|
|
return None
|
|
return bool(value)
|
|
|
|
|
|
def _iso_time(value: datetime | None) -> str | None:
|
|
if value is None:
|
|
return None
|
|
if value.tzinfo is None:
|
|
value = value.replace(tzinfo=timezone.utc)
|
|
return value.isoformat()
|
|
|
|
|
|
def list_users(db: Session) -> list[dict]:
|
|
has_credential = (Account.credential_cipher != "").label("has_credential")
|
|
rows = db.execute(
|
|
select(
|
|
Account.employee_id,
|
|
has_credential,
|
|
Account.refresh_paused,
|
|
Account.last_refresh_at,
|
|
Account.credential_valid,
|
|
).order_by(Account.employee_id)
|
|
).all()
|
|
return [
|
|
{
|
|
"employee_id": row.employee_id,
|
|
"has_credential": bool(row.has_credential),
|
|
"refresh_paused": bool(row.refresh_paused),
|
|
"last_refresh_at": _iso_time(row.last_refresh_at),
|
|
"credential_valid": _optional_bool(row.credential_valid),
|
|
}
|
|
for row in rows
|
|
]
|
|
|
|
|
|
def _require(db: Session, employee_id: str) -> Account:
|
|
account = db.get(Account, employee_id)
|
|
if account is None:
|
|
raise HTTPException(status_code=404, detail="用户不存在")
|
|
return account
|
|
|
|
|
|
def check_employee(db: Session, employee_id: str) -> dict:
|
|
account = _require(db, employee_id)
|
|
if not account.credential_cipher:
|
|
return {"employee_id": employee_id, "result": "未保存"}
|
|
before_password = account.password_cipher
|
|
before_credential = account.credential_cipher
|
|
client = None
|
|
result = "检查失败"
|
|
valid: bool | None = None
|
|
try:
|
|
client = build_client(employee_id, decrypt_secret(account.password_cipher))
|
|
client.restore(json.loads(decrypt_secret(account.credential_cipher)))
|
|
alive = bool(client.credential_alive())
|
|
result = "有效" if alive else "已失效"
|
|
valid = alive
|
|
except Exception:
|
|
db.rollback()
|
|
account = db.get(Account, employee_id)
|
|
result = "检查失败"
|
|
valid = None
|
|
finally:
|
|
if client is not None:
|
|
try:
|
|
client.close()
|
|
except Exception:
|
|
pass
|
|
if account is None:
|
|
raise HTTPException(status_code=404, detail="用户不存在")
|
|
if result != "检查失败":
|
|
account.password_cipher = before_password
|
|
account.credential_cipher = before_credential
|
|
record_outcome(account, valid)
|
|
db.commit()
|
|
payload = {"employee_id": employee_id, "result": result}
|
|
if result == "检查失败":
|
|
payload["detail"] = "检查失败"
|
|
return payload
|
|
|
|
|
|
def check_all(db: Session) -> list[dict]:
|
|
employee_ids = list(
|
|
db.scalars(
|
|
select(Account.employee_id)
|
|
.where(Account.credential_cipher != "")
|
|
.order_by(Account.employee_id)
|
|
)
|
|
)
|
|
results = []
|
|
for employee_id in employee_ids:
|
|
try:
|
|
results.append(check_employee(db, employee_id))
|
|
except HTTPException:
|
|
raise
|
|
except Exception:
|
|
results.append({"employee_id": employee_id, "result": "检查失败", "detail": "检查失败"})
|
|
return results
|
|
|
|
|
|
def set_paused(db: Session, employee_id: str, paused: bool) -> dict:
|
|
account = _require(db, employee_id)
|
|
account.refresh_paused = paused
|
|
db.commit()
|
|
return {"ok": True}
|
|
|
|
|
|
def read_credentials(db: Session, employee_id: str) -> dict:
|
|
account = _require(db, employee_id)
|
|
payload = {
|
|
"password": decrypt_secret(account.password_cipher) if account.password_cipher else "",
|
|
"ucs_token": "",
|
|
"ucs_account_id": "",
|
|
"ucs_user_id": "",
|
|
"ucs_ssoinfo": "",
|
|
"ucs_union_id": "",
|
|
"yxt_token": "",
|
|
}
|
|
if not account.credential_cipher:
|
|
payload["detail"] = "尚未完成登录或已注销"
|
|
return payload
|
|
stored = json.loads(decrypt_secret(account.credential_cipher))
|
|
for key in _TOKEN_KEYS:
|
|
payload[key] = str(stored.get(key) or "")
|
|
return payload
|
|
|
|
|
|
def delete_user(db: Session, employee_id: str) -> dict:
|
|
account = _require(db, employee_id)
|
|
db.delete(account)
|
|
db.commit()
|
|
return {"ok": True}
|