# -*- coding: utf-8 -*- """成员停用 → 吊销他名下全部 TDB key(2026-11-07)。 为什么是吊销 key,不是停用账号: TDB 没有「在职/离职」这回事。它的鉴权只认两样东西 —— key 的状态和过期时间, 而且每个请求都实时验(MemoryProxy 不缓存验证结果)。所以对 TDB 来说, 「这个人还在不在」等价于「他手里的 key 还能不能用」。 为什么不直接调 user-key/revoke: 内核的 revoke 会拒绝撤销「最后一个有效 key」(否则用户手里一把能用的都不剩)。 而离职场景恰恰是要把他所有 key 都废掉,所以统一改 expires_at 到过去 —— 鉴权每次都查这个字段,效果等同吊销,且不会撞上那条保护。 恢复: 成员重新启用后,下次取 key 时 tdb_provision 会发现本地缓存已清,自动重开一把新的。 失效是即时的,恢复也是自动的。 审计: key 记录本身不删(只改过期时间),谁什么时候被停用、废了几把,都留得住。 """ import time PAST = "2020-01-01T00:00:00.000Z" def revoke_member_keys(uid): """吊销某成员全部有效 key。返回 {ok, revoked, user_id} 或 {ok:False, err}。""" if not uid: return {"ok": False, "err": "缺少成员 uid"} try: import sources.tdb_provision as TP except Exception as e: return {"ok": False, "err": "模块不可用:%s" % str(e)[:80]} if not TP._conf(): return {"ok": False, "err": "团队 AI 未配置(tdb_admin.json 缺失)"} conn = None try: conn = TP._local_cache() cached = TP._cache_get(conn, uid) or {} user_id = cached.get("user_id") or "" # 缓存里没有这个人 → 按成员姓名去 TDB 找 if not user_id: import sources.members_store as M name = (M.find(uid) or {}).get("name") or "" if not name: return {"ok": True, "revoked": 0, "note": "成员不存在"} listing = TP._core("POST", "/v3/meta/user/list", {"page": 1, "page_size": 200}) for u in listing.get("items") or []: if u.get("username") == name: user_id = u.get("user_id") or "" break if not user_id: return {"ok": True, "revoked": 0, "note": "该成员还没有 TDB 账号,无需吊销"} keys = TP._core("POST", "/v3/meta/user-key/list", {"user_id": user_id}) items = keys.get("items") or [] revoked = 0 failed = [] for k in items: if (k or {}).get("status") != "active": continue kid = k.get("key_id") if not kid: continue try: TP._core("POST", "/v3/meta/user-key/update", {"key_id": kid, "expires_at": PAST}) revoked += 1 except Exception as e: failed.append("%s: %s" % (kid, str(e)[:60])) # 清本地缓存:不清的话,取 key 接口 24 小时内还会把旧 key 递出去 if conn: try: conn.execute("DELETE FROM accounts WHERE uid=?", (uid,)) conn.commit() except Exception: pass out = {"ok": True, "revoked": revoked, "user_id": user_id, "at": time.strftime("%Y-%m-%d %H:%M")} if failed: out["failed"] = failed[:5] return out except Exception as e: return {"ok": False, "err": str(e)[:140]} finally: if conn: try: conn.close() except Exception: pass def revoke_status(uid): """只读:看某成员名下 key 的现状(给管理页用,不动数据)。""" try: import sources.tdb_provision as TP conn = TP._local_cache() cached = TP._cache_get(conn, uid) or {} user_id = cached.get("user_id") or "" if conn: try: conn.close() except Exception: pass if not user_id: return {"ok": True, "user_id": "", "keys": []} listing = TP._core("POST", "/v3/meta/user-key/list", {"user_id": user_id}) rows = [] for k in listing.get("items") or []: rows.append({ "key_id": k.get("key_id"), "prefix": k.get("key_prefix"), "status": k.get("status"), "expires_at": k.get("expires_at"), "last_used_at": k.get("last_used_at"), }) return {"ok": True, "user_id": user_id, "keys": rows} except Exception as e: return {"ok": False, "err": str(e)[:120]}