user_tokens
feishu.auth.user_tokens
¶
用户态访问凭证的持久化与按需刷新:把「以用户身份执行」做成一个标准接缝。
feishu.auth.oauth.OAuthNamespace 已封装授权 URL、exchange_code、refresh、user_info 等线缆调用,但
不负责「持久化每个用户的 user_access_token / refresh_token 并在临近过期时自动刷新」。本模块补上这一层:
feishu.auth.user_tokens.OAuthTokenStore 抽象按用户多别名(open_id/union_id/user_id)存取凭证,
feishu.auth.user_tokens.UserTokenProvider 据此解析并刷新凭证、产出用户态客户端(client.as_user(token))。
其 as_user(user) 正好契合 feishu.agent.context.ToolContext 所需的提供方接口,可直接传给
feishu.agent.loop.Agent 的 user_tokens 参数。
TokenRecord
dataclass
¶
一个用户的凭证记录:用户态访问令牌、(轮换式)刷新令牌、各项过期时间与多别名键。
飞书的 refresh_token 为一次性轮换:每次刷新都会得到全新的刷新令牌,旧令牌随即失效,因此刷新后必须
整体覆盖保存本记录。
示例:
| Python Console Session | |
|---|---|
源代码位于: feishu/auth/user_tokens.py
is_expiring
¶
is_expired
¶
from_token_data
classmethod
¶
from_token_data(token_data: Mapping[str, Any], keys: tuple[str, ...], *, now: int) -> TokenRecord
从 exchange_code / refresh 的响应构造记录(expires_in 等折算为绝对过期时间)。
源代码位于: feishu/auth/user_tokens.py
OAuthTokenStore
¶
Bases: Protocol
用户态凭证存储协议:按用户多别名存取 feishu.auth.user_tokens.TokenRecord。
内置实现为 feishu.auth.user_tokens.InMemoryOAuthTokenStore 与
feishu.auth.user_tokens.SqliteOAuthTokenStore。该协议标注了 runtime_checkable。
源代码位于: feishu/auth/user_tokens.py
InMemoryOAuthTokenStore
¶
基于内存的 feishu.auth.user_tokens.OAuthTokenStore 实现,仅适用于单进程、可接受重启即丢失的场景。
示例:
源代码位于: feishu/auth/user_tokens.py
SqliteOAuthTokenStore
¶
基于 SQLite 的 feishu.auth.user_tokens.OAuthTokenStore 实现,用户态凭证跨重启存活。
同一用户的每个别名键写入一行、指向同一份记录 JSON,从而 open_id / union_id / user_id 任一皆可命中。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
|
str | Path
|
SQLite 数据库文件路径。 |
必需 |
示例:
| Python Console Session | |
|---|---|
源代码位于: feishu/auth/user_tokens.py
UserTokenProvider
¶
解析并按需刷新用户态凭证,产出用户态飞书客户端。
as_user(user) 正是 feishu.agent.context.ToolContext 所需的提供方接口:传给
feishu.agent.loop.Agent 的 user_tokens 后,工具即可以请求用户的身份执行读写。访问令牌将在临近过期
(refresh_skew_seconds)时用一次性轮换的 refresh_token 刷新并整体覆盖保存。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
|
Any
|
飞书客户端,需提供 |
必需 |
|
OAuthTokenStore
|
必需 | |
|
int
|
提前刷新的余量秒数。默认为 |
60
|
|
Logger | None
|
日志器。 |
None
|
源代码位于: feishu/auth/user_tokens.py
user_token
async
¶
解析有效的用户态访问令牌;临近过期则刷新;无记录或已失效返回 None。
源代码位于: feishu/auth/user_tokens.py
as_user
async
¶
complete_authorization
async
¶
完成 OAuth 回调:用 code 换取凭证、读取用户信息并保存,返回写入的别名键。
源代码位于: feishu/auth/user_tokens.py
user_identity_keys
¶
把用户标识映射归一为稳定、**带类型前缀**的多别名键(如 open_id:ou_x)——全库唯一的用户身份键表示。
前缀(open_id: / union_id: / user_id:)避免不同 ID 类型的裸值互相碰撞。用于按用户隔离 token / 分享
文件 / 收款账户等存储,以及把审批绑定到发起人。逆操作见 feishu.auth.user_tokens.user_from_identity_keys。
源代码位于: feishu/auth/user_tokens.py
user_from_identity_keys
¶
feishu.auth.user_tokens.user_identity_keys 的逆:把带前缀的身份键还原为 {kind: value} 用户标识映射。
源代码位于: feishu/auth/user_tokens.py
user_keys
¶
用户的稳定多别名键;feishu.auth.user_tokens.user_identity_keys 的别名(全库统一表示)。