Files
37duAutomation/libs/dingtalk/dingtalk_sdk/auth.py
T
puddy 9873eb1963 restore: 恢复 11-06~11-09 本地未提交改动
- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto
- controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图
- electron-shell: 插件同步、注册表、runner 调整
- plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新
- tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
2026-11-09 17:27:10 +08:00

125 lines
4.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""企业内部应用 access_token 获取与进程内缓存。
两套接口各有一个 token 端点,SDK 统一封装:
- ``v1`` :``POST https://api.dingtalk.com/v1.0/oauth2/accessToken``(AI 表格等新版接口)
- ``oapi`` :``GET https://oapi.dingtalk.com/gettoken``(媒体上传等旧版接口)
token 有 2 小时 TTL,缓存到「过期前 2 分钟」自动刷新;多实例按 (kind, appKey) 共享。
"""
from __future__ import annotations
import threading
import time
from typing import Dict, Optional, Tuple
from .config import get_settings
from .errors import ApiError, AuthError
from .http import API_BASE, OAPI_BASE, HttpClient, install_dns_fallback
KIND_V1 = "v1"
KIND_OAPI = "oapi"
#: 提前刷新窗口(秒)
EXPIRY_MARGIN = 120
_LOCK = threading.RLock()
_CACHE: Dict[Tuple[str, str], Tuple[str, float]] = {}
class AccessToken:
"""单个 (kind, appKey) 的 token 提供者。
Args:
kind: ``"v1"``(默认)或 ``"oapi"``
app_key/app_secret: 缺省读配置(``DINGTALK_APP_KEY`` / ``DINGTALK_APP_SECRET``)
timeout: HTTP 超时秒
"""
def __init__(self, kind: str = KIND_V1, app_key: str = "", app_secret: str = "",
timeout: Optional[float] = None) -> None:
kind = (kind or KIND_V1).strip().lower()
if kind not in (KIND_V1, KIND_OAPI):
raise ValueError(f"未知 token 类型「{kind}」,仅支持 v1 / oapi")
self.kind = kind
self.timeout = timeout
key, secret = app_key.strip(), app_secret.strip()
if not key or not secret:
cfg_key, cfg_secret = get_settings().require_app_credentials()
key = key or cfg_key
secret = secret or cfg_secret
self.app_key, self.app_secret = key, secret
# ---- 公开 ----
def get(self, force: bool = False) -> str:
"""取 token(命中缓存则直接返回)。"""
cache_key = (self.kind, self.app_key)
now = time.time()
if not force:
with _LOCK:
hit = _CACHE.get(cache_key)
if hit and hit[1] > now:
return hit[0]
value, ttl = self._fetch()
with _LOCK:
_CACHE[cache_key] = (value, now + max(ttl - EXPIRY_MARGIN, 60))
return value
def invalidate(self) -> None:
with _LOCK:
_CACHE.pop((self.kind, self.app_key), None)
# ---- 内部 ----
def _fetch(self) -> Tuple[str, int]:
install_dns_fallback()
client = HttpClient(timeout=self.timeout, retries=1)
try:
if self.kind == KIND_V1:
data = client.request(
"POST", f"{API_BASE}/oauth2/accessToken",
body={"appKey": self.app_key, "appSecret": self.app_secret})
tok = data.get("accessToken") or ""
ttl = int(data.get("expireIn") or 7200)
if not tok:
raise AuthError(f"获取钉钉 accessToken 失败:{data}")
return tok, ttl
data = client.request(
"GET", f"{OAPI_BASE}/gettoken",
params={"appkey": self.app_key, "appsecret": self.app_secret})
tok = data.get("access_token") or ""
if not tok:
msg = data.get("errmsg") or data
raise AuthError(f"获取钉钉 access_token 失败:{msg}")
return tok, int(data.get("expires_in") or 7200)
finally:
client.close()
def token(kind: str = KIND_V1) -> str:
"""取默认凭证的 access_token。"""
return AccessToken(kind=kind).get()
def invalidate(kind: str = "") -> None:
"""清空 token 缓存(``kind`` 为空则全清)。"""
with _LOCK:
if not kind:
_CACHE.clear()
return
for key in [k for k in _CACHE if k[0] == kind]:
_CACHE.pop(key, None)
__all__ = [
"EXPIRY_MARGIN",
"KIND_OAPI",
"KIND_V1",
"AccessToken",
"AuthError",
"ApiError",
"invalidate",
"token",
]