Files
37duAutomation/controlplane/core/dingtalk.py
T
puddy cb04790d28 refactor: 重构项目目录结构与代码组织
1.  重构controlplane与webhost后端的包结构,按领域拆分模块到core/apis子包
2.  移动并整理工具脚本到tools子目录,统一管理运维脚本
3.  重构插件运行时、调度、作业管理等核心模块到core子包
4.  更新AGENTS.md文档,明确各代码形态的组织规范
5.  清理重复的旧文件与冗余代码
2026-09-14 12:34:54 +08:00

145 lines
6.7 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 -*-
"""中心机钉钉官方接口封装:OAuth 扫码换身份 + 内嵌二维码(DDLogin)+ 工号解析。
与 webhost 扫码登录共用一套凭证语义:DINGTALK_APP_KEY/SECRET 即可完成
扫码换 unionid/昵称 → gettoken 企业内部 token → getbyunionid 取 userid → v2/user/get 取工号。
"""
from __future__ import annotations
import json
import time
from urllib.request import Request, urlopen
from fastapi import HTTPException
from controlplane.core import config
def _dingtalk_get_json(url: str, headers: dict | None = None) -> dict:
req = Request(url, method="GET")
for k, v in (headers or {}).items():
req.add_header(k, v)
try:
with urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode("utf-8"))
except OSError as _e:
raise HTTPException(502, f"钉钉接口访问失败:{getattr(_e, 'reason', _e)}")
def _dingtalk_post_json(url: str, payload: dict) -> dict:
req = Request(url, data=json.dumps(payload).encode("utf-8"), method="POST")
req.add_header("Content-Type", "application/json")
try:
with urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode("utf-8"))
except OSError as _e:
raise HTTPException(502, f"钉钉接口访问失败:{getattr(_e, 'reason', _e)}")
# 企业内部 token 缓存(gettoken 的 access_token 有 TTL,缓存到临近过期)
_DINGTALK_TOPAPI = {"at": "", "exp": 0.0}
def _dingtalk_topapi_token() -> str:
"""获取企业内部应用 access_token(取工号链路用)。复用 DINGTALK_APP_KEY/SECRET。"""
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
return ""
now = time.time()
if _DINGTALK_TOPAPI["at"] and _DINGTALK_TOPAPI["exp"] > now + 60:
return _DINGTALK_TOPAPI["at"]
try:
info = _dingtalk_get_json(
"https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s"
% (config.DINGTALK_APP_KEY, config.DINGTALK_APP_SECRET))
at = info.get("access_token", "")
if not at:
return ""
_DINGTALK_TOPAPI["at"] = at
_DINGTALK_TOPAPI["exp"] = now + int(info.get("expires_in", 7200))
return at
except Exception: # noqa: BLE001 取企业内部 token 失败不阻断扫码登录
return ""
def _dingtalk_userinfo(auth_code: str) -> dict:
"""用钉钉扫码回调的 authCode 换取当前钉钉用户工号/姓名/unionid。"""
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
# Step1: authCode -> accessToken -> unionid + nick
tok = _dingtalk_post_json(
"https://api.dingtalk.com/v1.0/oauth2/userAccessToken",
{"clientId": config.DINGTALK_APP_KEY, "clientSecret": config.DINGTALK_APP_SECRET,
"code": auth_code, "grantType": "authorization_code"})
at = tok.get("accessToken")
if not at:
raise HTTPException(401, "钉钉授权码无效或已过期,请重新扫码")
me = _dingtalk_get_json(
"https://api.dingtalk.com/v1.0/contact/users/me",
{"x-acs-dingtalk-access-token": at})
unionid = me.get("unionId") or me.get("unionid") or ""
nickname = me.get("nick") or ""
account = me.get("jobNumber") or me.get("userId") or unionid
# Step2/3: (可选)企业内部 token -> getbyunionid(userid) -> v2/user/get(job_number)
top_at = _dingtalk_topapi_token()
if top_at and unionid:
try:
byunion = _dingtalk_post_json(
"https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s" % top_at,
{"unionid": unionid})
ures = byunion.get("result") or {}
userid = ures.get("userid") or ures.get("userId") or ""
if userid:
ud = _dingtalk_post_json(
"https://oapi.dingtalk.com/topapi/v2/user/get?access_token=%s" % top_at,
{"userid": userid})
res = ud.get("result") or {}
job = res.get("job_number") or res.get("jobNumber") or ""
nickname = nickname or res.get("name") or ""
account = job or userid or account
except Exception: # noqa: BLE001 取工号失败不阻断登录,回退已得字段
pass
return {"account": account, "nickname": nickname, "unionid": unionid}
def _dingtalk_sns_userinfo(login_tmp_code: str) -> dict:
"""内嵌二维码扫码(钉钉 DDLogin):loginTmpCode → sns unionid/nick → 企业内部取工号。
与 _dingtalk_userinfo 的区别仅在于换码入口:OAuth 用 userAccessToken(code),
内嵌二维码用 sns/gettoken + sns/getuserinfo_bycode(loginTmpCode)。取工号链路共用。
"""
if not config.DINGTALK_APP_KEY or not config.DINGTALK_APP_SECRET:
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY / DINGTALK_APP_SECRET)")
# Step1: loginTmpCode -> sns access_token
tok = _dingtalk_get_json(
"https://oapi.dingtalk.com/sns/gettoken?access_key=%s&access_secret=%s"
% (config.DINGTALK_APP_KEY, config.DINGTALK_APP_SECRET))
at = tok.get("access_token")
if not at:
raise HTTPException(401, "钉钉扫码码无效或已过期,请重新扫码")
# Step2: sns access_token -> unionid + nick
info = _dingtalk_post_json(
"https://oapi.dingtalk.com/sns/getuserinfo_bycode?access_token=%s" % at,
{"tmp_auth_code": login_tmp_code})
ui = info.get("user_info") or info.get("userInfo") or info
unionid = ui.get("unionid") or ui.get("unionId") or ""
nickname = ui.get("nick") or ""
# Step3: (可选)企业内部 token -> getbyunionid(userid) -> v2/user/get(job_number)
account = unionid
top_at = _dingtalk_topapi_token()
if top_at and unionid:
try:
byunion = _dingtalk_post_json(
"https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s" % top_at,
{"unionid": unionid})
ures = byunion.get("result") or {}
userid = ures.get("userid") or ures.get("userId") or ""
if userid:
ud = _dingtalk_post_json(
"https://oapi.dingtalk.com/topapi/v2/user/get?access_token=%s" % top_at,
{"userid": userid})
res = ud.get("result") or {}
job = res.get("job_number") or res.get("jobNumber") or ""
account = job or userid or account
except Exception: # noqa: BLE001 取工号失败不阻断,回退已得字段
pass
return {"account": account, "nickname": nickname, "unionid": unionid}