66 lines
2.8 KiB
Python
66 lines
2.8 KiB
Python
"""auth_oauth 身份源插件 — 第三方授权登录示例(基于 chongming-auth 共享契约)。
|
||
|
||
演示 auth 域拆分后的身份源插件标准形态:
|
||
- 准入判断归插件(GitHub OAuth 授权码模式 / 手机验证码模式)
|
||
- 平台凭证签发归 chongming_auth.issue_token(claims 契约与内置登录完全一致)
|
||
- 账号落地到共享 users 表,第三方身份与账号的映射存插件自有绑定表
|
||
(identity_bindings,建在同一 auth 库,不改动 chongming-auth 拥有的 users schema)
|
||
|
||
演示模式说明:
|
||
- 手机验证码默认直接随响应返回 dev_code(无短信通道的本地演示用),
|
||
生产必须接真实短信通道并关闭 return_otp_in_response
|
||
- GitHub OAuth 需在 [workers.config.github] 配置 client_id/secret/redirect_uri
|
||
"""
|
||
import logging
|
||
|
||
from chongming_worker.plugin import Plugin
|
||
|
||
from .router import * # noqa: F401,F403 触发 @rpc_method 注册
|
||
|
||
# 模块加载时即注册 SQLModel 元数据(identity_bindings 表与 users 同库,
|
||
# 由 chongming_auth.open_database 的 create_all 一并创建)
|
||
from .models import IdentityBinding # noqa: F401
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
class AuthOAuthPlugin(Plugin):
|
||
"""AuthOAuth 插件 — 身份源示例,统一生命周期。"""
|
||
|
||
type = "auth_oauth"
|
||
# 不用基类建库:与网关内置登录共用同一 auth 库(chongming_auth.open_database
|
||
# 按 [workers.config] 的 data_dir / database 解析,指向 users + identity_bindings)
|
||
db_name = None
|
||
auto_bind = False # 请求/响应模型由端点函数的类型注解直接提供,无需 gen_models
|
||
|
||
async def on_init(self):
|
||
"""首次 create_workers 时调用一次:打开共享 auth 库 + 缓存。"""
|
||
from chongming_auth import open_database
|
||
from chongming_cache import Cache
|
||
from chongming_config import get_config
|
||
|
||
db = await open_database(self.config)
|
||
cache = Cache.from_config(get_config()["cache"])
|
||
|
||
# 写入全局变量供 router 使用(cleanup 时统一释放)
|
||
self.set_var("db", db)
|
||
self.set_var("cache", cache)
|
||
self.set_var("plugin_config", dict(self.config or {}))
|
||
logger.info("[auth_oauth] 初始化完成(共享 auth 库 + 缓存就绪)")
|
||
|
||
async def on_cleanup(self):
|
||
"""cleanup 时调用:释放自有资源(基类不再托管本插件的数据库)。"""
|
||
db = self.get_var("db")
|
||
cache = self.get_var("cache")
|
||
if db is not None:
|
||
await db.dispose()
|
||
if cache is not None:
|
||
cache.close()
|
||
logger.info("[auth_oauth] 清理完成")
|
||
|
||
|
||
# 暴露给 app lifespan 的模块级入口(bound method,签名与旧写法完全一致)
|
||
plugin = AuthOAuthPlugin()
|
||
create_workers = plugin.create_workers
|
||
cleanup = plugin.cleanup
|