优化了一些问题

This commit is contained in:
2026-08-29 22:03:48 +08:00
parent 1d904e6532
commit 780e1eba21
46 changed files with 4074 additions and 3143 deletions
+98 -126
View File
@@ -279,132 +279,104 @@ class SchemaUsers {
]],
],
],
'oauth' => [
'key' => 'oauth',
'title' => '第三方登录',
'version' => '1.0.0',
'option_key' => 'aksrt_settings',
'groups' => [
['key' => 'basic', 'title' => '基础设置', 'fields' => [
['key' => 'oauth_s', 'label' => '启用第三方登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_proxy_mode', 'label' => '代理登录模式', 'type' => 'radio', 'default' => 'close', 'options' => [
['label' => '关闭', 'value' => 'close'],
['label' => '服务端', 'value' => 'server'],
['label' => '客户端', 'value' => 'client'],
]],
['key' => 'oauth_proxy_secret', 'label' => '代理 HMAC 密钥', 'type' => 'input', 'default' => '', 'dependsOn' => ['key' => 'oauth_proxy_mode', 'not' => 'close']],
['key' => 'oauth_proxy_server_url', 'label' => '服务端地址', 'type' => 'input', 'default' => '', 'dependsOn' => ['key' => 'oauth_proxy_mode', 'value' => 'client']],
['key' => 'oauth_proxy_server_providers', 'label' => '服务端允许平台', 'type' => 'checkbox', 'default' => ['github', 'gitee', 'qq', 'google'], 'options' => [
['label' => 'GitHub', 'value' => 'github'],
['label' => 'Gitee', 'value' => 'gitee'],
['label' => 'QQ', 'value' => 'qq'],
['label' => 'Google', 'value' => 'google'],
['label' => '微博', 'value' => 'weibo'],
['label' => '微信', 'value' => 'weixin'],
['label' => '百度', 'value' => 'baidu'],
['label' => '支付宝', 'value' => 'alipay'],
], 'dependsOn' => ['key' => 'oauth_proxy_mode', 'value' => 'server']],
['key' => 'oauth_proxy_client_providers', 'label' => '客户端启用平台', 'type' => 'checkbox', 'default' => ['github', 'gitee', 'qq', 'google'], 'options' => [
['label' => 'GitHub', 'value' => 'github'],
['label' => 'Gitee', 'value' => 'gitee'],
['label' => 'QQ', 'value' => 'qq'],
['label' => 'Google', 'value' => 'google'],
['label' => '微博', 'value' => 'weibo'],
['label' => '微信', 'value' => 'weixin'],
['label' => '百度', 'value' => 'baidu'],
['label' => '支付宝', 'value' => 'alipay'],
], 'dependsOn' => ['key' => 'oauth_proxy_mode', 'value' => 'client']],
['key' => 'oauth_proxy_gzh_type', 'label' => '代理公众号类型', 'type' => 'radio', 'default' => 'service', 'options' => [
['label' => '服务号', 'value' => 'service'],
['label' => '订阅号', 'value' => 'subscribe'],
], 'dependsOn' => ['key' => 'oauth_proxy_mode', 'not' => 'close']],
['key' => 'oauth_bind_type', 'label' => '绑定方式', 'type' => 'radio', 'default' => 'auto', 'options' => [
['label' => '自动绑定', 'value' => 'auto'],
['label' => '手动绑定', 'value' => 'manual'],
]],
['key' => 'oauth_button_lg', 'label' => '大按钮样式', 'type' => 'switch', 'default' => false],
['key' => 'weixingzh_priority', 'label' => 'PC端优先微信扫码', 'type' => 'switch', 'default' => false, 'help' => '开启后 PC 端登录框优先显示微信公众号扫码'],
['key' => 'weixingzh_auto', 'label' => '微信APP内自动登录', 'type' => 'switch', 'default' => false, 'help' => '在微信内置浏览器中自动使用公众号授权登录'],
['key' => 'weixingzh_auto_expires', 'label' => '自动登录频率限制 (秒)', 'type' => 'number', 'default' => 3600, 'min' => 0, 'max' => 86400, 'dependsOn' => ['key' => 'weixingzh_auto', 'value' => true]],
]],
['key' => 'providers', 'title' => '登录提供商', 'fields' => [
['key' => 'oauth_github_s', 'label' => 'GitHub登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_gitee_s', 'label' => 'Gitee登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_qq_s', 'label' => 'QQ登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_weixingzh_s', 'label' => '微信公众号登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_weixin_s', 'label' => '微信开放平台登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_weibo_s', 'label' => '微博登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_baidu_s', 'label' => '百度登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_alipay_s', 'label' => '支付宝登录', 'type' => 'switch', 'default' => false],
['key' => 'clogin_s', 'label' => '彩虹聚合登录', 'type' => 'switch', 'default' => false],
]],
['key' => 'github', 'title' => 'GitHub配置', 'fields' => [
['key' => 'github_appid', 'label' => 'Client ID', 'type' => 'input', 'default' => ''],
['key' => 'github_appkey', 'label' => 'Client Secret', 'type' => 'input', 'default' => ''],
]],
['key' => 'gitee', 'title' => 'Gitee配置', 'fields' => [
['key' => 'gitee_appid', 'label' => 'Client ID', 'type' => 'input', 'default' => ''],
['key' => 'gitee_appkey', 'label' => 'Client Secret', 'type' => 'input', 'default' => ''],
]],
['key' => 'qq', 'title' => 'QQ配置', 'fields' => [
['key' => 'qq_appid', 'label' => 'App ID', 'type' => 'input', 'default' => ''],
['key' => 'qq_appkey', 'label' => 'App Key', 'type' => 'input', 'default' => ''],
]],
['key' => 'weixin', 'title' => '微信开放平台配置', 'fields' => [
['key' => 'weixin_appid', 'label' => 'AppID', 'type' => 'input', 'default' => ''],
['key' => 'weixin_appsecret', 'label' => 'AppSecret', 'type' => 'input', 'default' => ''],
]],
['key' => 'weixingzh', 'title' => '微信公众号配置', 'fields' => [
['key' => 'weixingzh_gzh_type', 'label' => '公众号类型', 'type' => 'radio', 'default' => 'service', 'options' => [
['label' => '服务号', 'value' => 'service'],
['label' => '订阅号', 'value' => 'subscribe'],
]],
['key' => 'weixingzh_token', 'label' => 'Token', 'type' => 'input', 'default' => ''],
['key' => 'weixingzh_token_nocheck', 'label' => '不验证Token', 'type' => 'switch', 'default' => false, 'help' => '开发调试时可跳过 Token 验证'],
['key' => 'weixingzh_encoding_aes_key', 'label' => 'EncodingAESKey', 'type' => 'input', 'default' => ''],
['key' => 'weixingzh_appid', 'label' => 'AppID', 'type' => 'input', 'default' => ''],
['key' => 'weixingzh_appsecret', 'label' => 'AppSecret', 'type' => 'input', 'default' => ''],
['key' => 'weixingzh_code_qrcode', 'label' => '公众号二维码', 'type' => 'media', 'default' => '', 'help' => '引导用户扫码关注登录的二维码图片'],
['key' => 'weixingzh_code_keyword', 'label' => '登录回复关键词', 'type' => 'input', 'default' => '登录', 'help' => '用户在公众号内回复此关键词触发登录验证码'],
['key' => 'weixingzh_code_reply', 'label' => '验证码回复模板', 'type' => 'textarea', 'default' => '您的验证码是:%s,有效期 %d 分钟。', 'help' => '%s=验证码,%d=有效分钟数'],
['key' => 'weixingzh_code_subscribe_reply', 'label' => '新关注回复模板', 'type' => 'textarea', 'default' => '欢迎关注!回复「%s」获取登录验证码。', 'help' => '%s=登录关键词'],
['key' => 'weixingzh_subscribe_msg', 'label' => '关注后回复', 'type' => 'textarea', 'default' => '', 'help' => '用户关注公众号后的自动回复文案'],
['key' => 'weixingzh_new_subscribe_msg', 'label' => '新用户关注回复', 'type' => 'textarea', 'default' => '', 'help' => '首次关注用户的专属回复文案,留空使用通用回复'],
['key' => 'weixingzh_scan_msg', 'label' => '扫码回复', 'type' => 'textarea', 'default' => '', 'help' => '用户扫码关注公众号后的回复文案'],
['key' => 'weixingzh_auto_reply_text', 'label' => '文本自动回复', 'type' => 'textarea', 'default' => '', 'help' => '收到文本消息的自动回复'],
['key' => 'weixingzh_auto_reply_search', 'label' => '搜索回复', 'type' => 'textarea', 'default' => '', 'help' => '未匹配关键词时的搜索提示回复'],
['key' => 'weixingzh_auto_reply_image', 'label' => '图片回复', 'type' => 'textarea', 'default' => '', 'help' => '收到图片消息的自动回复'],
['key' => 'weixingzh_auto_reply_voice', 'label' => '语音回复', 'type' => 'textarea', 'default' => '', 'help' => '收到语音消息的自动回复'],
['key' => 'weixingzh_auto_reply_default', 'label' => '默认回复', 'type' => 'textarea', 'default' => '暂不支持此类型的消息', 'help' => '其他未匹配消息类型的兜底回复'],
['key' => 'weixingzh_gzh_menu', 'label' => '自定义菜单 JSON', 'type' => 'textarea', 'default' => '', 'help' => '微信公众号自定义菜单 JSON 配置,留空不创建菜单'],
]],
['key' => 'weibo', 'title' => '微博配置', 'fields' => [
['key' => 'weibo_appid', 'label' => 'App Key', 'type' => 'input', 'default' => ''],
['key' => 'weibo_appkey', 'label' => 'App Secret', 'type' => 'input', 'default' => ''],
]],
['key' => 'baidu', 'title' => '百度配置', 'fields' => [
['key' => 'baidu_appid', 'label' => 'API Key', 'type' => 'input', 'default' => ''],
['key' => 'baidu_appkey', 'label' => 'Secret Key', 'type' => 'input', 'default' => ''],
]],
['key' => 'clogin', 'title' => '彩虹聚合登录', 'fields' => [
['key' => 'clogin_url', 'label' => '接口地址', 'type' => 'input', 'default' => '', 'dependsOn' => ['key' => 'clogin_s', 'value' => true], 'help' => '如 https://xxx.com'],
['key' => 'clogin_id', 'label' => 'AppID', 'type' => 'input', 'default' => '', 'dependsOn' => ['key' => 'clogin_s', 'value' => true]],
['key' => 'clogin_key', 'label' => 'AppKey', 'type' => 'input', 'default' => '', 'dependsOn' => ['key' => 'clogin_s', 'value' => true]],
['key' => 'clogin_oauth_s', 'label' => '启用平台', 'type' => 'checkbox', 'default' => ['qq', 'weixin', 'weibo', 'alipay'], 'options' => [
['label' => 'QQ', 'value' => 'qq'],
['label' => '微信', 'value' => 'weixin'],
['label' => '微博', 'value' => 'weibo'],
['label' => '支付宝', 'value' => 'alipay'],
['label' => '百度', 'value' => 'baidu'],
], 'dependsOn' => ['key' => 'clogin_s', 'value' => true]],
]],
['key' => 'alipay', 'title' => '支付宝配置', 'fields' => [
['key' => 'alipay_appid', 'label' => 'AppID', 'type' => 'input', 'default' => ''],
['key' => 'alipay_privatekey', 'label' => '应用私钥', 'type' => 'textarea', 'sanitize_type' => 'code', 'default' => ''],
['key' => 'alipay_publickey', 'label' => '支付宝公钥', 'type' => 'input', 'default' => ''],
]],
],
],
'oauth' => [
'key' => 'oauth',
'title' => '第三方登录',
'version' => '1.0.0',
'option_key' => 'aksrt_settings',
'groups' => [
['key' => 'basic', 'title' => '基础设置', 'fields' => [
['key' => 'oauth_s', 'label' => '启用第三方登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_proxy_mode', 'label' => '代理登录模式', 'type' => 'radio', 'default' => 'close', 'options' => [
['label' => '关闭', 'value' => 'close'],
['label' => '服务端', 'value' => 'server'],
['label' => '客户端', 'value' => 'client'],
]],
['key' => 'oauth_proxy_secret', 'label' => '代理 HMAC 密钥', 'type' => 'input', 'inputType' => 'password', 'secret' => true, 'default' => '', 'dependsOn' => ['key' => 'oauth_proxy_mode', 'not' => 'close']],
['key' => 'oauth_proxy_server_url', 'label' => '服务端地址', 'type' => 'input', 'sanitize_type' => 'url', 'default' => '', 'dependsOn' => ['key' => 'oauth_proxy_mode', 'value' => 'client']],
['key' => 'oauth_proxy_server_providers', 'label' => '服务端允许平台', 'type' => 'checkbox', 'default' => ['github', 'gitee', 'qq', 'google'], 'options' => [
['label' => 'GitHub', 'value' => 'github'],
['label' => 'Gitee', 'value' => 'gitee'],
['label' => 'QQ', 'value' => 'qq'],
['label' => 'Google', 'value' => 'google'],
['label' => '微博', 'value' => 'weibo'],
['label' => '微信', 'value' => 'weixin'],
], 'dependsOn' => ['key' => 'oauth_proxy_mode', 'value' => 'server']],
['key' => 'oauth_proxy_client_providers', 'label' => '客户端启用平台', 'type' => 'checkbox', 'default' => ['github', 'gitee', 'qq', 'google'], 'options' => [
['label' => 'GitHub', 'value' => 'github'],
['label' => 'Gitee', 'value' => 'gitee'],
['label' => 'QQ', 'value' => 'qq'],
['label' => 'Google', 'value' => 'google'],
['label' => '微博', 'value' => 'weibo'],
['label' => '微信', 'value' => 'weixin'],
], 'dependsOn' => ['key' => 'oauth_proxy_mode', 'value' => 'client']],
['key' => 'oauth_bind_type', 'label' => '绑定方式', 'type' => 'radio', 'default' => 'auto', 'options' => [
['label' => '自动绑定', 'value' => 'auto'],
['label' => '手动绑定', 'value' => 'manual'],
]],
['key' => 'oauth_button_lg', 'label' => '大按钮样式', 'type' => 'switch', 'default' => false],
['key' => 'weixingzh_priority', 'label' => 'PC端优先微信扫码', 'type' => 'switch', 'default' => false, 'help' => '开启后 PC 端登录框优先显示微信公众号扫码'],
]],
['key' => 'providers', 'title' => '登录提供商', 'fields' => [
['key' => 'oauth_github_s', 'label' => 'GitHub登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_gitee_s', 'label' => 'Gitee登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_qq_s', 'label' => 'QQ登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_google_s', 'label' => 'Google登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_weibo_s', 'label' => '微博登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_weixin_s', 'label' => '微信开放平台登录', 'type' => 'switch', 'default' => false],
['key' => 'oauth_weixingzh_s', 'label' => '微信公众号登录', 'type' => 'switch', 'default' => false],
['key' => 'clogin_s', 'label' => '彩虹聚合登录', 'type' => 'switch', 'default' => false],
]],
['key' => 'github', 'title' => 'GitHub配置', 'fields' => [
['key' => 'github_appid', 'label' => 'Client ID', 'type' => 'input', 'default' => ''],
['key' => 'github_appkey', 'label' => 'Client Secret', 'type' => 'input', 'inputType' => 'password', 'secret' => true, 'default' => ''],
]],
['key' => 'gitee', 'title' => 'Gitee配置', 'fields' => [
['key' => 'gitee_appid', 'label' => 'Client ID', 'type' => 'input', 'default' => ''],
['key' => 'gitee_appkey', 'label' => 'Client Secret', 'type' => 'input', 'inputType' => 'password', 'secret' => true, 'default' => ''],
]],
['key' => 'qq', 'title' => 'QQ配置', 'fields' => [
['key' => 'qq_appid', 'label' => 'App ID', 'type' => 'input', 'default' => ''],
['key' => 'qq_appkey', 'label' => 'App Key', 'type' => 'input', 'inputType' => 'password', 'secret' => true, 'default' => ''],
]],
['key' => 'google', 'title' => 'Google配置', 'fields' => [
['key' => 'google_client_id', 'label' => 'Client ID', 'type' => 'input', 'default' => ''],
['key' => 'google_client_secret', 'label' => 'Client Secret', 'type' => 'input', 'inputType' => 'password', 'secret' => true, 'default' => ''],
]],
['key' => 'weibo', 'title' => '微博配置', 'fields' => [
['key' => 'weibo_appid', 'label' => 'App Key', 'type' => 'input', 'default' => ''],
['key' => 'weibo_appkey', 'label' => 'App Secret', 'type' => 'input', 'inputType' => 'password', 'secret' => true, 'default' => ''],
]],
['key' => 'weixin', 'title' => '微信开放平台配置', 'fields' => [
['key' => 'weixin_appid', 'label' => 'AppID', 'type' => 'input', 'default' => ''],
['key' => 'weixin_appsecret', 'label' => 'AppSecret', 'type' => 'input', 'inputType' => 'password', 'secret' => true, 'default' => ''],
]],
['key' => 'weixingzh', 'title' => '微信公众号配置', 'fields' => [
['key' => 'weixingzh_gzh_type', 'label' => '公众号类型', 'type' => 'radio', 'default' => 'service', 'options' => [
['label' => '服务号', 'value' => 'service'],
['label' => '订阅号', 'value' => 'subscribe'],
]],
['key' => 'weixingzh_token', 'label' => 'Token', 'type' => 'input', 'inputType' => 'password', 'secret' => true, 'default' => ''],
['key' => 'weixingzh_appid', 'label' => 'AppID', 'type' => 'input', 'default' => ''],
['key' => 'weixingzh_appsecret', 'label' => 'AppSecret', 'type' => 'input', 'inputType' => 'password', 'secret' => true, 'default' => ''],
['key' => 'weixingzh_code_qrcode', 'label' => '公众号二维码', 'type' => 'media', 'default' => '', 'help' => '引导用户扫码关注登录的二维码图片'],
['key' => 'weixingzh_code_keyword', 'label' => '登录回复关键词', 'type' => 'input', 'default' => '登录', 'help' => '用户在公众号内回复此关键词触发登录验证码'],
['key' => 'weixingzh_code_reply', 'label' => '验证码回复模板', 'type' => 'textarea', 'default' => '您的验证码是:%s,有效期 %d 分钟。', 'help' => '%s=验证码,%d=有效分钟数'],
['key' => 'weixingzh_subscribe_msg', 'label' => '关注后回复', 'type' => 'textarea', 'default' => '', 'help' => '用户关注公众号后的自动回复文案'],
['key' => 'weixingzh_scan_msg', 'label' => '扫码回复', 'type' => 'textarea', 'default' => '', 'help' => '用户扫码关注公众号后的回复文案'],
]],
['key' => 'clogin', 'title' => '彩虹聚合登录', 'fields' => [
['key' => 'clogin_url', 'label' => '接口地址', 'type' => 'input', 'sanitize_type' => 'url', 'default' => '', 'dependsOn' => ['key' => 'clogin_s', 'value' => true], 'help' => '如 https://xxx.com,不要带 connect.php'],
['key' => 'clogin_id', 'label' => 'AppID', 'type' => 'input', 'default' => '', 'dependsOn' => ['key' => 'clogin_s', 'value' => true]],
['key' => 'clogin_key', 'label' => 'AppKey', 'type' => 'input', 'inputType' => 'password', 'secret' => true, 'default' => '', 'dependsOn' => ['key' => 'clogin_s', 'value' => true]],
['key' => 'clogin_oauth_s', 'label' => '启用平台', 'type' => 'checkbox', 'default' => ['qq', 'weixin', 'weibo'], 'options' => [
['label' => 'QQ', 'value' => 'qq'],
['label' => '微信', 'value' => 'weixin'],
['label' => '微博', 'value' => 'weibo'],
], 'dependsOn' => ['key' => 'clogin_s', 'value' => true]],
]],
],
],
'sms' => [
'key' => 'sms',
'title' => '短信接口',
+188 -10
View File
@@ -139,6 +139,12 @@ class SchemaProvider {
$clean[$key] = $this->sanitize_field_value($data[$key], $field);
}
}
if (!empty($data['__clear_secrets']) && is_array($data['__clear_secrets'])) {
$clean['__clear_secrets'] = array_values(array_intersect(
array_map('sanitize_key', $data['__clear_secrets']),
$this->secret_field_keys($schema)
));
}
return $clean;
}
@@ -266,6 +272,15 @@ class SchemaProvider {
}
}
if ($domain === 'users' && ($section === 'oauth' || $section === '')) {
$stored = get_option('aksrt_settings', []);
$merged = is_array($stored) ? array_merge($stored, $data) : $data;
foreach ((array) ($data['__clear_secrets'] ?? []) as $secret_key) {
$merged[sanitize_key((string) $secret_key)] = '';
}
$errors = array_merge($errors, $this->validate_oauth_settings($merged, is_array($stored) ? $stored : []));
}
if ($domain === 'payment' && $section === 'withdrawal') {
$stored = get_option('aksrt_settings', []);
$merged = is_array($stored) ? array_merge($stored, $data) : $data;
@@ -307,6 +322,132 @@ class SchemaProvider {
return ['valid' => empty($errors), 'errors' => $errors];
}
private function validate_oauth_settings(array $settings, array $stored = []): array {
if (empty($settings['oauth_s'])) {
return [];
}
$errors = [];
$mode = sanitize_key((string) ($settings['oauth_proxy_mode'] ?? 'close'));
$secret_configured = $this->oauth_secret_is_configured($settings['oauth_proxy_secret'] ?? '', $stored['oauth_proxy_secret'] ?? '');
if ($mode === 'client') {
$url = trim((string) ($settings['oauth_proxy_server_url'] ?? ''));
if (!$this->is_secure_oauth_url($url)) {
$errors[] = __('客户端代理模式需要有效的 HTTPS 服务端地址', 'aksrt');
}
if (!$secret_configured) {
$errors[] = __('客户端代理模式需要代理 HMAC 密钥', 'aksrt');
}
if (empty($settings['oauth_proxy_client_providers']) || !is_array($settings['oauth_proxy_client_providers'])) {
$errors[] = __('客户端代理模式至少需要启用一个登录平台', 'aksrt');
}
return $errors;
}
if ($mode === 'server') {
if (!$secret_configured) {
$errors[] = __('服务端代理模式需要代理 HMAC 密钥', 'aksrt');
}
$selected = is_array($settings['oauth_proxy_server_providers'] ?? null) ? $settings['oauth_proxy_server_providers'] : [];
if ($selected === []) {
$errors[] = __('服务端代理模式至少需要允许一个登录平台', 'aksrt');
}
$provider_fields = [
'github' => ['GitHub', 'github_appid', 'github_appkey'],
'gitee' => ['Gitee', 'gitee_appid', 'gitee_appkey'],
'qq' => ['QQ', 'qq_appid', 'qq_appkey'],
'google' => ['Google', 'google_client_id', 'google_client_secret'],
'weibo' => ['微博', 'weibo_appid', 'weibo_appkey'],
'weixin' => ['微信开放平台', 'weixin_appid', 'weixin_appsecret'],
];
foreach ($selected as $provider) {
if (!isset($provider_fields[$provider])) {
continue;
}
[$label, $id_key, $secret_key] = $provider_fields[$provider];
if (trim((string) ($settings[$id_key] ?? '')) === '' || !$this->oauth_secret_is_configured($settings[$secret_key] ?? '', $stored[$secret_key] ?? '')) {
$errors[] = sprintf(__('代理服务端的 %s 平台缺少完整凭据', 'aksrt'), $label);
}
}
return $errors;
}
$providers = [
'github' => ['GitHub', 'github_appid', 'github_appkey'],
'gitee' => ['Gitee', 'gitee_appid', 'gitee_appkey'],
'qq' => ['QQ', 'qq_appid', 'qq_appkey'],
'google' => ['Google', 'google_client_id', 'google_client_secret'],
'weibo' => ['微博', 'weibo_appid', 'weibo_appkey'],
'weixin' => ['微信开放平台', 'weixin_appid', 'weixin_appsecret'],
];
$enabled = 0;
foreach ($providers as $provider => [$label, $id_key, $secret_key]) {
if (empty($settings['oauth_' . $provider . '_s'])) {
continue;
}
$enabled++;
if (trim((string) ($settings[$id_key] ?? '')) === '' || !$this->oauth_secret_is_configured($settings[$secret_key] ?? '', $stored[$secret_key] ?? '')) {
$errors[] = sprintf(__('%s 登录已启用,请填写完整凭据', 'aksrt'), $label);
}
}
if (!empty($settings['oauth_weixingzh_s'])) {
$enabled++;
$gzh_type = sanitize_key((string) ($settings['weixingzh_gzh_type'] ?? 'service'));
$base_ready = $this->oauth_secret_is_configured($settings['weixingzh_token'] ?? '', $stored['weixingzh_token'] ?? '')
&& trim((string) ($settings['weixingzh_appid'] ?? '')) !== '';
$mode_ready = $gzh_type === 'subscribe'
? trim((string) ($settings['weixingzh_code_qrcode'] ?? '')) !== ''
&& trim((string) ($settings['weixingzh_code_keyword'] ?? '')) !== ''
: $this->oauth_secret_is_configured($settings['weixingzh_appsecret'] ?? '', $stored['weixingzh_appsecret'] ?? '');
if (!$base_ready || !$mode_ready) {
$errors[] = $gzh_type === 'subscribe'
? __('微信公众号订阅号登录已启用,请填写 Token、AppID、二维码和回复关键词', 'aksrt')
: __('微信公众号服务号登录已启用,请填写 Token、AppID 和 AppSecret', 'aksrt');
}
}
if (!empty($settings['clogin_s'])) {
$enabled++;
if (!$this->is_secure_oauth_url((string) ($settings['clogin_url'] ?? ''))
|| trim((string) ($settings['clogin_id'] ?? '')) === ''
|| !$this->oauth_secret_is_configured($settings['clogin_key'] ?? '', $stored['clogin_key'] ?? '')
|| empty($settings['clogin_oauth_s'])
) {
$errors[] = __('彩虹聚合登录已启用,请填写 HTTPS 接口地址、AppID、AppKey 并选择平台', 'aksrt');
}
}
if ($enabled === 0) {
$errors[] = __('启用第三方登录后,至少需要启用一个本地登录提供商', 'aksrt');
}
return $errors;
}
private function oauth_secret_is_configured($value, $stored_value = ''): bool {
$value = trim((string) $value);
if ($value === '***') {
return trim((string) $stored_value) !== '';
}
return $value !== '';
}
private function is_secure_oauth_url(string $url): bool {
$url = trim($url);
if ($url === '' || filter_var($url, FILTER_VALIDATE_URL) === false) {
return false;
}
$parts = wp_parse_url($url);
return is_array($parts)
&& strtolower((string) ($parts['scheme'] ?? '')) === 'https'
&& !empty($parts['host'])
&& empty($parts['user'])
&& empty($parts['pass'])
&& empty($parts['fragment']);
}
/**
* Top-level slugs that must never be shadowed by the download route.
*/
@@ -360,13 +501,22 @@ class SchemaProvider {
return $result;
}
public function reset_to_defaults(string $domain, string $section = ''): bool {
if ($section !== '') {
return $this->write_settings($domain, $this->get_defaults($domain, $section), $section);
}
public function reset_to_defaults(string $domain, string $section = ''): bool {
if ($section !== '') {
$defaults = $this->get_defaults($domain, $section);
$schema = $this->get_section_schema($domain, $section);
$defaults['__clear_secrets'] = $schema ? $this->secret_field_keys($schema) : [];
return $this->write_settings($domain, $defaults, $section);
}
return $this->write_settings($domain, $this->get_defaults($domain));
}
$result = true;
foreach ($this->get_sections($domain) as $section_schema) {
$defaults = $this->collect_defaults($section_schema);
$defaults['__clear_secrets'] = $this->secret_field_keys($section_schema);
$result = $this->write_section_settings($section_schema, $defaults) && $result;
}
return $result;
}
private function get_schema_builder_map(): array {
// Builders live under AKSRT\Admin\Schema (Composer PSR-4). Relative
@@ -395,6 +545,10 @@ class SchemaProvider {
if (array_key_exists($field['key'], $stored)) {
$data[$field['key']] = $stored[$field['key']];
}
$stored_value = array_key_exists($field['key'], $stored) ? $stored[$field['key']] : ($data[$field['key']] ?? '');
if (!empty($field['secret'])) {
$data[$field['key']] = trim((string) $stored_value) !== '' ? '***' : '';
}
}
// Captcha: always surface the normalized positive scene list.
@@ -421,13 +575,27 @@ class SchemaProvider {
foreach ($this->get_all_fields($schema) as $field) {
$fields[(string) $field['key']] = $field;
}
$clear_secrets = isset($data['__clear_secrets']) && is_array($data['__clear_secrets'])
? array_values(array_map('sanitize_key', $data['__clear_secrets']))
: [];
foreach ($fields as $key => $field) {
if (!array_key_exists($key, $data)) {
continue;
}
if (!empty($field['secret']) && in_array($key, $clear_secrets, true)) {
unset($stored[$key]);
continue;
}
if (!array_key_exists($key, $data)) {
continue;
}
if (!empty($field['secret'])) {
$value = is_scalar($data[$key]) ? trim((string) $data[$key]) : '';
if ($value === '' || $value === '***') {
continue;
}
}
$stored[$key] = $this->sanitize_field_value($data[$key], $field);
}
}
// Captcha stores a single positive scene list.
if ($option_key === 'aksrt_captcha_config' && function_exists('aksrt_captcha_scenes')) {
@@ -449,6 +617,16 @@ class SchemaProvider {
return $updated || true;
}
private function secret_field_keys(array $schema): array {
$keys = [];
foreach ($this->get_all_fields($schema) as $field) {
if (!empty($field['secret']) && !empty($field['key'])) {
$keys[] = sanitize_key((string) $field['key']);
}
}
return array_values(array_unique($keys));
}
private function collect_defaults(array $schema): array {
$defaults = [];
foreach ($this->get_all_fields($schema) as $field) {
-67
View File
@@ -31,20 +31,6 @@ class UserController extends ControllerBase {
'permission_callback' => [$this, 'check_permission'],
]);
// OAuth settings
register_rest_route(self::API_NAMESPACE, '/settings/oauth', [
'methods' => ['GET', 'POST'],
'callback' => [$this, 'rest_handle_oauth'],
'permission_callback' => [$this, 'check_permission'],
]);
// OAuth proxy settings
register_rest_route(self::API_NAMESPACE, '/settings/oauth-proxy', [
'methods' => ['GET', 'POST'],
'callback' => [$this, 'rest_handle_oauth_proxy'],
'permission_callback' => [$this, 'check_permission'],
]);
// User profile media uploads (logged-in users).
register_rest_route(self::API_NAMESPACE, '/user/background', [
'methods' => 'POST',
@@ -531,59 +517,6 @@ class UserController extends ControllerBase {
return $this->success(['message' => __('消息清理任务已受理', 'aksrt')]);
}
public function rest_handle_oauth(\WP_REST_Request $request): \WP_REST_Response {
$provider = SchemaProvider::get_instance();
$allowed = $provider->get_allowed_fields('users', 'oauth');
if ($request->get_method() === 'GET') {
$data = \AKSRT\Settings\Settings::get_all();
return $this->success(['data' => array_intersect_key($data, $allowed)]);
}
$params = $this->get_json_params($request);
$settings = \AKSRT\Settings\Settings::get_all();
$settings = array_merge($settings, $this->sanitize_fields($params, $allowed));
update_option('aksrt_settings', $settings);
\AKSRT\Settings\Settings::flush_settings_cache();
return $this->success(['message' => __('第三方登录配置已保存', 'aksrt')]);
}
public function rest_handle_oauth_proxy(\WP_REST_Request $request): \WP_REST_Response {
$keys = [
'oauth_proxy_mode',
'oauth_proxy_secret',
'oauth_proxy_server_url',
'oauth_proxy_server_providers',
'oauth_proxy_client_providers',
'oauth_proxy_gzh_type',
];
if ($request->get_method() === 'GET') {
$all = \AKSRT\Settings\Settings::get_all();
$data = [];
foreach ($keys as $key) {
$data[$key] = $all[$key] ?? null;
}
return $this->success(['data' => $data]);
}
$params = $this->get_json_params($request);
$settings = \AKSRT\Settings\Settings::get_all();
foreach ($keys as $key) {
if (!array_key_exists($key, $params)) {
continue;
}
$settings[$key] = is_array($params[$key])
? array_values(array_map('sanitize_key', (array) $params[$key]))
: sanitize_text_field((string) $params[$key]);
}
update_option('aksrt_settings', $settings);
\AKSRT\Settings\Settings::flush_settings_cache();
return $this->success(['message' => __('OAuth 代理配置已保存', 'aksrt')]);
}
public function rest_upload_comment_image(\WP_REST_Request $request): \WP_REST_Response {
$user_id = get_current_user_id();
if ($user_id <= 0) {
+66 -15
View File
@@ -11,6 +11,14 @@ defined('ABSPATH') || exit;
trait UserControllerAuthPhoneOperations {
private function delete_oauth_registration_user(int $user_id): void {
if ($user_id <= 0) {
return;
}
require_once ABSPATH . 'wp-admin/includes/user.php';
wp_delete_user($user_id);
}
private function auth_payload(\WP_REST_Request $request): array {
$params = $this->get_json_params($request);
return is_array($params) ? $params : [];
@@ -220,14 +228,23 @@ trait UserControllerAuthPhoneOperations {
if (!$user || !$this->auth_consume_code('login', $target, sanitize_text_field((string) $payload['code']), $channel)) {
return $this->error(__('账号或验证码错误', 'aksrt'), 401);
}
if ($oauth_data) {
$oauth_data = \AKSRT\Auth\Service::claim_oauth_bind_context($obk);
if (!$oauth_data) {
return $this->error(__('绑定会话已被使用,请重新授权', 'aksrt'), 410);
}
$binding = \AKSRT\Auth\Service::finalize_oauth_binding((int) $user->ID, $oauth_data, $obk);
if (is_wp_error($binding)) {
return $this->error($binding->get_error_message(), 409);
}
\AKSRT\Auth\OAuthAccountService::complete_login($user, !empty($payload['rememberme']));
$redirect = function_exists('aksrt_get_user_center_url') ? aksrt_get_user_center_url() : $redirect;
return $this->success(['message' => __('账号绑定成功', 'aksrt'), 'redirect' => $redirect]);
}
wp_set_current_user((int) $user->ID);
wp_set_auth_cookie((int) $user->ID, !empty($payload['rememberme']));
do_action('wp_login', $user->user_login, $user);
if ($oauth_data) {
\AKSRT\Auth\Service::finalize_oauth_binding((int) $user->ID, $oauth_data, $obk);
$redirect = function_exists('aksrt_get_user_center_url') ? aksrt_get_user_center_url() : $redirect;
}
return $this->success(['message' => $oauth_data ? __('账号绑定成功', 'aksrt') : __('登录成功', 'aksrt'), 'redirect' => $redirect]);
return $this->success(['message' => __('登录成功', 'aksrt'), 'redirect' => $redirect]);
}
if (!class_exists('\AKSRT\Auth\Service')) {
@@ -236,17 +253,27 @@ trait UserControllerAuthPhoneOperations {
$payload['log'] = $target;
$payload['pwd'] = (string) ($payload['password'] ?? $payload['pwd'] ?? '');
$payload['redirect_to'] = $redirect;
$result = \AKSRT\Auth\Service::login_user($payload, $oauth_data ? 'bind' : 'login');
if (empty($result['success'])) {
return $this->error(__('账号或密码错误', 'aksrt'), 401);
}
if ($oauth_data) {
$user_id = get_current_user_id();
if ($user_id <= 0) {
$resolved_login = \AKSRT\Auth\Service::resolve_email_to_username($target);
$user = wp_authenticate($resolved_login, (string) ($payload['password'] ?? $payload['pwd'] ?? ''));
if (is_wp_error($user) || !$user instanceof \WP_User) {
return $this->error(__('账号或密码错误', 'aksrt'), 401);
}
\AKSRT\Auth\Service::finalize_oauth_binding($user_id, $oauth_data, $obk);
$oauth_data = \AKSRT\Auth\Service::claim_oauth_bind_context($obk);
if (!$oauth_data) {
return $this->error(__('绑定会话已被使用,请重新授权', 'aksrt'), 410);
}
$binding = \AKSRT\Auth\Service::finalize_oauth_binding((int) $user->ID, $oauth_data, $obk);
if (is_wp_error($binding)) {
return $this->error($binding->get_error_message(), 409);
}
\AKSRT\Auth\OAuthAccountService::complete_login($user, !empty($payload['rememberme']));
$redirect = function_exists('aksrt_get_user_center_url') ? aksrt_get_user_center_url() : $redirect;
return $this->success(['message' => __('账号绑定成功', 'aksrt'), 'redirect' => $redirect]);
}
$result = \AKSRT\Auth\Service::login_user($payload, 'login');
if (empty($result['success'])) {
return $this->error(__('账号或密码错误', 'aksrt'), 401);
}
return $this->success(['message' => $oauth_data ? __('账号绑定成功', 'aksrt') : __('登录成功', 'aksrt'), 'redirect' => $redirect]);
}
@@ -263,7 +290,10 @@ trait UserControllerAuthPhoneOperations {
if ($obk !== '' && !$oauth_data) {
return $this->error(__('绑定会话已过期,请重新使用第三方登录', 'aksrt'), 410);
}
if (class_exists('\AKSRT\Settings\Settings') && (\AKSRT\Settings\Settings::close_sign() || (!$oauth_data && !\AKSRT\Settings\Settings::registration_enabled()))) {
if (class_exists('\AKSRT\Settings\Settings') && (
\AKSRT\Settings\Settings::close_sign()
|| ($oauth_data ? !\AKSRT\Settings\Settings::oauth_registration_enabled() : !\AKSRT\Settings\Settings::registration_enabled())
)) {
return $this->error(__('当前已关闭新用户注册', 'aksrt'), 403);
}
if ($this->auth_rate_limited('register')) {
@@ -296,26 +326,47 @@ trait UserControllerAuthPhoneOperations {
}
if ($channel === 'phone') {
$payload['phone'] = $target;
$payload['_defer_login'] = !empty($oauth_data);
$result = \AKSRT\Auth\Service::register_by_phone($payload);
if (empty($result['success'])) {
return $this->error($this->auth_registration_error((string) ($result['error'] ?? __('注册失败', 'aksrt'))));
}
$user_id = (int) ($result['user_id'] ?? 0);
if ($oauth_data && $user_id > 0) {
\AKSRT\Auth\Service::finalize_oauth_binding($user_id, $oauth_data, $obk);
$binding = \AKSRT\Auth\Service::finalize_oauth_binding($user_id, $oauth_data, $obk);
if (is_wp_error($binding)) {
$this->delete_oauth_registration_user($user_id);
return $this->error($binding->get_error_message(), 409);
}
$user = get_user_by('id', $user_id);
if ($user instanceof \WP_User) {
\AKSRT\Auth\OAuthAccountService::complete_login($user, true);
}
}
return $this->success(['message' => $oauth_data ? __('注册并绑定成功', 'aksrt') : __('注册成功', 'aksrt'), 'redirect' => $result['redirect'] ?? home_url('/'), 'notice' => (string) ($result['notice'] ?? '')]);
}
$payload['user_email'] = sanitize_email($target);
$payload['user_pass'] = (string) ($payload['password'] ?? '');
$payload['user_pass_confirm'] = (string) ($payload['password_confirm'] ?? $payload['password'] ?? '');
$payload['_defer_login'] = !empty($oauth_data);
$result = \AKSRT\Auth\Service::register_user($payload);
if (empty($result['success'])) {
return $this->error($this->auth_registration_error((string) ($result['error'] ?? __('注册失败', 'aksrt'))));
}
$user_id = (int) ($result['user_id'] ?? 0);
if ($oauth_data && $user_id > 0) {
\AKSRT\Auth\Service::finalize_oauth_binding($user_id, $oauth_data, $obk);
$binding = \AKSRT\Auth\Service::finalize_oauth_binding($user_id, $oauth_data, $obk);
if (is_wp_error($binding)) {
wp_delete_user($user_id);
return $this->error($binding->get_error_message(), 409);
}
$user = get_user_by('id', $user_id);
if ($user instanceof \WP_User) {
if ($channel === 'email' && !empty($payload['_auth_code_verified'])) {
\AKSRT\Auth\Service::mark_verified_email($user_id);
}
\AKSRT\Auth\OAuthAccountService::complete_login($user, true);
}
}
return $this->success([
'message' => $oauth_data ? __('注册并绑定成功', 'aksrt') : __('注册成功', 'aksrt'),
+42 -45
View File
@@ -1,6 +1,6 @@
<?php
/**
* CaiHong / rainbow aggregate OAuth client (legacy clogin parity).
* CaiHong aggregate OAuth client.
*
* @package AKSRT
*/
@@ -9,56 +9,51 @@ namespace AKSRT\Auth;
defined('ABSPATH') || exit;
class CLoginClient {
final class CLoginClient {
private string $apiurl;
private string $appid;
private string $appkey;
private string $callback;
public string $state = '';
/**
* @param array{apiurl:string,appid:string,appkey:string,callback?:string} $config
*/
public function __construct(array $config) {
$this->apiurl = rtrim((string) ($config['apiurl'] ?? ''), '/') . '/connect.php';
$this->appid = (string) ($config['appid'] ?? '');
$this->appkey = (string) ($config['appkey'] ?? '');
$base = OAuthUrlPolicy::public_https((string) ($config['apiurl'] ?? ''));
$this->apiurl = $base !== '' ? rtrim($base, '/') . '/connect.php' : '';
$this->appid = trim((string) ($config['appid'] ?? ''));
$this->appkey = trim((string) ($config['appkey'] ?? ''));
$this->callback = (string) ($config['callback'] ?? '');
}
/**
* @return array<string,mixed>
*/
public function login(string $type): array {
$this->state = md5(uniqid((string) wp_rand(), true));
$params = [
'act' => 'login',
'appid' => $this->appid,
'appkey' => $this->appkey,
'type' => $this->to_api_type($type),
public function login(string $type, string $state): array {
$type = sanitize_key($type);
if (!in_array($type, ['qq', 'weixin', 'weibo'], true) || $state === '') {
return ['code' => 1, 'msg' => __('聚合登录参数无效', 'aksrt')];
}
return $this->request([
'act' => 'login',
'appid' => $this->appid,
'appkey' => $this->appkey,
'type' => $this->to_api_type($type),
'redirect_uri' => $this->callback,
'state' => $this->state,
];
return $this->request($params);
'state' => $state,
], true);
}
/**
* @return array<string,mixed>
*/
public function callback(string $code): array {
return $this->request([
'act' => 'callback',
'appid' => $this->appid,
'act' => 'callback',
'appid' => $this->appid,
'appkey' => $this->appkey,
'code' => $code,
'code' => $code,
]);
}
public function to_api_type(string $type): string {
switch (sanitize_key($type)) {
case 'weixin':
case 'wechat':
return 'wx';
case 'weibo':
return 'sina';
@@ -78,29 +73,31 @@ class CLoginClient {
}
}
/**
* @param array<string,string> $params
* @return array<string,mixed>
*/
private function request(array $params): array {
private function request(array $params, bool $expect_url = false): array {
if ($this->apiurl === '' || $this->appid === '' || $this->appkey === '') {
return ['code' => 1, 'msg' => __('聚合登录配置无效', 'aksrt')];
}
$url = $this->apiurl . '?' . http_build_query($params);
$response = wp_remote_get($url, [
$response = wp_safe_remote_get($url, [
'timeout' => 15,
'headers' => [
'User-Agent' => 'AKSRT-CLogin/1.0',
],
'redirects' => 1,
'limit_response_size' => 256 * 1024,
'headers' => ['User-Agent' => 'AKSRT-CLogin/2.0'],
]);
if (is_wp_error($response)) {
return [
'code' => 1,
'msg' => $response->get_error_message(),
];
return ['code' => 1, 'msg' => $response->get_error_message()];
}
$body = (string) wp_remote_retrieve_body($response);
$data = json_decode($body, true);
return is_array($data) ? $data : [
'code' => 1,
'msg' => __('聚合登录接口返回异常', 'aksrt'),
];
$status = (int) wp_remote_retrieve_response_code($response);
if ($status < 200 || $status >= 300) {
return ['code' => 1, 'msg' => __('聚合登录接口请求失败', 'aksrt')];
}
$data = json_decode((string) wp_remote_retrieve_body($response), true);
if (!is_array($data)) {
return ['code' => 1, 'msg' => __('聚合登录接口返回异常', 'aksrt')];
}
if ($expect_url && empty($data['code']) && OAuthUrlPolicy::public_https((string) ($data['url'] ?? '')) === '') {
return ['code' => 1, 'msg' => __('聚合登录返回地址无效', 'aksrt')];
}
return $data;
}
}
+374 -414
View File
@@ -7,418 +7,378 @@ namespace AKSRT\Auth;
defined('ABSPATH') || exit;
class OAuth {
use OAuthPart1;
use OAuthPart2;
private static $instance = null;
private function __construct() {}
public static function get_instance(): self {
if (null === self::$instance) self::$instance = new self();
return self::$instance;
}
public function init(): void {
add_action('init', [$this, 'add_rewrite_rules']);
add_action('template_redirect', [$this, 'handle_callback']);
add_action('template_redirect', [$this, 'handle_clogin_routes'], 9);
add_action('show_user_profile', [$this, 'profile_bindings'], 10, 1);
add_action('wp_ajax_aksrt_oauth_unbind', [$this, 'ajax_unbind']);
}
public function add_rewrite_rules(): void {
add_rewrite_rule('^oauth/callback/?$', 'index.php?aksrt_oauth=callback', 'top');
add_rewrite_rule('^oauth/clogin/?$', 'index.php?aksrt_oauth=clogin', 'top');
add_rewrite_rule('^oauth/clogin/callback/?$', 'index.php?aksrt_oauth=clogin_callback', 'top');
add_filter('query_vars', function($vars) {
$vars[] = 'aksrt_oauth';
return $vars;
});
}
/**
* 生成OAuth授权URL
*/
public function get_auth_url(string $provider, string $action = 'login'): string {
$provider = sanitize_key($provider);
if (str_starts_with($provider, 'clogin_') || str_starts_with($provider, 'clogin-')) {
$type = str_replace(['clogin_', 'clogin-'], '', $provider);
return $this->get_clogin_login_url($type, $action);
}
if ($provider === 'clogin') {
return $this->get_clogin_login_url('qq', $action);
}
if (class_exists('\AKSRT\Settings\Settings') && \AKSRT\Settings\Settings::oauth_proxy_mode() === 'client') {
if (class_exists('AKSRT\\Auth\\OAuthProxyClient')) {
return OAuthProxyClient::get_instance()->get_proxy_auth_url($provider, $action);
}
return '';
}
$config = $this->get_provider_config($provider);
if (!$config) return '';
$uid = get_current_user_id();
$nonce = wp_create_nonce('aksrt_oauth_' . $provider . '_' . $uid);
$state = ($action === 'bind' && $uid)
? 'bind_' . $provider . '_' . $nonce
: $provider . '_' . $nonce;
$redirect_uri = !empty($config['redirect_uri']) ? $config['redirect_uri'] : home_url('/oauth/callback/');
try {
switch ($provider) {
case 'github':
$oauth = new \Yurun\OAuthLogin\Github\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'gitee':
$oauth = new \Yurun\OAuthLogin\Gitee\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'qq':
$oauth = new \Yurun\OAuthLogin\QQ\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'weibo':
$oauth = new \Yurun\OAuthLogin\Weibo\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'weixin':
$oauth = new \Yurun\OAuthLogin\Weixin\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'baidu':
$oauth = new \Yurun\OAuthLogin\Baidu\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'alipay':
$oauth = new \Yurun\OAuthLogin\Alipay\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
return $oauth->getAuthUrl($redirect_uri, $state);
case 'google':
return $this->get_google_auth_url($config, $redirect_uri, $state);
case 'weixingzh':
return $this->get_weixingzh_auth_url($config, $redirect_uri, $state);
default:
return '';
}
} catch (\Exception $e) {
return '';
}
}
/**
* 处理OAuth回调 — 路由分发
*/
public function handle_callback(): void {
$provider = $this->resolve_callback_provider();
if ($provider === '' || !in_array($provider, $this->get_enabled_providers())) return;
$error = $_GET['error'] ?? '';
if ($error) {
wp_die(__('登录失败:', 'aksrt') . esc_html($error));
}
$code = $_GET['code'] ?? '';
$state = $_GET['state'] ?? '';
if (empty($code)) {
wp_die(__('OAuth回调缺少授权码', 'aksrt'));
}
$is_bind = strpos($state, 'bind_') === 0;
$rest = $is_bind ? substr($state, 5) : $state;
$sep = strpos($rest, '_');
if ($sep === false || $sep >= strlen($rest) - 1) {
wp_die(__('无效的OAuth状态参数', 'aksrt'));
}
$parsed_provider = sanitize_key(substr($rest, 0, $sep));
if (!in_array($parsed_provider, $this->get_enabled_providers())) {
wp_die(__('未知的OAuth提供商', 'aksrt'));
}
$nonce_state = substr($rest, $sep + 1);
if ($is_bind) {
$this->handle_bind_callback($parsed_provider, $code, $nonce_state);
} else {
$this->handle_login_callback($parsed_provider, $code, $nonce_state);
}
}
private function handle_login_callback(string $provider, string $code, string $nonce): void {
try {
if (!wp_verify_nonce($nonce, "aksrt_oauth_{$provider}_0")) {
throw new \Exception(__('安全验证失败,请重试', 'aksrt'));
}
$user_data = $this->get_user_data($provider, $code);
if (!$user_data || empty($user_data['provider_id'])) {
throw new \Exception(__('无法获取用户信息', 'aksrt'));
}
$user = $this->find_or_create_user($provider, $user_data);
if (is_wp_error($user) && $user->get_error_code() === 'oauth_no_match') {
$error_data = $user->get_error_data();
$obk = 'aksrt_ob_' . wp_generate_password(24, false);
set_transient($obk, [
'provider' => $error_data['provider'],
'provider_id' => $error_data['user_data']['provider_id'] ?? '',
'user_data' => $error_data['user_data'],
], 15 * MINUTE_IN_SECONDS);
$bind_url = aksrt_get_bind_url();
wp_safe_redirect(add_query_arg('obk', $obk, $bind_url));
exit;
}
if (is_wp_error($user)) {
throw new \Exception($user->get_error_message());
}
wp_set_auth_cookie($user->ID, true);
$redirect_url = home_url('/');
if (function_exists('aksrt_get_user_center_url')) {
$redirect_url = aksrt_get_user_center_url();
}
wp_safe_redirect(add_query_arg(['oauth_action' => 'login', 'oauth_bound' => $provider], $redirect_url));
exit;
} catch (\Exception $e) {
wp_die(__('登录失败:', 'aksrt') . '<br>' . esc_html($e->getMessage()));
}
}
private function handle_bind_callback(string $provider, string $code, string $nonce): void {
$current_uid = get_current_user_id();
if (!$current_uid) {
wp_safe_redirect(aksrt_get_login_url());
exit;
}
try {
$expected = wp_create_nonce("aksrt_oauth_{$provider}_{$current_uid}");
if (!hash_equals($expected, $nonce)) {
throw new \Exception(__('安全验证失败,请重试', 'aksrt'));
}
$existing_binding = get_user_meta($current_uid, "aksrt_{$provider}_id", true);
if (!empty($existing_binding)) {
wp_safe_redirect(add_query_arg(['tab' => 'settings', 'oauth_action' => 'bind', 'oauth_bound' => $provider], $this->get_profile_url()));
exit;
}
$user_data = $this->get_user_data($provider, $code);
if (!$user_data || empty($user_data['provider_id'])) {
throw new \Exception(__('无法获取用户信息', 'aksrt'));
}
$existing = $this->find_user_by_provider($provider, $user_data['provider_id'] ?? '');
if ($existing && $existing->ID !== $current_uid) {
throw new \Exception(__('该第三方账号已被其他用户绑定', 'aksrt'));
}
$this->bind_provider_to_user($current_uid, $provider, $user_data);
wp_safe_redirect(add_query_arg(['tab' => 'settings', 'oauth_action' => 'bind', 'oauth_bound' => $provider], $this->get_profile_url()));
exit;
} catch (\Exception $e) {
wp_die(__('绑定失败:', 'aksrt') . '<br>' . esc_html($e->getMessage()));
}
}
/**
* 通过授权码获取用户数据(统一输出格式)
*/
private function get_user_data(string $provider, string $code): array {
$config = $this->get_provider_config($provider);
$redirect_uri = !empty($config['redirect_uri']) ? $config['redirect_uri'] : home_url('/oauth/callback/');
switch ($provider) {
case 'github':
return $this->get_github_user_data($config, $code, $redirect_uri);
case 'gitee':
return $this->get_gitee_user_data($config, $code, $redirect_uri);
case 'qq':
return $this->get_qq_user_data($config, $code, $redirect_uri);
case 'weibo':
return $this->get_weibo_user_data($config, $code, $redirect_uri);
case 'weixin':
return $this->get_weixin_user_data($config, $code, $redirect_uri);
case 'baidu':
return $this->get_baidu_user_data($config, $code, $redirect_uri);
case 'alipay':
return $this->get_alipay_user_data($config, $code, $redirect_uri);
case 'google':
return $this->get_google_user_data($config, $code, $redirect_uri);
case 'weixingzh':
return $this->get_weixingzh_user_data($config, $code, $redirect_uri);
default:
throw new \Exception(__('不支持的OAuth平台:', 'aksrt') . $provider);
}
}
private function get_github_user_data(array $config, string $code, string $redirect_uri): array {
$oauth = new \Yurun\OAuthLogin\Github\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$userInfo = $oauth->getUserInfo();
// 获取邮箱
$email = $userInfo['email'] ?? '';
if (empty($email)) {
$emails_json = $oauth->http->header('Authorization', ' token ' . $oauth->accessToken)
->get('https://api.github.com/user/emails')
->body();
$emails = json_decode($emails_json, true) ?: [];
foreach ($emails as $em) {
if (!empty($em['primary']) && !empty($em['email'])) {
$email = $em['email'];
break;
}
}
}
return [
'provider' => 'github',
'provider_id' => (string) ($userInfo['id'] ?? ''),
'username' => $userInfo['login'] ?? '',
'name' => $userInfo['name'] ?? '',
'email' => $email,
'avatar_url' => $userInfo['avatar_url'] ?? '',
'url' => $userInfo['html_url'] ?? '',
'bio' => $userInfo['bio'] ?? '',
];
}
private function get_gitee_user_data(array $config, string $code, string $redirect_uri): array {
$oauth = new \Yurun\OAuthLogin\Gitee\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$userInfo = $oauth->getUserInfo();
return [
'provider' => 'gitee',
'provider_id' => (string) ($userInfo['id'] ?? ''),
'username' => $userInfo['login'] ?? '',
'name' => $userInfo['name'] ?? '',
'email' => $userInfo['email'] ?? '',
'avatar_url' => $userInfo['avatar_url'] ?? '',
'url' => $userInfo['html_url'] ?? '',
'bio' => $userInfo['bio'] ?? '',
];
}
private function get_qq_user_data(array $config, string $code, string $redirect_uri): array {
$oauth = new \Yurun\OAuthLogin\QQ\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$openid = $oauth->getOpenID();
$userInfo = $oauth->getUserInfo();
return [
'provider' => 'qq',
'provider_id' => $openid,
'username' => $userInfo['nickname'] ?? '',
'name' => $userInfo['nickname'] ?? '',
'email' => '',
'avatar_url' => $userInfo['figureurl_qq_2'] ?? $userInfo['figureurl_2'] ?? $userInfo['figureurl'] ?? '',
'gender' => $userInfo['gender'] ?? '',
];
}
private function get_weibo_user_data(array $config, string $code, string $redirect_uri): array {
$oauth = new \Yurun\OAuthLogin\Weibo\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$userInfo = $oauth->getUserInfo();
return [
'provider' => 'weibo',
'provider_id' => (string) ($userInfo['id'] ?? ''),
'username' => $userInfo['screen_name'] ?? '',
'name' => $userInfo['name'] ?? '',
'email' => '',
'avatar_url' => $userInfo['avatar_large'] ?? $userInfo['profile_image_url'] ?? '',
'gender' => ($userInfo['gender'] ?? '') === 'm' ? 'male' : (($userInfo['gender'] ?? '') === 'f' ? 'female' : ''),
];
}
private function get_weixin_user_data(array $config, string $code, string $redirect_uri): array {
$oauth = new \Yurun\OAuthLogin\Weixin\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$userInfo = $oauth->getUserInfo();
return [
'provider' => 'weixin',
'provider_id' => (string) ($userInfo['openid'] ?? ''),
'username' => $userInfo['nickname'] ?? '',
'name' => $userInfo['nickname'] ?? '',
'email' => '',
'avatar_url' => $userInfo['headimgurl'] ?? '',
'gender' => ($userInfo['sex'] ?? 0) == 1 ? 'male' : (($userInfo['sex'] ?? 0) == 2 ? 'female' : ''),
];
}
final class OAuth {
private static $instance = null;
private OAuthProviderBroker $broker;
private function __construct() {
$this->broker = new OAuthProviderBroker();
}
public static function get_instance(): self {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public function init(): void {
add_action('init', [$this, 'add_rewrite_rules']);
add_action('init', [$this, 'maybe_flush_rewrite_rules'], 20);
add_action('init', static function (): void {
if (wp_rand(1, 100) === 1) {
OAuthTransactionStore::cleanup();
}
}, 30);
add_action('template_redirect', [$this, 'handle_routes'], 8);
add_action('wp_ajax_aksrt_oauth_unbind', [$this, 'ajax_unbind']);
}
public function add_rewrite_rules(): void {
add_rewrite_rule('^oauth/start/([a-z0-9_-]+)/?$', 'index.php?aksrt_oauth=start&aksrt_oauth_provider=$matches[1]', 'top');
add_rewrite_rule('^oauth/callback/?$', 'index.php?aksrt_oauth=callback', 'top');
add_rewrite_rule('^oauth/clogin/?$', 'index.php?aksrt_oauth=clogin', 'top');
add_rewrite_rule('^oauth/clogin/callback/?$', 'index.php?aksrt_oauth=clogin_callback', 'top');
add_filter('query_vars', static function (array $vars): array {
$vars[] = 'aksrt_oauth';
$vars[] = 'aksrt_oauth_provider';
return $vars;
});
}
public function maybe_flush_rewrite_rules(): void {
$version = defined('AKSRT_VERSION') ? AKSRT_VERSION . ':oauth-v2' : 'oauth-v2';
if (get_option('aksrt_oauth_routes_flushed') !== $version) {
flush_rewrite_rules(false);
update_option('aksrt_oauth_routes_flushed', $version, false);
}
}
public function handle_routes(): void {
$route = sanitize_key((string) get_query_var('aksrt_oauth'));
if ($route === '') {
return;
}
switch ($route) {
case 'start':
$this->handle_start();
break;
case 'callback':
$this->handle_callback();
break;
case 'clogin':
$this->handle_clogin_start();
break;
case 'clogin_callback':
$this->handle_clogin_callback();
break;
}
}
public function get_auth_url(string $provider, string $action = 'login'): string {
$provider = sanitize_key($provider);
$action = $action === 'bind' ? 'bind' : 'login';
if (!in_array($provider, OAuthProviderCatalog::enabled_login_keys(), true)) {
return '';
}
$redirect = isset($_GET['redirect_to'])
? OAuthUrlPolicy::validated_redirect((string) wp_unslash($_GET['redirect_to']), home_url('/'))
: '';
if ($provider === 'weixingzh') {
$url = function_exists('aksrt_get_sign_page_url') ? aksrt_get_sign_page_url('oauth') : home_url('/sign/?tab=oauth');
$url = add_query_arg('oauth_intent', $action, $url);
return $redirect !== '' ? add_query_arg('redirect_to', $redirect, $url) : $url;
}
if (str_starts_with($provider, 'clogin_')) {
$url = add_query_arg([
'type' => substr($provider, 7),
'action' => $action,
], home_url('/oauth/clogin/'));
return $redirect !== '' ? add_query_arg('redirect_to', $redirect, $url) : $url;
}
$url = add_query_arg('action', $action, home_url('/oauth/start/' . $provider . '/'));
return $redirect !== '' ? add_query_arg('redirect_to', $redirect, $url) : $url;
}
public function get_auth_providers_data(): array {
$result = [];
foreach (OAuthProviderCatalog::enabled_login_keys() as $provider) {
$url = $this->get_auth_url($provider);
if ($url === '') {
continue;
}
$result[] = [
'name' => $provider,
'label' => OAuthProviderCatalog::label($provider),
'icon' => function_exists('aksrt_brand_icon') ? aksrt_brand_icon(OAuthProviderCatalog::icon_key($provider)) : '',
'url' => esc_url($url),
];
}
return $result;
}
public function render_social_buttons(string $title = ''): string {
$items = $this->get_auth_providers_data();
if ($items === []) {
return '';
}
ob_start();
?>
<div class="social-login-divider">
<span><?php echo esc_html($title) ?: esc_html__('or', 'aksrt'); ?></span>
</div>
<div class="oauth-row">
<?php foreach ($items as $item) : ?>
<a href="<?php echo esc_url((string) $item['url']); ?>"
class="oauth-btn oauth-btn--<?php echo esc_attr((string) $item['name']); ?>"
data-provider="<?php echo esc_attr((string) $item['name']); ?>"
aria-label="<?php echo esc_attr((string) $item['label']); ?>"
title="<?php echo esc_attr((string) $item['label']); ?>">
<?php echo $item['icon']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
</a>
<?php endforeach; ?>
</div>
<?php
return (string) ob_get_clean();
}
public function get_frontend_bindings_data(int $user_id): array {
$bound = OAuthAccountService::bindings($user_id);
$bindings = [];
foreach ($bound as $provider) {
$bindings[] = $this->binding_row($provider, true);
}
$available = [];
foreach (OAuthProviderCatalog::enabled_login_keys() as $provider) {
if (in_array($provider, $bound, true)) {
continue;
}
$url = $this->get_auth_url($provider, 'bind');
if ($url !== '') {
$row = $this->binding_row($provider, false);
$row['url'] = $url;
$available[] = $row;
}
}
return ['bindings' => $bindings, 'available' => $available];
}
public function ajax_unbind(): void {
check_ajax_referer('aksrt_oauth_unbind', 'nonce');
$provider = sanitize_key((string) ($_POST['provider'] ?? ''));
$user_id = isset($_POST['userId']) ? (int) $_POST['userId'] : 0;
$current_id = get_current_user_id();
if ($current_id <= 0 || $current_id !== $user_id || !current_user_can('read')) {
wp_send_json_error(['message' => __('无权执行此操作', 'aksrt')], 403);
}
$result = OAuthAccountService::unbind($current_id, $provider);
if (is_wp_error($result)) {
$status = $result->get_error_code() === 'oauth_last_login_method' ? 409 : 400;
wp_send_json_error(['message' => $result->get_error_message()], $status);
}
wp_send_json_success(['unbound' => true, 'message' => __('解除绑定成功', 'aksrt')]);
}
private function handle_start(): void {
$provider = sanitize_key((string) get_query_var('aksrt_oauth_provider'));
$action = isset($_GET['action']) && sanitize_key((string) $_GET['action']) === 'bind' ? 'bind' : 'login';
if (!OAuthProviderCatalog::master_enabled() || !in_array($provider, OAuthProviderCatalog::enabled_login_keys(), true)) {
$this->redirect_error('provider_disabled', $provider, $action);
}
if (OAuthProviderCatalog::proxy_mode() === 'client') {
$url = OAuthProxyClient::get_instance()->get_proxy_auth_url($provider, $action);
if ($url === '') {
$this->redirect_error('proxy_config', $provider, $action);
}
wp_redirect($url); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
exit;
}
$user_id = get_current_user_id();
if ($action === 'bind' && $user_id <= 0) {
wp_safe_redirect(function_exists('aksrt_get_login_url') ? aksrt_get_login_url() : wp_login_url());
exit;
}
$redirect = isset($_GET['redirect_to']) ? OAuthUrlPolicy::validated_redirect((string) $_GET['redirect_to'], home_url('/')) : home_url('/');
$redirect_uri = home_url('/oauth/callback/');
try {
$state = OAuthTransactionStore::issue('direct', [
'provider' => $provider,
'action' => $action,
'user_id' => $user_id,
'redirect_to' => $redirect,
'redirect_uri' => $redirect_uri,
], 10 * MINUTE_IN_SECONDS);
wp_redirect($this->broker->auth_url($provider, $redirect_uri, $state)); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
exit;
} catch (\Throwable $e) {
$this->redirect_error('provider_unavailable', $provider, $action);
}
}
private function handle_callback(): void {
$state = sanitize_text_field((string) ($_GET['state'] ?? ''));
$row = $state !== '' ? OAuthTransactionStore::claim($state, 'direct') : null;
$payload = is_array($row['payload'] ?? null) ? $row['payload'] : [];
$provider = sanitize_key((string) ($payload['provider'] ?? ''));
$action = (string) ($payload['action'] ?? 'login');
if (!$row || !OAuthProviderCatalog::is_direct($provider)) {
$this->redirect_error('state_invalid', $provider, $action);
}
if ($action === 'bind' && (int) ($payload['user_id'] ?? 0) !== get_current_user_id()) {
$this->redirect_error('state_user_mismatch', $provider, $action);
}
if (!empty($_GET['error'])) {
$this->redirect_error('provider_cancelled', $provider, $action);
}
$code = sanitize_text_field((string) ($_GET['code'] ?? ''));
if ($code === '') {
$this->redirect_error('code_missing', $provider, $action);
}
try {
$identity = $this->broker->identity($provider, $code, (string) $payload['redirect_uri'], $state);
if (empty($identity['provider_id'])) {
throw new \RuntimeException('missing_provider_id');
}
if ($action === 'bind') {
$result = OAuthAccountService::bind(get_current_user_id(), $provider, $identity);
if (is_wp_error($result)) {
throw new \RuntimeException($result->get_error_code());
}
$this->redirect_success('bind', $provider, function_exists('aksrt_get_user_center_url') ? aksrt_get_user_center_url('settings') : home_url('/'));
}
$this->complete_identity_login($provider, $identity, (string) ($payload['redirect_to'] ?? home_url('/')));
} catch (\Throwable $e) {
$this->redirect_error($e->getMessage() === 'oauth_binding_conflict' ? 'binding_conflict' : 'callback_failed', $provider, $action);
}
}
private function handle_clogin_start(): void {
$config = OAuthProviderCatalog::clogin_settings();
$type = sanitize_key((string) ($_GET['type'] ?? ''));
$action = sanitize_key((string) ($_GET['action'] ?? '')) === 'bind' ? 'bind' : 'login';
if (!$config['enabled'] || !in_array($type, $config['types'], true)) {
$this->redirect_error('provider_disabled', 'clogin_' . $type, $action);
}
if ($action === 'bind' && !is_user_logged_in()) {
wp_safe_redirect(function_exists('aksrt_get_login_url') ? aksrt_get_login_url() : wp_login_url());
exit;
}
$redirect = isset($_GET['redirect_to']) ? OAuthUrlPolicy::validated_redirect((string) $_GET['redirect_to'], home_url('/')) : home_url('/');
try {
$state = OAuthTransactionStore::issue('clogin', [
'type' => $type,
'action' => $action,
'user_id' => get_current_user_id(),
'redirect_to' => $redirect,
], 10 * MINUTE_IN_SECONDS);
$client = new CLoginClient([
'apiurl' => $config['url'],
'appid' => $config['id'],
'appkey' => $config['key'],
'callback' => home_url('/oauth/clogin/callback/'),
]);
$response = $client->login($type, $state);
if (!empty($response['code']) || empty($response['url'])) {
throw new \RuntimeException('clogin_unavailable');
}
wp_redirect((string) $response['url']); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
exit;
} catch (\Throwable $e) {
$this->redirect_error('provider_unavailable', 'clogin_' . $type, $action);
}
}
private function handle_clogin_callback(): void {
$state = sanitize_text_field((string) ($_GET['state'] ?? ''));
$row = $state !== '' ? OAuthTransactionStore::claim($state, 'clogin') : null;
$payload = is_array($row['payload'] ?? null) ? $row['payload'] : [];
$type = sanitize_key((string) ($payload['type'] ?? ''));
$provider = 'clogin_' . $type;
$action = (string) ($payload['action'] ?? 'login');
if (!$row || !in_array($type, OAuthProviderCatalog::clogin_settings()['types'], true)) {
$this->redirect_error('state_invalid', $provider, $action);
}
if ($action === 'bind' && (int) ($payload['user_id'] ?? 0) !== get_current_user_id()) {
$this->redirect_error('state_user_mismatch', $provider, $action);
}
$code = sanitize_text_field((string) ($_GET['code'] ?? ''));
if ($code === '') {
$this->redirect_error('code_missing', $provider, $action);
}
$config = OAuthProviderCatalog::clogin_settings();
$client = new CLoginClient(['apiurl' => $config['url'], 'appid' => $config['id'], 'appkey' => $config['key']]);
$info = $client->callback($code);
$returned_type = $client->from_api_type((string) ($info['type'] ?? ''));
if ((isset($info['code']) && (int) $info['code'] !== 0) || $returned_type !== $type || empty($info['social_uid'])) {
$this->redirect_error('callback_failed', $provider, $action);
}
$identity = [
'provider' => $provider,
'provider_id' => (string) $info['social_uid'],
'username' => sanitize_text_field((string) ($info['nickname'] ?? '')),
'name' => sanitize_text_field((string) ($info['nickname'] ?? '')),
'email' => '',
'email_verified' => false,
'avatar_url' => esc_url_raw((string) ($info['faceimg'] ?? '')),
];
if ($action === 'bind') {
$result = OAuthAccountService::bind(get_current_user_id(), $provider, $identity);
if (is_wp_error($result)) {
$this->redirect_error('binding_conflict', $provider, $action);
}
$this->redirect_success('bind', $provider, function_exists('aksrt_get_user_center_url') ? aksrt_get_user_center_url('settings') : home_url('/'));
}
$this->complete_identity_login($provider, $identity, (string) ($payload['redirect_to'] ?? home_url('/')));
}
private function complete_identity_login(string $provider, array $identity, string $redirect): void {
$user = OAuthAccountService::resolve($provider, $identity);
if (is_wp_error($user) && $user->get_error_code() === 'oauth_no_match') {
$obk = OAuthTransactionStore::issue('obk', [
'provider' => $provider,
'provider_id' => (string) ($identity['provider_id'] ?? ''),
'user_data' => $identity,
'redirect_to' => OAuthUrlPolicy::validated_redirect($redirect, home_url('/')),
], 15 * MINUTE_IN_SECONDS);
$url = function_exists('aksrt_get_bind_url') ? aksrt_get_bind_url($obk) : home_url('/sign/?tab=bind&obk=' . rawurlencode($obk));
wp_safe_redirect($url);
exit;
}
if (!$user instanceof \WP_User) {
$this->redirect_error('account_match_failed', $provider, 'login');
}
OAuthAccountService::complete_login($user, true);
$this->redirect_success('login', $provider, OAuthUrlPolicy::validated_redirect($redirect, home_url('/')));
}
private function binding_row(string $provider, bool $bound): array {
return [
'key' => $provider,
'name' => OAuthProviderCatalog::label($provider),
'icon' => function_exists('aksrt_brand_icon') ? aksrt_brand_icon(OAuthProviderCatalog::icon_key($provider)) : '',
'is_bound' => $bound,
'url' => '',
];
}
private function redirect_success(string $action, string $provider, string $target): void {
wp_safe_redirect(add_query_arg([
'oauth_action' => $action,
'oauth_provider' => $provider,
], $target));
exit;
}
private function redirect_error(string $code, string $provider = '', string $action = 'login'): void {
$target = $action === 'bind' && is_user_logged_in() && function_exists('aksrt_get_user_center_url')
? aksrt_get_user_center_url('settings')
: (function_exists('aksrt_get_login_url') ? aksrt_get_login_url() : wp_login_url());
wp_safe_redirect(add_query_arg([
'oauth_action' => 'error',
'oauth_provider' => sanitize_key($provider),
'oauth_error' => sanitize_key($code),
], $target));
exit;
}
}
+133
View File
@@ -0,0 +1,133 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Auth;
defined('ABSPATH') || exit;
final class OAuthAccountService {
public static function resolve(string $provider, array $identity) {
$provider = sanitize_key($provider);
$provider_id = (string) ($identity['provider_id'] ?? '');
$user = self::find($provider, $provider_id);
if ($user instanceof \WP_User) {
self::refresh($user->ID, $provider, $identity);
return $user;
}
if (
OAuthProviderCatalog::bind_type() === 'auto'
&& !empty($identity['email_verified'])
&& is_email((string) ($identity['email'] ?? ''))
) {
$user = get_user_by('email', sanitize_email((string) $identity['email']));
if ($user instanceof \WP_User) {
$result = self::bind($user->ID, $provider, $identity);
return is_wp_error($result) ? $result : $user;
}
}
return new \WP_Error('oauth_no_match', __('需要绑定已有账号', 'aksrt'), [
'provider' => $provider,
'user_data' => $identity,
]);
}
public static function find(string $provider, string $provider_id): ?\WP_User {
$provider = sanitize_key($provider);
if (!OAuthProviderCatalog::is_binding_provider($provider) || $provider_id === '') {
return null;
}
$users = get_users([
'meta_key' => 'aksrt_' . $provider . '_id',
'meta_value' => $provider_id,
'number' => 1,
'fields' => 'all',
]);
return !empty($users[0]) && $users[0] instanceof \WP_User ? $users[0] : null;
}
public static function bind(int $user_id, string $provider, array $identity) {
$provider = sanitize_key($provider);
$provider_id = trim((string) ($identity['provider_id'] ?? ''));
if ($user_id <= 0 || !OAuthProviderCatalog::is_binding_provider($provider) || $provider_id === '') {
return new \WP_Error('oauth_binding_invalid', __('第三方账号信息无效', 'aksrt'));
}
$scope = 'identity:' . $provider . ':' . $provider_id;
$lock = OAuthTransactionStore::acquire_lock($scope, 20);
if ($lock === false) {
return new \WP_Error('oauth_binding_busy', __('该第三方账号正在绑定,请稍后重试', 'aksrt'));
}
try {
$existing = self::find($provider, $provider_id);
if ($existing && (int) $existing->ID !== $user_id) {
return new \WP_Error('oauth_binding_conflict', __('该第三方账号已被其他用户绑定', 'aksrt'));
}
update_user_meta($user_id, 'aksrt_' . $provider . '_id', $provider_id);
$bindings = get_user_meta($user_id, 'aksrt_oauth_bindings', true);
$bindings = is_array($bindings) ? array_values(array_intersect($bindings, OAuthProviderCatalog::all_binding_keys())) : [];
if (!in_array($provider, $bindings, true)) {
$bindings[] = $provider;
}
update_user_meta($user_id, 'aksrt_oauth_bindings', array_values(array_unique($bindings)));
if (!empty($identity['avatar_url'])) {
update_user_meta($user_id, 'aksrt_oauth_avatar', esc_url_raw((string) $identity['avatar_url']));
}
return true;
} finally {
OAuthTransactionStore::release_lock($scope, (string) $lock);
}
}
public static function unbind(int $user_id, string $provider) {
$provider = sanitize_key($provider);
if ($user_id <= 0 || !OAuthProviderCatalog::is_binding_provider($provider)) {
return new \WP_Error('oauth_unbind_invalid', __('第三方账号类型无效', 'aksrt'));
}
if (!self::has_recovery_after_unbind($user_id, $provider)) {
return new \WP_Error('oauth_last_login_method', __('请先设置其他登录或找回方式,再解除当前绑定', 'aksrt'));
}
$bindings = get_user_meta($user_id, 'aksrt_oauth_bindings', true);
$bindings = is_array($bindings) ? $bindings : [];
$bindings = array_values(array_diff($bindings, [$provider]));
update_user_meta($user_id, 'aksrt_oauth_bindings', $bindings);
delete_user_meta($user_id, 'aksrt_' . $provider . '_id');
delete_user_meta($user_id, 'aksrt_' . $provider . '_token');
return true;
}
public static function complete_login(\WP_User $user, bool $remember = true): void {
wp_set_current_user($user->ID);
wp_set_auth_cookie($user->ID, $remember);
do_action('wp_login', $user->user_login, $user);
}
public static function bindings(int $user_id): array {
$bindings = get_user_meta($user_id, 'aksrt_oauth_bindings', true);
return is_array($bindings) ? array_values(array_intersect($bindings, OAuthProviderCatalog::all_binding_keys())) : [];
}
private static function refresh(int $user_id, string $provider, array $identity): void {
$bindings = self::bindings($user_id);
if (!in_array($provider, $bindings, true)) {
$bindings[] = $provider;
update_user_meta($user_id, 'aksrt_oauth_bindings', array_values(array_unique($bindings)));
}
if (!empty($identity['avatar_url'])) {
update_user_meta($user_id, 'aksrt_oauth_avatar', esc_url_raw((string) $identity['avatar_url']));
}
}
private static function has_recovery_after_unbind(int $user_id, string $provider): bool {
$remaining = array_values(array_diff(self::bindings($user_id), [$provider]));
if ($remaining !== []) {
return true;
}
if (get_user_meta($user_id, 'aksrt_phone_verified', true) === '1') {
return true;
}
$user = get_user_by('id', $user_id);
return $user instanceof \WP_User && is_email($user->user_email);
}
}
-615
View File
@@ -1,615 +0,0 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Auth;
defined('ABSPATH') || exit;
trait OAuthPart1 {
private function get_baidu_user_data(array $config, string $code, string $redirect_uri): array {
$oauth = new \Yurun\OAuthLogin\Baidu\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$userInfo = $oauth->getUserInfo();
return [
'provider' => 'baidu',
'provider_id' => (string) ($userInfo['userid'] ?? ''),
'username' => $userInfo['username'] ?? '',
'name' => $userInfo['realname'] ?? $userInfo['username'] ?? '',
'email' => $userInfo['email'] ?? '',
'avatar_url' => $userInfo['portrait'] ? ('https://himg.bdimg.com/sys/portrait/item/' . $userInfo['portrait'] . '.jpg') : '',
];
}
private function get_alipay_user_data(array $config, string $code, string $redirect_uri): array {
$oauth = new \Yurun\OAuthLogin\Alipay\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$userInfo = $oauth->getUserInfo();
return [
'provider' => 'alipay',
'provider_id' => (string) ($userInfo['user_id'] ?? ''),
'username' => $userInfo['user_name'] ?? '',
'name' => $userInfo['user_name'] ?? '',
'email' => $userInfo['email'] ?? '',
'avatar_url' => $userInfo['avatar'] ?? '',
'gender' => ($userInfo['gender'] ?? '') === 'm' ? 'male' : (($userInfo['gender'] ?? '') === 'f' ? 'female' : ''),
];
}
private function get_google_auth_url(array $config, string $redirect_uri, string $state): string {
$params = http_build_query([
'client_id' => $config['client_id'],
'redirect_uri' => $redirect_uri,
'response_type' => 'code',
'scope' => 'openid email profile',
'state' => $state,
'access_type' => 'offline',
]);
return 'https://accounts.google.com/o/oauth2/v2/auth?' . $params;
}
private function get_google_user_data(array $config, string $code, string $redirect_uri): array {
// 换取 token
$response = wp_remote_post('https://oauth2.googleapis.com/token', [
'body' => [
'code' => $code,
'client_id' => $config['client_id'],
'client_secret' => $config['client_secret'],
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code',
],
]);
if (is_wp_error($response)) {
throw new \Exception($response->get_error_message());
}
$token_data = json_decode(wp_remote_retrieve_body($response), true);
if (empty($token_data['access_token'])) {
throw new \Exception(__('Google token 获取失败', 'aksrt'));
}
// 获取用户信息
$user_response = wp_remote_get('https://www.googleapis.com/oauth2/v2/userinfo', [
'headers' => ['Authorization' => 'Bearer ' . $token_data['access_token']],
]);
if (is_wp_error($user_response)) {
throw new \Exception($user_response->get_error_message());
}
$user_info = json_decode(wp_remote_retrieve_body($user_response), true);
return [
'provider' => 'google',
'provider_id' => (string) ($user_info['id'] ?? ''),
'username' => $user_info['email'] ?? '',
'name' => $user_info['name'] ?? '',
'email' => $user_info['email'] ?? '',
'email_verified' => !empty($user_info['verified_email']),
'avatar_url' => $user_info['picture'] ?? '',
'locale' => $user_info['locale'] ?? '',
];
}
/**
* 微信公众号 OAuth2 授权 URL
*
* 使用 snsapi_userinfo scope 获取用户信息(需已认证服务号或订阅号+验证)。
*/
private function get_weixingzh_auth_url(array $config, string $redirect_uri, string $state): string {
$params = http_build_query([
'appid' => $config['client_id'],
'redirect_uri' => $redirect_uri,
'response_type' => 'code',
'scope' => 'snsapi_userinfo',
'state' => $state,
]);
return 'https://open.weixin.qq.com/connect/oauth2/authorize?' . $params . '#wechat_redirect';
}
/**
* 微信公众号 OAuth2 获取用户信息
*
* 1. code → access_token + openid
* 2. access_token + openid → userinfo
*/
private function get_weixingzh_user_data(array $config, string $code, string $redirect_uri): array {
// 1. 换取 access_token
$token_url = add_query_arg([
'appid' => $config['client_id'],
'secret' => $config['client_secret'],
'code' => $code,
'grant_type' => 'authorization_code',
], 'https://api.weixin.qq.com/sns/oauth2/access_token');
$response = wp_remote_get($token_url);
if (is_wp_error($response)) {
throw new \Exception($response->get_error_message());
}
$token_data = json_decode(wp_remote_retrieve_body($response), true);
if (empty($token_data['access_token']) || empty($token_data['openid'])) {
$errmsg = $token_data['errmsg'] ?? __('微信公众号 token 获取失败', 'aksrt');
throw new \Exception($errmsg);
}
// 2. 获取用户信息
$user_url = add_query_arg([
'access_token' => $token_data['access_token'],
'openid' => $token_data['openid'],
'lang' => 'zh_CN',
], 'https://api.weixin.qq.com/sns/userinfo');
$user_response = wp_remote_get($user_url);
if (is_wp_error($user_response)) {
throw new \Exception($user_response->get_error_message());
}
$user_info = json_decode(wp_remote_retrieve_body($user_response), true);
return [
'provider' => 'weixingzh',
'provider_id' => (string) ($user_info['openid'] ?? $token_data['openid']),
'username' => $user_info['nickname'] ?? '',
'name' => $user_info['nickname'] ?? '',
'email' => '',
'email_verified' => false,
'avatar_url' => $user_info['headimgurl'] ?? '',
'locale' => 'zh_CN',
'unionid' => $user_info['unionid'] ?? '',
];
}
private function resolve_callback_provider(): string {
$state = $_GET['state'] ?? '';
if ($state === '') return '';
$rest = (strpos($state, 'bind_') === 0) ? substr($state, 5) : $state;
$sep = strpos($rest, '_');
if ($sep !== false && $sep < strlen($rest) - 1) {
return sanitize_key(substr($rest, 0, $sep));
}
return '';
}
private function get_enabled_providers(): array {
if (class_exists('\AKSRT\Settings\Settings') && \AKSRT\Settings\Settings::oauth_proxy_mode() === 'client') {
return \AKSRT\Settings\Settings::oauth_proxy_client_providers();
}
$providers = get_option('aksrt_oauth', []);
$enabled = [];
foreach (['github', 'gitee', 'qq', 'google', 'weibo', 'weixin', 'baidu', 'alipay', 'weixingzh'] as $key) {
if (!empty($providers[$key]['enabled']) && !empty($providers[$key]['client_id'])) {
$enabled[] = $key;
continue;
}
// BC: also check aksrt_settings flat keys
if (class_exists('\AKSRT\Settings\Settings')) {
$s = \AKSRT\Settings\Settings::get_all();
$switch_key = 'oauth_' . $key . '_s';
if (!empty($s[$switch_key])) {
$id_key = $key . '_appid';
$sec_key = $key . '_appsecret';
if ($key === 'weixingzh') {
$sec_key = 'weixingzh_appsecret';
} elseif ($key === 'github' || $key === 'gitee' || $key === 'qq') {
$sec_key = $key . '_appkey';
}
if (!empty($s[$id_key]) && !empty($s[$sec_key])) {
$enabled[] = $key;
}
}
}
}
// Rainbow aggregate (clogin) providers as virtual keys: clogin_qq, clogin_weixin...
if (class_exists('\AKSRT\Settings\Settings')) {
$s = \AKSRT\Settings\Settings::get_all();
if (!empty($s['clogin_s']) && !empty($s['clogin_url']) && !empty($s['clogin_id']) && !empty($s['clogin_key'])) {
$raw = $s['clogin_oauth_s'] ?? $s['clogin_types'] ?? ['qq', 'weixin', 'weibo', 'alipay'];
if (is_string($raw)) {
$raw = preg_split('/[,,\s]+/', $raw) ?: [];
}
if (!is_array($raw)) {
$raw = [];
}
foreach ($raw as $ctype) {
$ctype = sanitize_key((string) $ctype);
if ($ctype === '') {
continue;
}
$enabled[] = 'clogin_' . $ctype;
}
}
}
return array_values(array_unique($enabled));
}
/**
* 获取 OAuth 提供商数据(供模板使用)
* 返回 [{name, label, icon, url}, ...]
*/
public function get_auth_providers_data(): array {
$platform_names = [
'github' => 'GitHub',
'gitee' => 'Gitee',
'qq' => 'QQ',
'google' => 'Google',
'weibo' => 'Weibo',
'weixin' => 'WeChat',
'baidu' => 'Baidu',
'alipay' => 'Alipay',
'weixingzh' => '微信公众号',
];
$result = [];
foreach ($this->get_enabled_providers() as $key) {
$url = $this->get_auth_url($key);
if (empty($url)) continue;
$label = $platform_names[$key] ?? '';
$icon_key = $key;
if (str_starts_with($key, 'clogin_')) {
$ctype = substr($key, 7);
$label = ($platform_names[$ctype] ?? strtoupper($ctype)) . ' · 聚合';
$icon_key = $ctype === 'weixin' ? 'weixin' : $ctype;
}
if ($label === '') {
$label = ucfirst($key);
}
$result[] = [
'name' => $key,
'label' => $label,
'icon' => function_exists('aksrt_brand_icon') ? aksrt_brand_icon((string) $icon_key) : '',
'url' => esc_url($url),
];
}
return $result;
}
private function get_provider_config(string $provider): ?array {
$providers = get_option('aksrt_oauth', []);
$config = $providers[$provider] ?? null;
if (!empty($config['client_id']) && !empty($config['client_secret'])) {
return $config;
}
// BC: fallback to aksrt_settings flat keys
if (class_exists('\AKSRT\Settings\Settings')) {
$s = \AKSRT\Settings\Settings::get_all();
$id_key = $provider . '_appid';
$sec_key = $provider . '_appsecret';
if ($provider === 'github' || $provider === 'gitee' || $provider === 'qq') {
$sec_key = $provider . '_appkey';
} elseif ($provider === 'google') {
$id_key = 'google_client_id';
$sec_key = 'google_client_secret';
}
$client_id = (string) ($s[$id_key] ?? '');
$client_secret = (string) ($s[$sec_key] ?? '');
if ($client_id !== '' && $client_secret !== '') {
return [
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => home_url('/oauth/callback/'),
];
}
}
return null;
}
private function find_or_create_user($provider, $user_data) {
$email = $user_data['email'] ?? '';
if (!empty($user_data['provider_id'])) {
$by_provider = $this->find_user_by_provider($provider, (string) $user_data['provider_id']);
if ($by_provider instanceof \WP_User) {
$bindings = get_user_meta($by_provider->ID, 'aksrt_oauth_bindings', true) ?: [];
if (!is_array($bindings)) $bindings = [];
if (!in_array($provider, $bindings, true)) {
$bindings[] = $provider;
update_user_meta($by_provider->ID, 'aksrt_oauth_bindings', $bindings);
}
if (!empty($user_data['avatar_url'])) {
update_user_meta($by_provider->ID, 'aksrt_oauth_avatar', esc_url_raw($user_data['avatar_url']));
}
return $by_provider;
}
}
if (!empty($email)) {
$existing = get_user_by('email', $email);
if ($existing && !$existing instanceof \WP_Error) {
$bindings = get_user_meta($existing->ID, 'aksrt_oauth_bindings', true) ?: [];
if (!is_array($bindings)) $bindings = [];
if (!in_array($provider, $bindings, true)) {
$bindings[] = $provider;
update_user_meta($existing->ID, 'aksrt_oauth_bindings', $bindings);
}
if (!empty($user_data['provider_id'])) {
update_user_meta($existing->ID, "aksrt_{$provider}_id", (string) $user_data['provider_id']);
}
if (!empty($user_data['avatar_url'])) {
update_user_meta($existing->ID, 'aksrt_oauth_avatar', esc_url_raw($user_data['avatar_url']));
}
return $existing;
}
}
return new \WP_Error(
'oauth_no_match',
__('需要绑定已有账号', 'aksrt'),
[
'provider' => $provider,
'user_data' => $user_data,
]
);
}
// ============================================
// 前端UI方法
// ============================================
public function login_button(): void {
echo $this->render_social_buttons(__('使用以下方式快速登录', 'aksrt'));
}
public function register_button(): void {
echo $this->render_social_buttons(__('使用以下方式快速注册', 'aksrt'));
}
public function render_social_buttons(string $title = ''): string {
$items = $this->get_auth_providers_data();
if (empty($items)) {
return '';
}
ob_start();
?>
<div class="social-login-divider">
<span><?php echo esc_html($title) ?: esc_html__('or', 'aksrt'); ?></span>
</div>
<div class="oauth-row">
<?php foreach ($items as $item):
$key = (string) ($item['name'] ?? '');
$url = (string) ($item['url'] ?? '');
if ($key === '' || $url === '') continue;
?>
<a href="<?php echo esc_url($url); ?>"
class="oauth-btn oauth-btn--<?php echo esc_attr($key); ?>"
data-provider="<?php echo esc_attr($key); ?>"
aria-label="<?php echo esc_attr((string) ($item['label'] ?? $key)); ?>"
title="<?php echo esc_attr((string) ($item['label'] ?? $key)); ?>">
<?php echo $item['icon'] ?? ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
</a>
<?php endforeach; ?>
</div>
<?php
return ob_get_clean();
}
public function get_login_buttons(): string {
return $this->render_social_buttons();
}
public function login_message(string $message): string {
return $message . self::get_instance()->render_social_buttons();
}
public function register_message(string $message): string {
return $message . self::get_instance()->render_social_buttons(__('或使用社交账号快速注册', 'aksrt'));
}
/**
* @return array{enabled:bool,url:string,id:string,key:string,types:string[]}
*/
private function get_clogin_settings(): array {
$s = class_exists('\AKSRT\Settings\Settings') ? \AKSRT\Settings\Settings::get_all() : [];
$raw = $s['clogin_oauth_s'] ?? $s['clogin_types'] ?? ['qq', 'weixin', 'weibo', 'alipay'];
if (is_string($raw)) {
$raw = preg_split('/[,,\s]+/', $raw) ?: [];
}
if (!is_array($raw)) {
$raw = [];
}
$types = [];
foreach ($raw as $t) {
$t = sanitize_key((string) $t);
if ($t !== '') {
$types[] = $t;
}
}
return [
'enabled' => !empty($s['clogin_s']),
'url' => esc_url_raw((string) ($s['clogin_url'] ?? '')),
'id' => (string) ($s['clogin_id'] ?? ''),
'key' => (string) ($s['clogin_key'] ?? ''),
'types' => array_values(array_unique($types)),
];
}
private function get_clogin_login_url(string $type, string $action = 'login'): string {
$cfg = $this->get_clogin_settings();
$type = sanitize_key($type);
if (!$cfg['enabled'] || $cfg['url'] === '' || $cfg['id'] === '' || $cfg['key'] === '' || $type === '') {
return '';
}
if (!empty($cfg['types']) && !in_array($type, $cfg['types'], true)) {
return '';
}
$args = ['type' => $type];
if ($action === 'bind' && is_user_logged_in()) {
$args['bind'] = 1;
}
$rurl = isset($_GET['redirect_to']) ? esc_url_raw(wp_unslash((string) $_GET['redirect_to'])) : '';
if ($rurl !== '') {
$args['rurl'] = $rurl;
}
return add_query_arg($args, home_url('/oauth/clogin/'));
}
public function handle_clogin_routes(): void {
$route = get_query_var('aksrt_oauth');
if ($route === 'clogin') {
$this->handle_clogin_login();
return;
}
if ($route === 'clogin_callback') {
$this->handle_clogin_callback();
}
}
private function handle_clogin_login(): void {
$cfg = $this->get_clogin_settings();
$type = isset($_GET['type']) ? sanitize_key(wp_unslash((string) $_GET['type'])) : '';
if (!$cfg['enabled'] || $cfg['url'] === '' || $cfg['id'] === '' || $cfg['key'] === '' || $type === '') {
wp_die(esc_html__('暂未启用此登录方式', 'aksrt'));
}
if (!empty($cfg['types']) && !in_array($type, $cfg['types'], true)) {
wp_die(esc_html__('此登录方式未启用', 'aksrt'));
}
if (!class_exists(CLoginClient::class)) {
wp_die(esc_html__('聚合登录组件未加载', 'aksrt'));
}
$client = new CLoginClient([
'apiurl' => $cfg['url'],
'appid' => $cfg['id'],
'appkey' => $cfg['key'],
'callback' => home_url('/oauth/clogin/callback'),
]);
$resp = $client->login($type);
if (!empty($resp['code']) && (int) $resp['code'] !== 0 && !empty($resp['msg'])) {
wp_die(esc_html(sprintf(__('处理失败:%s', 'aksrt'), (string) $resp['msg'])));
}
if (empty($resp['url'])) {
wp_die(esc_html__('无法获取聚合登录地址', 'aksrt'));
}
if (!session_id()) {
@session_start();
}
$_SESSION['AKSRT_CLOGIN_STATE'] = $client->state;
$_SESSION['AKSRT_CLOGIN_TYPE'] = $type;
$_SESSION['AKSRT_CLOGIN_RURL'] = !empty($_GET['rurl']) ? esc_url_raw(wp_unslash((string) $_GET['rurl'])) : '';
$_SESSION['AKSRT_CLOGIN_BIND'] = !empty($_GET['bind']) ? 1 : 0;
wp_redirect(esc_url_raw((string) $resp['url']));
exit;
}
private function handle_clogin_callback(): void {
if (!session_id()) {
@session_start();
}
$state = isset($_GET['state']) ? (string) wp_unslash($_GET['state']) : '';
$code = isset($_GET['code']) ? (string) wp_unslash($_GET['code']) : '';
if ($code === '' || $state === '' || empty($_SESSION['AKSRT_CLOGIN_STATE']) || !hash_equals((string) $_SESSION['AKSRT_CLOGIN_STATE'], $state)) {
wp_die(esc_html__('环境异常,state 验证失败,请刷新后重试', 'aksrt'));
}
$cfg = $this->get_clogin_settings();
if (!$cfg['enabled']) {
wp_die(esc_html__('暂未启用此功能', 'aksrt'));
}
$client = new CLoginClient([
'apiurl' => $cfg['url'],
'appid' => $cfg['id'],
'appkey' => $cfg['key'],
]);
$info = $client->callback($code);
if (!empty($info['code']) && (int) $info['code'] !== 0 && !empty($info['msg'])) {
wp_die(esc_html((string) $info['msg']));
}
$openid = (string) ($info['social_uid'] ?? '');
$api_type = (string) ($info['type'] ?? ($_SESSION['AKSRT_CLOGIN_TYPE'] ?? ''));
$provider_type = $client->from_api_type($api_type);
if ($openid === '' || $provider_type === '') {
wp_die(esc_html__('无法获取用户信息', 'aksrt'));
}
$provider = 'clogin_' . sanitize_key($provider_type);
$user_data = [
'provider' => $provider,
'provider_id' => $openid,
'username' => (string) ($info['nickname'] ?? ''),
'name' => (string) ($info['nickname'] ?? ''),
'email' => '',
'avatar_url' => (string) ($info['faceimg'] ?? ''),
];
if ($user_data['avatar_url'] !== '' && str_contains($user_data['avatar_url'], 'no_portrait')) {
$user_data['avatar_url'] = '';
}
$is_bind = !empty($_SESSION['AKSRT_CLOGIN_BIND']);
$rurl = !empty($_SESSION['AKSRT_CLOGIN_RURL']) ? (string) $_SESSION['AKSRT_CLOGIN_RURL'] : '';
unset($_SESSION['AKSRT_CLOGIN_STATE'], $_SESSION['AKSRT_CLOGIN_TYPE'], $_SESSION['AKSRT_CLOGIN_RURL'], $_SESSION['AKSRT_CLOGIN_BIND']);
try {
if ($is_bind) {
$uid = get_current_user_id();
if ($uid <= 0) {
wp_safe_redirect(function_exists('aksrt_get_login_url') ? aksrt_get_login_url() : wp_login_url());
exit;
}
$existing = $this->find_user_by_provider($provider, $openid);
if ($existing && (int) $existing->ID !== $uid) {
throw new \Exception(__('该第三方账号已被其他用户绑定', 'aksrt'));
}
$this->bind_provider_to_user($uid, $provider, $user_data);
$redirect = function_exists('aksrt_get_user_center_url') ? aksrt_get_user_center_url() : home_url('/');
wp_safe_redirect(add_query_arg(['tab' => 'settings', 'oauth_action' => 'bind', 'oauth_bound' => $provider], $redirect));
exit;
}
$user = $this->find_or_create_user($provider, $user_data);
if (is_wp_error($user) && $user->get_error_code() === 'oauth_no_match') {
// Auto-create account for aggregate login when no match (legacy-like).
$login = 'u' . wp_generate_password(10, false, false);
$uid = wp_insert_user([
'user_login' => $login,
'user_pass' => wp_generate_password(24, true, true),
'display_name' => $user_data['name'] !== '' ? $user_data['name'] : $login,
'nickname' => $user_data['name'] !== '' ? $user_data['name'] : $login,
'role' => get_option('default_role', 'subscriber'),
]);
if (is_wp_error($uid)) {
throw new \Exception($uid->get_error_message());
}
$this->bind_provider_to_user((int) $uid, $provider, $user_data);
$user = get_user_by('id', (int) $uid);
}
if (is_wp_error($user) || !$user instanceof \WP_User) {
throw new \Exception(is_wp_error($user) ? $user->get_error_message() : __('登录失败', 'aksrt'));
}
wp_set_current_user($user->ID);
wp_set_auth_cookie($user->ID, true);
do_action('wp_login', $user->user_login, $user);
$redirect = $rurl !== '' ? $rurl : (function_exists('aksrt_get_user_center_url') ? aksrt_get_user_center_url() : home_url('/'));
wp_safe_redirect(add_query_arg(['oauth_action' => 'login', 'oauth_bound' => $provider], $redirect));
exit;
} catch (\Exception $e) {
wp_die(esc_html__('登录失败:', 'aksrt') . '<br>' . esc_html($e->getMessage()));
}
}
}
-172
View File
@@ -1,172 +0,0 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Auth;
defined('ABSPATH') || exit;
trait OAuthPart2 {
public function get_frontend_bindings_data(int $user_id): array {
$providers = get_option('aksrt_oauth', []);
$bound_list = get_user_meta($user_id, 'aksrt_oauth_bindings', true) ?: [];
if (!is_array($bound_list)) $bound_list = [];
$platform_names = [
'github' => 'GitHub', 'gitee' => 'Gitee',
'qq' => 'QQ', 'google' => 'Google',
'weibo' => 'Weibo', 'weixin' => 'WeChat',
'baidu' => 'Baidu', 'alipay' => 'Alipay',
];
$icons = [
'github' => aksrt_brand_icon('github'),
'gitee' => aksrt_brand_icon('gitee'),
'qq' => aksrt_brand_icon('qq'),
'google' => aksrt_brand_icon('google'),
'weibo' => aksrt_brand_icon('weibo'),
'weixin' => aksrt_brand_icon('weixin'),
'baidu' => aksrt_brand_icon('baidu'),
'alipay' => aksrt_brand_icon('alipay'),
];
$bindings = [];
foreach ($bound_list as $binding) {
if (in_array($binding, ['github', 'gitee', 'qq', 'google', 'weibo', 'weixin', 'baidu', 'alipay'], true) && !empty($providers[$binding]['enabled'])) {
$bindings[] = [
'key' => $binding,
'name' => $platform_names[$binding] ?? ucfirst($binding),
'icon' => $icons[$binding] ?? '',
];
}
}
$available = [];
foreach (['github', 'gitee', 'qq', 'google', 'weibo', 'weixin', 'baidu', 'alipay'] as $key) {
if (in_array($key, $bound_list, true)) continue;
if (empty($providers[$key]['enabled']) || empty($providers[$key]['client_id'])) continue;
$url = $this->get_auth_url($key, 'bind');
if (empty($url)) continue;
$available[] = [
'key' => $key,
'name' => $platform_names[$key],
'icon' => $icons[$key] ?? '',
'url' => esc_url($url),
];
}
return [
'bindings' => $bindings,
'available' => $available,
];
}
public function profile_bindings(\WP_User $user): void {
$bindings = get_user_meta($user->ID, 'aksrt_oauth_bindings', true) ?: [];
if (empty($bindings)) return;
$unbind_nonce = wp_create_nonce('aksrt_oauth_unbind');
?>
<h2><?php _e('社交账号绑定', 'aksrt'); ?></h2>
<table class="form-table">
<?php foreach ($bindings as $binding): ?>
<tr>
<th scope="row"><?php echo esc_html(ucfirst($binding)); ?></th>
<td><span class="badge" style="background:#d1fae5;color:#065f46;padding:4px 12px;border-radius:12px;font-size:12px;">&#10003; <?php esc_html_e('已绑定', 'aksrt'); ?></span></td>
<td>
<button type="button" class="button button-link-delete aksrt-oauth-unbind-btn"
data-provider="<?php echo esc_attr($binding); ?>"
data-user-id="<?php echo esc_attr((string) $user->ID); ?>">
<?php _e('解除绑定', 'aksrt'); ?>
</button>
</td>
</tr>
<?php endforeach; ?>
</table>
<script>
(function(){
var nonce = <?php echo wp_json_encode($unbind_nonce); ?>;
var ajaxUrl = <?php echo wp_json_encode(admin_url('admin-ajax.php')); ?>;
document.querySelectorAll('.aksrt-oauth-unbind-btn').forEach(function(btn){
btn.addEventListener('click', function(){
var msg = <?php echo wp_json_encode(__('确定要解除绑定吗?', 'aksrt')); ?>;
if(!window.confirm(msg)) return;
var fd = new FormData();
fd.append('action', 'aksrt_oauth_unbind');
fd.append('nonce', nonce);
fd.append('provider', btn.getAttribute('data-provider'));
fd.append('userId', btn.getAttribute('data-user-id'));
fetch(ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd })
.then(function(r){ return r.json(); })
.then(function(d){ if(d && d.success){ location.reload(); } });
});
});
})();
</script>
<?php
}
public function ajax_unbind(): void {
check_ajax_referer('aksrt_oauth_unbind', 'nonce');
$provider = sanitize_key($_POST['provider'] ?? '');
$user_id = isset($_POST['userId']) ? (int) $_POST['userId'] : 0;
$current_id = get_current_user_id();
if (empty($provider) || !in_array($provider, ['github', 'gitee', 'qq', 'google', 'weibo', 'weixin', 'baidu', 'alipay'], true)) {
wp_send_json_error(400);
}
if ($current_id !== $user_id || !current_user_can('read')) {
wp_send_json_error(403);
}
$bindings = get_user_meta($current_id, 'aksrt_oauth_bindings', true) ?: [];
$bindings = array_values(array_diff($bindings, [$provider]));
update_user_meta($current_id, 'aksrt_oauth_bindings', $bindings);
delete_user_meta($current_id, "aksrt_{$provider}_id");
delete_user_meta($current_id, "aksrt_{$provider}_token");
wp_send_json_success(['unbound' => true]);
}
private function find_user_by_provider(string $provider, string $provider_id): ?\WP_User {
if (empty($provider_id)) return null;
$users = get_users([
'meta_key' => "aksrt_{$provider}_id",
'meta_value' => $provider_id,
'number' => 1,
]);
return !empty($users[0]) ? $users[0] : null;
}
private function bind_provider_to_user(int $user_id, string $provider, array $user_data): void {
if (!empty($user_data['provider_id'])) {
update_user_meta($user_id, "aksrt_{$provider}_id", $user_data['provider_id']);
}
$bindings = get_user_meta($user_id, 'aksrt_oauth_bindings', true) ?: [];
if (!is_array($bindings)) $bindings = [];
if (!in_array($provider, $bindings, true)) {
$bindings[] = $provider;
update_user_meta($user_id, 'aksrt_oauth_bindings', $bindings);
}
if (!empty($user_data['avatar_url'])) {
update_user_meta($user_id, 'aksrt_oauth_avatar', esc_url_raw($user_data['avatar_url']));
}
}
private function get_profile_url(): string {
if (function_exists('aksrt_get_user_center_url')) {
return aksrt_get_user_center_url();
}
$user = wp_get_current_user();
if ($user->ID) {
return function_exists('aksrt_get_user_home_url') ? aksrt_get_user_home_url($user) : home_url('/');
}
return home_url('/');
}
}
+183
View File
@@ -0,0 +1,183 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Auth;
defined('ABSPATH') || exit;
final class OAuthProviderBroker {
public function auth_url(string $provider, string $redirect_uri, string $state): string {
$config = OAuthProviderCatalog::provider_config($provider);
if (!$config || !$config['configured']) {
throw new \RuntimeException(__('未配置此第三方登录平台', 'aksrt'));
}
if ($provider === 'google') {
return 'https://accounts.google.com/o/oauth2/v2/auth?' . http_build_query([
'client_id' => $config['client_id'],
'redirect_uri' => $redirect_uri,
'response_type' => 'code',
'scope' => 'openid email profile',
'state' => $state,
]);
}
$oauth = $this->client($provider, $config, $redirect_uri);
$scope = $provider === 'github' ? 'read:user user:email' : null;
return (string) $oauth->getAuthUrl($redirect_uri, $state, $scope);
}
public function identity(string $provider, string $code, string $redirect_uri, string $state): array {
$config = OAuthProviderCatalog::provider_config($provider);
if (!$config || !$config['configured']) {
throw new \RuntimeException(__('未配置此第三方登录平台', 'aksrt'));
}
if ($provider === 'google') {
return $this->google_identity($config, $code, $redirect_uri);
}
$oauth = $this->client($provider, $config, $redirect_uri);
$oauth->getAccessToken($state, $code, $state);
if ($provider === 'qq') {
$openid = (string) $oauth->getOpenID();
$info = (array) $oauth->getUserInfo();
return $this->normalize($provider, $openid, $info);
}
$info = (array) $oauth->getUserInfo();
if ($provider === 'github') {
return $this->github_identity($oauth, $info);
}
return $this->normalize($provider, '', $info);
}
private function client(string $provider, array $config, string $redirect_uri) {
switch ($provider) {
case 'github':
return new \Yurun\OAuthLogin\Github\OAuth2($config['client_id'], $config['client_secret'], $redirect_uri);
case 'gitee':
return new \Yurun\OAuthLogin\Gitee\OAuth2($config['client_id'], $config['client_secret'], $redirect_uri);
case 'qq':
return new \Yurun\OAuthLogin\QQ\OAuth2($config['client_id'], $config['client_secret'], $redirect_uri);
case 'weibo':
return new \Yurun\OAuthLogin\Weibo\OAuth2($config['client_id'], $config['client_secret'], $redirect_uri);
case 'weixin':
return new \Yurun\OAuthLogin\Weixin\OAuth2($config['client_id'], $config['client_secret'], $redirect_uri);
}
throw new \RuntimeException(__('不支持的第三方登录平台', 'aksrt'));
}
private function github_identity($oauth, array $info): array {
$email = '';
$email_verified = false;
$response = $oauth->http->header('Authorization', ' token ' . $oauth->accessToken)
->get('https://api.github.com/user/emails')
->body();
$emails = json_decode((string) $response, true);
foreach (is_array($emails) ? $emails : [] as $candidate) {
if (!empty($candidate['primary']) && !empty($candidate['verified']) && is_email((string) ($candidate['email'] ?? ''))) {
$email = sanitize_email((string) $candidate['email']);
$email_verified = true;
break;
}
}
return [
'provider' => 'github',
'provider_id' => (string) ($info['id'] ?? ''),
'username' => (string) ($info['login'] ?? ''),
'name' => (string) ($info['name'] ?? ''),
'email' => $email,
'email_verified' => $email_verified,
'avatar_url' => (string) ($info['avatar_url'] ?? ''),
'url' => (string) ($info['html_url'] ?? ''),
'bio' => (string) ($info['bio'] ?? ''),
];
}
private function google_identity(array $config, string $code, string $redirect_uri): array {
$response = wp_remote_post('https://oauth2.googleapis.com/token', [
'timeout' => 15,
'redirects' => 2,
'body' => [
'code' => $code,
'client_id' => $config['client_id'],
'client_secret' => $config['client_secret'],
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code',
],
]);
if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
throw new \RuntimeException(is_wp_error($response) ? $response->get_error_message() : __('Google token 获取失败', 'aksrt'));
}
$token = json_decode((string) wp_remote_retrieve_body($response), true);
if (empty($token['access_token'])) {
throw new \RuntimeException(__('Google token 获取失败', 'aksrt'));
}
$profile_response = wp_remote_get('https://openidconnect.googleapis.com/v1/userinfo', [
'timeout' => 15,
'redirects' => 2,
'headers' => ['Authorization' => 'Bearer ' . $token['access_token']],
]);
if (is_wp_error($profile_response) || wp_remote_retrieve_response_code($profile_response) !== 200) {
throw new \RuntimeException(is_wp_error($profile_response) ? $profile_response->get_error_message() : __('Google 用户信息获取失败', 'aksrt'));
}
$info = json_decode((string) wp_remote_retrieve_body($profile_response), true);
return [
'provider' => 'google',
'provider_id' => (string) ($info['sub'] ?? ''),
'username' => (string) ($info['email'] ?? ''),
'name' => (string) ($info['name'] ?? ''),
'email' => sanitize_email((string) ($info['email'] ?? '')),
'email_verified' => !empty($info['email_verified']),
'avatar_url' => (string) ($info['picture'] ?? ''),
'locale' => (string) ($info['locale'] ?? ''),
];
}
private function normalize(string $provider, string $provider_id, array $info): array {
switch ($provider) {
case 'gitee':
return [
'provider' => $provider,
'provider_id' => (string) ($info['id'] ?? ''),
'username' => (string) ($info['login'] ?? ''),
'name' => (string) ($info['name'] ?? ''),
'email' => sanitize_email((string) ($info['email'] ?? '')),
'email_verified' => false,
'avatar_url' => (string) ($info['avatar_url'] ?? ''),
'url' => (string) ($info['html_url'] ?? ''),
'bio' => (string) ($info['bio'] ?? ''),
];
case 'qq':
return [
'provider' => $provider,
'provider_id' => $provider_id,
'username' => (string) ($info['nickname'] ?? ''),
'name' => (string) ($info['nickname'] ?? ''),
'email' => '',
'email_verified' => false,
'avatar_url' => (string) ($info['figureurl_qq_2'] ?? $info['figureurl_2'] ?? $info['figureurl'] ?? ''),
];
case 'weibo':
return [
'provider' => $provider,
'provider_id' => (string) ($info['id'] ?? ''),
'username' => (string) ($info['screen_name'] ?? ''),
'name' => (string) ($info['name'] ?? ''),
'email' => '',
'email_verified' => false,
'avatar_url' => (string) ($info['avatar_large'] ?? $info['profile_image_url'] ?? ''),
];
case 'weixin':
return [
'provider' => $provider,
'provider_id' => (string) ($info['openid'] ?? ''),
'username' => (string) ($info['nickname'] ?? ''),
'name' => (string) ($info['nickname'] ?? ''),
'email' => '',
'email_verified' => false,
'avatar_url' => (string) ($info['headimgurl'] ?? ''),
];
}
throw new \RuntimeException(__('不支持的第三方登录平台', 'aksrt'));
}
}
+206
View File
@@ -0,0 +1,206 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Auth;
use AKSRT\Settings\Settings;
defined('ABSPATH') || exit;
final class OAuthProviderCatalog {
private const DIRECT = [
'github' => [
'label' => 'GitHub',
'id_key' => 'github_appid',
'secret_key' => 'github_appkey',
],
'gitee' => [
'label' => 'Gitee',
'id_key' => 'gitee_appid',
'secret_key' => 'gitee_appkey',
],
'qq' => [
'label' => 'QQ',
'id_key' => 'qq_appid',
'secret_key' => 'qq_appkey',
],
'google' => [
'label' => 'Google',
'id_key' => 'google_client_id',
'secret_key' => 'google_client_secret',
],
'weibo' => [
'label' => 'Weibo',
'id_key' => 'weibo_appid',
'secret_key' => 'weibo_appkey',
],
'weixin' => [
'label' => 'WeChat',
'id_key' => 'weixin_appid',
'secret_key' => 'weixin_appsecret',
],
];
private const CLOGIN_TYPES = ['qq', 'weixin', 'weibo'];
public static function direct_keys(): array {
return array_keys(self::DIRECT);
}
public static function all_binding_keys(): array {
$keys = array_merge(self::direct_keys(), ['weixingzh']);
foreach (self::CLOGIN_TYPES as $type) {
$keys[] = 'clogin_' . $type;
}
return $keys;
}
public static function is_direct(string $provider): bool {
return isset(self::DIRECT[sanitize_key($provider)]);
}
public static function is_binding_provider(string $provider): bool {
return in_array(sanitize_key($provider), self::all_binding_keys(), true);
}
public static function label(string $provider): string {
$provider = sanitize_key($provider);
if (isset(self::DIRECT[$provider])) {
return self::DIRECT[$provider]['label'];
}
if ($provider === 'weixingzh') {
return __('微信公众号', 'aksrt');
}
if (str_starts_with($provider, 'clogin_')) {
$type = substr($provider, 7);
if (in_array($type, self::CLOGIN_TYPES, true)) {
return self::label($type) . ' · ' . __('聚合', 'aksrt');
}
}
return ucfirst($provider);
}
public static function icon_key(string $provider): string {
$provider = sanitize_key($provider);
return str_starts_with($provider, 'clogin_') ? substr($provider, 7) : $provider;
}
public static function master_enabled(): bool {
return !Settings::close_sign() && (bool) Settings::get_value('oauth_s', false);
}
public static function provider_config(string $provider): ?array {
$provider = sanitize_key($provider);
if (!isset(self::DIRECT[$provider])) {
return null;
}
$settings = Settings::get_all();
$definition = self::DIRECT[$provider];
$client_id = trim((string) ($settings[$definition['id_key']] ?? ''));
$client_secret = trim((string) ($settings[$definition['secret_key']] ?? ''));
return [
'provider' => $provider,
'enabled' => self::master_enabled() && !empty($settings['oauth_' . $provider . '_s']),
'client_id' => $client_id,
'client_secret' => $client_secret,
'configured' => $client_id !== '' && $client_secret !== '',
];
}
public static function enabled_direct_keys(): array {
if (!self::master_enabled()) {
return [];
}
$result = [];
foreach (self::direct_keys() as $provider) {
$config = self::provider_config($provider);
if ($config && $config['enabled'] && $config['configured']) {
$result[] = $provider;
}
}
return $result;
}
public static function proxy_mode(): string {
$mode = sanitize_key((string) Settings::get_value('oauth_proxy_mode', 'close'));
return in_array($mode, ['close', 'server', 'client'], true) ? $mode : 'close';
}
public static function proxy_secret(): string {
return trim((string) Settings::get_value('oauth_proxy_secret', ''));
}
public static function proxy_server_url(): string {
return esc_url_raw(trim((string) Settings::get_value('oauth_proxy_server_url', '')));
}
public static function proxy_server_providers(): array {
$providers = (array) Settings::get_value('oauth_proxy_server_providers', []);
$result = [];
foreach (array_values(array_intersect(array_map('sanitize_key', $providers), self::direct_keys())) as $provider) {
$config = self::provider_config($provider);
if ($config && $config['configured']) {
$result[] = $provider;
}
}
return $result;
}
public static function proxy_client_providers(): array {
$providers = (array) Settings::get_value('oauth_proxy_client_providers', []);
return array_values(array_intersect(array_map('sanitize_key', $providers), self::direct_keys()));
}
public static function bind_type(): string {
$type = sanitize_key((string) Settings::get_value('oauth_bind_type', 'auto'));
return in_array($type, ['auto', 'manual'], true) ? $type : 'auto';
}
public static function clogin_settings(): array {
$settings = Settings::get_all();
$raw = (array) ($settings['clogin_oauth_s'] ?? self::CLOGIN_TYPES);
$types = array_values(array_intersect(array_map('sanitize_key', $raw), self::CLOGIN_TYPES));
return [
'enabled' => self::master_enabled() && !empty($settings['clogin_s']),
'url' => esc_url_raw(trim((string) ($settings['clogin_url'] ?? ''))),
'id' => trim((string) ($settings['clogin_id'] ?? '')),
'key' => trim((string) ($settings['clogin_key'] ?? '')),
'types' => $types,
];
}
public static function enabled_login_keys(): array {
if (!self::master_enabled()) {
return [];
}
if (self::proxy_mode() === 'client') {
if (self::proxy_server_url() === '' || self::proxy_secret() === '') {
return [];
}
return self::proxy_client_providers();
}
$result = self::enabled_direct_keys();
$settings = Settings::get_all();
if (!empty($settings['oauth_weixingzh_s'])) {
$gzh_type = sanitize_key((string) ($settings['weixingzh_gzh_type'] ?? 'service'));
$has_base = trim((string) ($settings['weixingzh_token'] ?? '')) !== ''
&& trim((string) ($settings['weixingzh_appid'] ?? '')) !== '';
$has_mode = $gzh_type === 'subscribe'
? trim((string) ($settings['weixingzh_code_qrcode'] ?? '')) !== ''
: trim((string) ($settings['weixingzh_appsecret'] ?? '')) !== '';
if ($has_base && $has_mode) {
$result[] = 'weixingzh';
}
}
$clogin = self::clogin_settings();
if ($clogin['enabled'] && $clogin['url'] !== '' && $clogin['id'] !== '' && $clogin['key'] !== '') {
foreach ($clogin['types'] as $type) {
$result[] = 'clogin_' . $type;
}
}
return array_values(array_unique($result));
}
}
+228 -264
View File
@@ -7,300 +7,264 @@ namespace AKSRT\Auth;
defined('ABSPATH') || exit;
class OAuthProxyClient {
final class OAuthProxyClient {
private static $instance = null;
private static $instance = null;
public static function get_instance(): self {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public static function get_instance(): self {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {}
private function __construct() {}
/**
* 初始化:注册回调路由
*/
public function init(): void {
add_action('template_redirect', [$this, 'handle_proxy_callback']);
add_action('init', [$this, 'add_rewrite_rules']);
}
public function init(): void {
add_action('init', [$this, 'add_rewrite_rules']);
add_action('init', [$this, 'maybe_flush_rewrite_rules'], 20);
add_action('template_redirect', [$this, 'handle_proxy_callback'], 5);
}
/**
* 添加 URL 重写规则
*/
public function add_rewrite_rules(): void {
add_rewrite_rule(
'^oauth/proxy/callback/?$',
'index.php?aksrt_proxy_callback=1',
'top'
);
public function add_rewrite_rules(): void {
add_rewrite_rule('^oauth/proxy/callback/?$', 'index.php?aksrt_proxy_callback=1', 'top');
add_filter('query_vars', static function (array $vars): array {
$vars[] = 'aksrt_proxy_callback';
return $vars;
});
}
add_filter('query_vars', function ($vars) {
$vars[] = 'aksrt_proxy_callback';
return $vars;
});
}
public function maybe_flush_rewrite_rules(): void {
$version = defined('AKSRT_VERSION') ? AKSRT_VERSION . ':oauth-proxy-client-v2' : 'oauth-proxy-client-v2';
if (get_option('aksrt_oauth_proxy_client_routes_flushed') !== $version) {
flush_rewrite_rules(false);
update_option('aksrt_oauth_proxy_client_routes_flushed', $version, false);
}
}
/**
* 生成代理登录 URL
*
* @param string $provider 平台标识
* @param string $action 操作类型: 'login' | 'bind'
* @return string 代理登录 URL
*/
public function get_proxy_auth_url(string $provider, string $action = 'login'): string {
$server_url = \AKSRT\Settings\Settings::oauth_proxy_server_url();
$secret = \AKSRT\Settings\Settings::oauth_proxy_secret();
public function get_proxy_auth_url(string $provider, string $action = 'login'): string {
$provider = sanitize_key($provider);
$action = $action === 'bind' ? 'bind' : 'login';
$server_url = OAuthProxyProtocol::server_base_url(OAuthProviderCatalog::proxy_server_url());
$secret = OAuthProviderCatalog::proxy_secret();
if (empty($server_url) || empty($secret)) {
return '';
}
if (
!OAuthProviderCatalog::master_enabled()
|| OAuthProviderCatalog::proxy_mode() !== 'client'
|| !OAuthProviderCatalog::is_direct($provider)
|| !in_array($provider, OAuthProviderCatalog::proxy_client_providers(), true)
|| $server_url === ''
|| $secret === ''
) {
return '';
}
$back_url = home_url('/oauth/proxy/callback');
$uid = get_current_user_id();
$nonce = wp_create_nonce('aksrt_proxy_' . $provider . '_' . $uid);
$user_id = get_current_user_id();
if ($action === 'bind' && $user_id <= 0) {
return '';
}
$params = [
'provider' => $provider,
'agent_back_url' => $back_url,
'action' => $action,
'nonce' => $nonce,
'uid' => $uid,
'ts' => time(),
];
$redirect_to = isset($_GET['redirect_to'])
? OAuthUrlPolicy::validated_redirect((string) wp_unslash($_GET['redirect_to']), home_url('/'))
: home_url('/');
$callback = OAuthProxyProtocol::callback_url(home_url('/oauth/proxy/callback/'));
if ($callback === '') {
return '';
}
$params['sign'] = $this->sign($params, $secret);
try {
$request_id = OAuthTransactionStore::issue('proxy_client', [
'request_id' => '',
'provider' => $provider,
'action' => $action,
'user_id' => $user_id,
'redirect_to' => $redirect_to,
'callback' => $callback,
'issuer' => OAuthProxyProtocol::issuer($server_url),
], OAuthProxyProtocol::REPLAY_TTL, true);
$updated = OAuthTransactionStore::update($request_id, 'proxy_client', static function (array $row) use ($request_id): array {
$row['payload']['request_id'] = $request_id;
return $row;
}, true);
if (!$updated) {
OAuthTransactionStore::claim($request_id, 'proxy_client', true);
return '';
}
} catch (\Throwable $e) {
return '';
}
$server_url = rtrim($server_url, '/');
return $server_url . '/oauth/proxy/' . $provider . '?' . http_build_query($params);
}
$params = [
'v' => OAuthProxyProtocol::VERSION,
'request_id' => $request_id,
'provider' => $provider,
'action' => $action,
'agent_back_url' => $callback,
'ts' => (string) time(),
];
$params['sign'] = OAuthProxyProtocol::sign_request($params, $secret);
/**
* 处理代理回调(从服务端重定向回来)
*/
public function handle_proxy_callback(): void {
if (!get_query_var('aksrt_proxy_callback')) {
return;
}
return $server_url . '/oauth/proxy/' . rawurlencode($provider) . '/?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
}
$secret = \AKSRT\Settings\Settings::oauth_proxy_secret();
if (empty($secret)) {
wp_die(__('代理登录配置错误', 'aksrt'));
}
public function handle_proxy_callback(): void {
if (!get_query_var('aksrt_proxy_callback')) {
return;
}
$sign = sanitize_text_field($_GET['sign'] ?? '');
$provider = sanitize_key($_GET['provider'] ?? '');
$action = sanitize_key($_GET['action'] ?? 'login');
$fields = OAuthProxyProtocol::callback_fields($_GET);
$signature = sanitize_text_field((string) wp_unslash($_GET['sign'] ?? ''));
$secret = OAuthProviderCatalog::proxy_secret();
$request_id = sanitize_text_field($fields['request_id']);
$provider = sanitize_key($fields['provider']);
$action = $fields['action'] === 'bind' ? 'bind' : 'login';
if (empty($sign) || empty($provider)) {
wp_die(__('代理回调参数无效', 'aksrt'));
}
if (
OAuthProviderCatalog::proxy_mode() !== 'client'
|| $fields['v'] !== OAuthProxyProtocol::VERSION
|| !OAuthProxyProtocol::token_valid($request_id)
|| !OAuthProxyProtocol::token_valid($fields['jti'])
|| !OAuthProxyProtocol::timestamp_valid($fields['ts'])
|| !OAuthProxyProtocol::verify_callback($fields, $secret, $signature)
) {
$this->redirect_error('proxy_response_invalid', $provider, $action);
}
// 验证签名
$verify_params = $_GET;
unset($verify_params['sign']);
$row = OAuthTransactionStore::peek($request_id, 'proxy_client', true);
$payload = is_array($row['payload'] ?? null) ? $row['payload'] : [];
$expected_provider = sanitize_key((string) ($payload['provider'] ?? ''));
$expected_action = (string) ($payload['action'] ?? 'login') === 'bind' ? 'bind' : 'login';
$expected_issuer = (string) ($payload['issuer'] ?? '');
$issuer = OAuthProxyProtocol::issuer($fields['issuer']);
if (!$this->verify_sign($verify_params, $secret, $sign)) {
wp_die(__('代理回调签名验证失败', 'aksrt'));
}
if (
!$row
|| !hash_equals((string) ($payload['request_id'] ?? ''), $request_id)
|| !hash_equals($expected_provider, $provider)
|| !hash_equals($expected_action, $action)
|| $issuer === ''
|| !hash_equals($expected_issuer, $issuer)
|| !OAuthProviderCatalog::is_direct($provider)
|| !in_array($provider, OAuthProviderCatalog::proxy_client_providers(), true)
) {
$this->redirect_error('proxy_response_mismatch', $expected_provider ?: $provider, $expected_action);
}
// 验证时间戳(5分钟内有效)
$ts = (int) ($_GET['ts'] ?? 0);
if (abs(time() - $ts) > 300) {
wp_die(__('代理回调已过期,请重新登录', 'aksrt'));
}
if ($action === 'bind' && (int) ($payload['user_id'] ?? 0) !== get_current_user_id()) {
$this->redirect_error('state_user_mismatch', $provider, $action);
}
// 提取用户数据
$provider_id = sanitize_text_field($_GET['provider_id'] ?? '');
if (empty($provider_id)) {
wp_die(__('代理回调缺少用户标识', 'aksrt'));
}
$jti_scope = 'proxy_client_jti:' . $issuer . ':' . $fields['jti'];
$jti_lock = OAuthTransactionStore::acquire_lock($jti_scope, OAuthProxyProtocol::REPLAY_TTL);
if ($jti_lock === false) {
$this->redirect_error('proxy_replayed', $provider, $action);
}
$user_data = [
'provider' => $provider,
'provider_id' => $provider_id,
'username' => sanitize_user($_GET['username'] ?? '', true),
'name' => sanitize_text_field($_GET['name'] ?? ''),
'email' => sanitize_email($_GET['email'] ?? ''),
'email_verified' => !empty($_GET['email_verified']),
'avatar_url' => esc_url_raw($_GET['avatar_url'] ?? ''),
'bio' => sanitize_text_field($_GET['bio'] ?? ''),
];
if ($action === 'bind') {
$this->handle_proxy_bind($provider, $user_data);
return;
}
$claimed = OAuthTransactionStore::claim($request_id, 'proxy_client', true);
if (!$claimed) {
$this->redirect_error('proxy_replayed', $provider, $action);
}
$this->handle_proxy_login($provider, $user_data);
}
if ($fields['error'] !== '') {
$this->redirect_error($this->public_error($fields['error']), $provider, $action);
}
/**
* 处理代理登录
*/
private function handle_proxy_login(string $provider, array $user_data): void {
$user = $this->find_or_create_user_from_proxy($provider, $user_data);
$identity = $this->identity($provider, $fields);
if ($identity['provider_id'] === '') {
$this->redirect_error('proxy_identity_invalid', $provider, $action);
}
// 未匹配已有账号 → 跳转绑定页
if (is_wp_error($user) && $user->get_error_code() === 'oauth_no_match') {
$error_data = $user->get_error_data();
$obk = 'aksrt_ob_' . wp_generate_password(24, false);
set_transient($obk, [
'provider' => $error_data['provider'],
'provider_id' => $error_data['user_data']['provider_id'] ?? '',
'user_data' => $error_data['user_data'],
'token' => [],
], 15 * MINUTE_IN_SECONDS);
if ($action === 'bind') {
$result = OAuthAccountService::bind(get_current_user_id(), $provider, $identity);
if (is_wp_error($result)) {
$this->redirect_error(
$result->get_error_code() === 'oauth_binding_conflict' ? 'binding_conflict' : 'binding_failed',
$provider,
$action
);
}
$this->redirect_success('bind', $provider, $this->settings_url());
}
$bind_url = aksrt_get_bind_url();
wp_safe_redirect(add_query_arg('obk', $obk, $bind_url));
exit;
}
$user = OAuthAccountService::resolve($provider, $identity);
if (is_wp_error($user) && $user->get_error_code() === 'oauth_no_match') {
try {
$obk = OAuthTransactionStore::issue('obk', [
'provider' => $provider,
'provider_id' => $identity['provider_id'],
'user_data' => $identity,
'redirect_to' => OAuthUrlPolicy::validated_redirect((string) ($payload['redirect_to'] ?? ''), home_url('/')),
], 15 * MINUTE_IN_SECONDS, true);
} catch (\Throwable $e) {
$this->redirect_error('account_match_failed', $provider, $action);
}
$bind_url = function_exists('aksrt_get_bind_url')
? aksrt_get_bind_url($obk)
: home_url('/sign/?tab=bind&obk=' . rawurlencode($obk));
wp_safe_redirect($bind_url);
exit;
}
if (!$user instanceof \WP_User) {
$this->redirect_error('account_match_failed', $provider, $action);
}
if (is_wp_error($user)) {
wp_die(__('登录失败:', 'aksrt') . esc_html($user->get_error_message()));
}
OAuthAccountService::complete_login($user, true);
$this->redirect_success(
'login',
$provider,
OAuthUrlPolicy::validated_redirect((string) ($payload['redirect_to'] ?? ''), home_url('/'))
);
}
// 登录成功
wp_set_auth_cookie($user->ID, true);
$redirect_url = function_exists('aksrt_get_user_center_url') ? aksrt_get_user_center_url() : home_url('/');
wp_safe_redirect(add_query_arg(['oauth_action' => 'login', 'oauth_bound' => $provider], $redirect_url));
exit;
}
private function identity(string $provider, array $fields): array {
return [
'provider' => $provider,
'provider_id' => sanitize_text_field($fields['provider_id']),
'username' => sanitize_text_field($fields['username']),
'name' => sanitize_text_field($fields['name']),
'email' => sanitize_email($fields['email']),
'email_verified' => $fields['email_verified'] === '1',
'avatar_url' => esc_url_raw($fields['avatar_url']),
'url' => esc_url_raw($fields['url']),
'bio' => sanitize_text_field($fields['bio']),
'locale' => sanitize_text_field($fields['locale']),
];
}
/**
* 处理代理绑定(已登录用户绑定第三方账号)
*/
private function handle_proxy_bind(string $provider, array $user_data): void {
$current_uid = get_current_user_id();
if (!$current_uid) {
wp_safe_redirect(aksrt_get_login_url());
exit;
}
private function public_error(string $error): string {
$error = sanitize_key($error);
$allowed = [
'provider_cancelled',
'code_missing',
'provider_unavailable',
'identity_invalid',
'callback_failed',
];
return in_array($error, $allowed, true) ? $error : 'callback_failed';
}
// 检查是否已被其他用户占用
$existing = $this->find_user_by_provider_meta($provider, $user_data['provider_id']);
if ($existing && (int) $existing->ID !== $current_uid) {
wp_die(__('该第三方账号已被其他用户绑定', 'aksrt'));
}
private function settings_url(): string {
return function_exists('aksrt_get_user_center_url') ? aksrt_get_user_center_url('settings') : home_url('/');
}
$this->bind_provider_to_user($current_uid, $provider, $user_data);
private function redirect_success(string $action, string $provider, string $target): void {
wp_safe_redirect(add_query_arg([
'oauth_action' => $action,
'oauth_provider' => sanitize_key($provider),
], $target));
exit;
}
$redirect_url = function_exists('aksrt_get_user_center_url')
? add_query_arg(['oauth_action' => 'bind', 'oauth_bound' => $provider], aksrt_get_user_center_url('settings'))
: home_url('/');
wp_safe_redirect($redirect_url);
exit;
}
/**
* 查找或创建用户(代理模式)
*
* @return \WP_User|\WP_Error
*/
private function find_or_create_user_from_proxy(string $provider, array $user_data) {
$email = $user_data['email'] ?? '';
// 1. 通过 provider_id 查找
if (!empty($user_data['provider_id'])) {
$existing = $this->find_user_by_provider_meta($provider, $user_data['provider_id']);
if ($existing instanceof \WP_User) {
$this->ensure_binding_meta($existing->ID, $provider, $user_data);
return $existing;
}
}
// 2. 通过邮箱查找
if (!empty($email) && is_email($email)) {
$existing = get_user_by('email', $email);
if ($existing && !$existing instanceof \WP_Error) {
$this->ensure_binding_meta($existing->ID, $provider, $user_data);
return $existing;
}
}
// 3. 未匹配
return new \WP_Error('oauth_no_match', __('需要绑定已有账号', 'aksrt'), [
'provider' => $provider,
'user_data' => $user_data,
]);
}
/**
* 确保绑定 meta 存在
*/
private function ensure_binding_meta(int $user_id, string $provider, array $user_data): void {
update_user_meta($user_id, "aksrt_{$provider}_id", $user_data['provider_id'] ?? '');
$bindings = get_user_meta($user_id, 'aksrt_oauth_bindings', true) ?: [];
if (!is_array($bindings)) {
$bindings = [];
}
if (!in_array($provider, $bindings, true)) {
$bindings[] = $provider;
update_user_meta($user_id, 'aksrt_oauth_bindings', $bindings);
}
if (!empty($user_data['avatar_url'])) {
update_user_meta($user_id, 'aksrt_oauth_avatar', esc_url_raw($user_data['avatar_url']));
}
}
/**
* 绑定第三方账号到用户
*/
private function bind_provider_to_user(int $user_id, string $provider, array $user_data): void {
if (!empty($user_data['provider_id'])) {
update_user_meta($user_id, "aksrt_{$provider}_id", $user_data['provider_id']);
}
$bindings = get_user_meta($user_id, 'aksrt_oauth_bindings', true) ?: [];
if (!is_array($bindings)) {
$bindings = [];
}
if (!in_array($provider, $bindings, true)) {
$bindings[] = $provider;
update_user_meta($user_id, 'aksrt_oauth_bindings', $bindings);
}
if (!empty($user_data['avatar_url'])) {
update_user_meta($user_id, 'aksrt_oauth_avatar', esc_url_raw($user_data['avatar_url']));
}
}
/**
* 通过 provider meta 查找用户
*/
private function find_user_by_provider_meta(string $provider, string $provider_id): ?\WP_User {
if (empty($provider_id)) {
return null;
}
$users = get_users([
'meta_key' => "aksrt_{$provider}_id",
'meta_value' => $provider_id,
'number' => 1,
]);
return !empty($users[0]) ? $users[0] : null;
}
/**
* 生成 HMAC-SHA256 签名
*/
private function sign(array $data, string $secret): string {
unset($data['sign']);
ksort($data);
$payload = http_build_query($data);
return hash_hmac('sha256', $payload, $secret);
}
/**
* 验证 HMAC-SHA256 签名
*/
private function verify_sign(array $data, string $secret, string $expected_sign): bool {
$computed = $this->sign($data, $secret);
return hash_equals($computed, $expected_sign);
}
private function redirect_error(string $code, string $provider = '', string $action = 'login'): void {
$target = $action === 'bind' && is_user_logged_in()
? $this->settings_url()
: (function_exists('aksrt_get_login_url') ? aksrt_get_login_url() : wp_login_url());
wp_safe_redirect(add_query_arg([
'oauth_action' => 'error',
'oauth_provider' => sanitize_key($provider),
'oauth_error' => sanitize_key($code),
], $target));
exit;
}
}
+164
View File
@@ -0,0 +1,164 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Auth;
defined('ABSPATH') || exit;
final class OAuthProxyProtocol {
public const VERSION = '2';
public const MAX_CLOCK_SKEW = 300;
public const REPLAY_TTL = 660;
private const REQUEST_DIRECTION = 'request';
private const CALLBACK_DIRECTION = 'callback';
private const REQUEST_FIELDS = [
'v',
'request_id',
'provider',
'action',
'agent_back_url',
'ts',
];
private const CALLBACK_FIELDS = [
'v',
'request_id',
'jti',
'provider',
'action',
'issuer',
'provider_id',
'username',
'name',
'email',
'email_verified',
'avatar_url',
'url',
'bio',
'locale',
'error',
'ts',
];
public static function request_fields(array $source): array {
return self::fields($source, self::REQUEST_FIELDS);
}
public static function callback_fields(array $source): array {
return self::fields($source, self::CALLBACK_FIELDS);
}
public static function sign_request(array $fields, string $secret): string {
return self::sign(self::request_fields($fields), $secret, self::REQUEST_DIRECTION);
}
public static function verify_request(array $fields, string $secret, string $signature): bool {
return self::verify(self::request_fields($fields), $secret, self::REQUEST_DIRECTION, $signature);
}
public static function sign_callback(array $fields, string $secret): string {
return self::sign(self::callback_fields($fields), $secret, self::CALLBACK_DIRECTION);
}
public static function verify_callback(array $fields, string $secret, string $signature): bool {
return self::verify(self::callback_fields($fields), $secret, self::CALLBACK_DIRECTION, $signature);
}
public static function timestamp_valid(string $timestamp): bool {
if (preg_match('/^[0-9]{10}$/', $timestamp) !== 1) {
return false;
}
return abs(time() - (int) $timestamp) <= self::MAX_CLOCK_SKEW;
}
public static function token_valid(string $token): bool {
return preg_match('/^[A-Za-z0-9_-]{32,128}$/', $token) === 1;
}
public static function callback_url(string $url): string {
$url = OAuthUrlPolicy::public_https($url);
if ($url === '') {
return '';
}
$parts = wp_parse_url($url);
$path = rtrim((string) ($parts['path'] ?? ''), '/');
if (!is_array($parts) || !str_ends_with($path, '/oauth/proxy/callback') || isset($parts['query'])) {
return '';
}
$authority = self::authority($parts);
return $authority !== '' ? 'https://' . $authority . $path . '/' : '';
}
public static function server_base_url(string $url): string {
$url = OAuthUrlPolicy::public_https($url);
if ($url === '') {
return '';
}
$parts = wp_parse_url($url);
if (!is_array($parts) || isset($parts['query'])) {
return '';
}
$authority = self::authority($parts);
if ($authority === '') {
return '';
}
$path = rtrim((string) ($parts['path'] ?? ''), '/');
return 'https://' . $authority . $path;
}
public static function issuer(string $url): string {
$url = OAuthUrlPolicy::public_https($url);
$parts = $url !== '' ? wp_parse_url($url) : false;
if (!is_array($parts)) {
return '';
}
$authority = self::authority($parts);
return $authority !== '' ? 'https://' . $authority : '';
}
private static function authority(array $parts): string {
$host = strtolower((string) ($parts['host'] ?? ''));
if ($host === '') {
return '';
}
if (str_contains($host, ':') && $host[0] !== '[') {
$host = '[' . $host . ']';
}
$port = isset($parts['port']) ? ':' . (int) $parts['port'] : '';
return $host . $port;
}
private static function fields(array $source, array $names): array {
$fields = [];
foreach ($names as $name) {
$value = $source[$name] ?? '';
if (!is_scalar($value) && $value !== null) {
$value = '';
}
$fields[$name] = (string) wp_unslash((string) $value);
}
return $fields;
}
private static function sign(array $fields, string $secret, string $direction): string {
if ($secret === '') {
return '';
}
ksort($fields, SORT_STRING);
$payload = http_build_query($fields, '', '&', PHP_QUERY_RFC3986);
$key = hash_hmac('sha256', 'aksrt-oauth-proxy-v2/' . $direction, $secret, true);
return hash_hmac('sha256', $payload, $key);
}
private static function verify(array $fields, string $secret, string $direction, string $signature): bool {
if ($secret === '' || preg_match('/^[a-f0-9]{64}$/i', $signature) !== 1) {
return false;
}
return hash_equals(self::sign($fields, $secret, $direction), strtolower($signature));
}
}
+185 -259
View File
@@ -7,283 +7,209 @@ namespace AKSRT\Auth;
defined('ABSPATH') || exit;
class OAuthProxyServer {
final class OAuthProxyServer {
private static $instance = null;
private static $instance = null;
private OAuthProviderBroker $broker;
public static function get_instance(): self {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public static function get_instance(): self {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {}
private function __construct() {
$this->broker = new OAuthProviderBroker();
}
public function init(): void {
add_action('template_redirect', [$this, 'handle_proxy_routes'], 5);
add_action('init', [$this, 'add_rewrite_rules']);
}
public function init(): void {
add_action('init', [$this, 'add_rewrite_rules']);
add_action('init', [$this, 'maybe_flush_rewrite_rules'], 20);
add_action('template_redirect', [$this, 'handle_proxy_routes'], 5);
}
public function add_rewrite_rules(): void {
add_rewrite_rule('^oauth/proxy/([a-z]+)/?$', 'index.php?aksrt_proxy_provider=$matches[1]', 'top');
add_rewrite_rule('^oauth/proxy/([a-z]+)/callback/?$', 'index.php?aksrt_proxy_provider=$matches[1]&aksrt_proxy_server_callback=1', 'top');
add_filter('query_vars', function ($vars) {
$vars[] = 'aksrt_proxy_provider';
$vars[] = 'aksrt_proxy_server_callback';
return $vars;
});
}
public function add_rewrite_rules(): void {
add_rewrite_rule('^oauth/proxy/([a-z0-9_-]+)/?$', 'index.php?aksrt_proxy_provider=$matches[1]', 'top');
add_rewrite_rule('^oauth/proxy/([a-z0-9_-]+)/callback/?$', 'index.php?aksrt_proxy_provider=$matches[1]&aksrt_proxy_server_callback=1', 'top');
add_filter('query_vars', static function (array $vars): array {
$vars[] = 'aksrt_proxy_provider';
$vars[] = 'aksrt_proxy_server_callback';
return $vars;
});
}
public function handle_proxy_routes(): void {
$provider = sanitize_key(get_query_var('aksrt_proxy_provider'));
if (empty($provider)) return;
public function maybe_flush_rewrite_rules(): void {
$version = defined('AKSRT_VERSION') ? AKSRT_VERSION . ':oauth-proxy-server-v2' : 'oauth-proxy-server-v2';
if (get_option('aksrt_oauth_proxy_server_routes_flushed') !== $version) {
flush_rewrite_rules(false);
update_option('aksrt_oauth_proxy_server_routes_flushed', $version, false);
}
}
if (\AKSRT\Settings\Settings::oauth_proxy_mode() !== 'server') return;
public function handle_proxy_routes(): void {
$provider = sanitize_key((string) get_query_var('aksrt_proxy_provider'));
if ($provider === '') {
return;
}
if (OAuthProviderCatalog::proxy_mode() !== 'server') {
return;
}
if (
!OAuthProviderCatalog::master_enabled()
|| !OAuthProviderCatalog::is_direct($provider)
|| !in_array($provider, OAuthProviderCatalog::proxy_server_providers(), true)
) {
wp_die(esc_html__('不支持的代理登录平台', 'aksrt'), '', ['response' => 403]);
}
$allowed = \AKSRT\Settings\Settings::oauth_proxy_allowed_providers();
if (!in_array($provider, $allowed, true)) {
wp_die(__('不支持的代理登录平台', 'aksrt'));
}
if (get_query_var('aksrt_proxy_server_callback')) {
$this->handle_proxy_callback($provider);
}
$this->handle_proxy_request($provider);
}
$is_callback = !empty(get_query_var('aksrt_proxy_server_callback'));
if ($is_callback) {
$this->handle_proxy_callback($provider);
} else {
$this->handle_proxy_request($provider);
}
}
private function handle_proxy_request(string $route_provider): void {
$secret = OAuthProviderCatalog::proxy_secret();
$fields = OAuthProxyProtocol::request_fields($_GET);
$signature = sanitize_text_field((string) wp_unslash($_GET['sign'] ?? ''));
$request_id = sanitize_text_field($fields['request_id']);
$provider = sanitize_key($fields['provider']);
$action = $fields['action'] === 'bind' ? 'bind' : 'login';
$agent_back_url = OAuthProxyProtocol::callback_url($fields['agent_back_url']);
private function handle_proxy_request(string $provider): void {
$secret = \AKSRT\Settings\Settings::oauth_proxy_secret();
if (empty($secret)) {
wp_die(__('代理登录服务端未配置密钥', 'aksrt'));
}
if (
$secret === ''
|| $fields['v'] !== OAuthProxyProtocol::VERSION
|| !hash_equals($route_provider, $provider)
|| !OAuthProxyProtocol::token_valid($request_id)
|| $agent_back_url === ''
|| !OAuthProxyProtocol::timestamp_valid($fields['ts'])
|| !OAuthProxyProtocol::verify_request($fields, $secret, $signature)
) {
wp_die(esc_html__('代理请求验证失败', 'aksrt'), '', ['response' => 400]);
}
$agent_back_url = esc_url_raw($_GET['agent_back_url'] ?? '');
$sign = sanitize_text_field($_GET['sign'] ?? '');
$action = sanitize_key($_GET['action'] ?? 'login');
$replay_scope = 'proxy_server_request:' . $request_id;
$lock = OAuthTransactionStore::acquire_lock($replay_scope, OAuthProxyProtocol::REPLAY_TTL);
if ($lock === false) {
wp_die(esc_html__('代理请求已使用', 'aksrt'), '', ['response' => 409]);
}
if (empty($agent_back_url) || empty($sign)) {
wp_die(__('代理请求参数不完整', 'aksrt'));
}
$redirect_uri = home_url('/oauth/proxy/' . $provider . '/callback/');
try {
$state = OAuthTransactionStore::issue('proxy_server', [
'request_id' => $request_id,
'provider' => $provider,
'action' => $action,
'agent_back_url' => $agent_back_url,
'redirect_uri' => $redirect_uri,
], OAuthProxyProtocol::REPLAY_TTL, false);
$auth_url = $this->broker->auth_url($provider, $redirect_uri, $state);
if ($auth_url === '') {
throw new \RuntimeException('provider_unavailable');
}
} catch (\Throwable $e) {
$this->redirect_callback($agent_back_url, $this->callback_payload([
'request_id' => $request_id,
'provider' => $provider,
'action' => $action,
'error' => 'provider_unavailable',
]));
}
$verify_params = $_GET;
unset($verify_params['sign']);
if (!$this->verify_sign($verify_params, $secret, $sign)) {
wp_die(__('代理请求签名验证失败', 'aksrt'));
}
wp_redirect($auth_url); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
exit;
}
$ts = (int) ($_GET['ts'] ?? 0);
if (abs(time() - $ts) > 300) {
wp_die(__('代理请求已过期,请重试', 'aksrt'));
}
private function handle_proxy_callback(string $route_provider): void {
$state = sanitize_text_field((string) wp_unslash($_GET['state'] ?? ''));
$row = $state !== '' ? OAuthTransactionStore::claim($state, 'proxy_server', false) : null;
$payload = is_array($row['payload'] ?? null) ? $row['payload'] : [];
$provider = sanitize_key((string) ($payload['provider'] ?? ''));
$action = (string) ($payload['action'] ?? 'login') === 'bind' ? 'bind' : 'login';
$request_id = sanitize_text_field((string) ($payload['request_id'] ?? ''));
$agent_back_url = OAuthProxyProtocol::callback_url((string) ($payload['agent_back_url'] ?? ''));
$redirect_uri = (string) ($payload['redirect_uri'] ?? '');
@session_start();
$_SESSION['aksrt_proxy_agent_back_url'] = $agent_back_url;
$_SESSION['aksrt_proxy_action'] = $action;
$_SESSION['aksrt_proxy_nonce'] = sanitize_text_field($_GET['nonce'] ?? '');
$_SESSION['aksrt_proxy_uid'] = (int) ($_GET['uid'] ?? 0);
if (
!$row
|| !hash_equals($route_provider, $provider)
|| !OAuthProxyProtocol::token_valid($request_id)
|| $agent_back_url === ''
|| $redirect_uri === ''
) {
wp_die(esc_html__('代理回调状态无效', 'aksrt'), '', ['response' => 400]);
}
try {
$oauth = OAuth::get_instance();
$auth_url = $oauth->get_auth_url($provider, $action);
if (empty($auth_url)) {
wp_die(__('无法生成授权链接', 'aksrt'));
}
wp_safe_redirect($auth_url);
exit;
} catch (\Exception $e) {
wp_die(__('代理登录错误:', 'aksrt') . esc_html($e->getMessage()));
}
}
if (!empty($_GET['error'])) {
$this->redirect_callback($agent_back_url, $this->callback_payload([
'request_id' => $request_id,
'provider' => $provider,
'action' => $action,
'error' => 'provider_cancelled',
]));
}
private function handle_proxy_callback(string $provider): void {
@session_start();
$code = sanitize_text_field((string) wp_unslash($_GET['code'] ?? ''));
if ($code === '') {
$this->redirect_callback($agent_back_url, $this->callback_payload([
'request_id' => $request_id,
'provider' => $provider,
'action' => $action,
'error' => 'code_missing',
]));
}
$agent_back_url = $_SESSION['aksrt_proxy_agent_back_url'] ?? '';
if (empty($agent_back_url)) return;
try {
$identity = $this->broker->identity($provider, $code, $redirect_uri, $state);
if (empty($identity['provider_id'])) {
throw new \RuntimeException('identity_invalid');
}
$this->redirect_callback($agent_back_url, $this->callback_payload([
'request_id' => $request_id,
'provider' => $provider,
'action' => $action,
'identity' => $identity,
]));
} catch (\Throwable $e) {
$this->redirect_callback($agent_back_url, $this->callback_payload([
'request_id' => $request_id,
'provider' => $provider,
'action' => $action,
'error' => $e->getMessage() === 'identity_invalid' ? 'identity_invalid' : 'callback_failed',
]));
}
}
$_SESSION['aksrt_proxy_agent_back_url'] = '';
$_SESSION['aksrt_proxy_action'] = '';
$_SESSION['aksrt_proxy_nonce'] = '';
$_SESSION['aksrt_proxy_uid'] = 0;
private function callback_payload(array $context): array {
$identity = is_array($context['identity'] ?? null) ? $context['identity'] : [];
$fields = [
'v' => OAuthProxyProtocol::VERSION,
'request_id' => (string) ($context['request_id'] ?? ''),
'jti' => rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '='),
'provider' => sanitize_key((string) ($context['provider'] ?? '')),
'action' => (string) ($context['action'] ?? 'login') === 'bind' ? 'bind' : 'login',
'issuer' => OAuthProxyProtocol::issuer(home_url('/')),
'provider_id' => sanitize_text_field((string) ($identity['provider_id'] ?? '')),
'username' => sanitize_text_field((string) ($identity['username'] ?? '')),
'name' => sanitize_text_field((string) ($identity['name'] ?? '')),
'email' => sanitize_email((string) ($identity['email'] ?? '')),
'email_verified' => !empty($identity['email_verified']) ? '1' : '0',
'avatar_url' => esc_url_raw((string) ($identity['avatar_url'] ?? '')),
'url' => esc_url_raw((string) ($identity['url'] ?? '')),
'bio' => sanitize_text_field((string) ($identity['bio'] ?? '')),
'locale' => sanitize_text_field((string) ($identity['locale'] ?? '')),
'error' => sanitize_key((string) ($context['error'] ?? '')),
'ts' => (string) time(),
];
$fields['sign'] = OAuthProxyProtocol::sign_callback($fields, OAuthProviderCatalog::proxy_secret());
return $fields;
}
$secret = \AKSRT\Settings\Settings::oauth_proxy_secret();
if (empty($secret)) {
wp_die(__('代理登录服务端配置错误', 'aksrt'));
}
$error = $_GET['error'] ?? '';
if ($error) {
wp_safe_redirect(add_query_arg(['error' => urlencode($error)], $agent_back_url));
exit;
}
$code = sanitize_text_field($_GET['code'] ?? '');
if (empty($code)) {
wp_safe_redirect(add_query_arg(['error' => urlencode('missing_code')], $agent_back_url));
exit;
}
try {
$user_data = $this->fetch_user_data($provider, $code);
if (empty($user_data['provider_id'])) {
wp_safe_redirect(add_query_arg(['error' => urlencode('no_user_info')], $agent_back_url));
exit;
}
$callback_params = [
'provider' => $provider,
'provider_id' => $user_data['provider_id'],
'username' => $user_data['username'] ?? '',
'name' => $user_data['name'] ?? '',
'email' => $user_data['email'] ?? '',
'email_verified' => !empty($user_data['email_verified']) ? '1' : '0',
'avatar_url' => $user_data['avatar_url'] ?? '',
'bio' => $user_data['bio'] ?? '',
'action' => sanitize_key($_SESSION['aksrt_proxy_action'] ?? 'login'),
'ts' => time(),
];
$callback_params['sign'] = $this->sign($callback_params, $secret);
$redirect_url = $agent_back_url . (strpos($agent_back_url, '?') !== false ? '&' : '?') . http_build_query($callback_params);
wp_safe_redirect($redirect_url);
exit;
} catch (\Exception $e) {
wp_safe_redirect(add_query_arg(['error' => urlencode($e->getMessage())], $agent_back_url));
exit;
}
}
/**
* 获取用户数据
*/
private function fetch_user_data(string $provider, string $code): array {
$config = get_option('aksrt_oauth', [])[$provider] ?? [];
if (empty($config['client_id']) || empty($config['client_secret'])) {
throw new \Exception(__('未配置此平台的 OAuth 凭据', 'aksrt'));
}
$redirect_uri = !empty($config['redirect_uri'])
? $config['redirect_uri']
: home_url('/oauth/proxy/' . $provider . '/callback');
switch ($provider) {
case 'github':
$oauth = new \Yurun\OAuthLogin\Github\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$userInfo = $oauth->getUserInfo();
$email = $userInfo['email'] ?? '';
if (empty($email)) {
$emails_json = $oauth->http->header('Authorization', ' token ' . $oauth->accessToken)
->get('https://api.github.com/user/emails')
->body();
$emails = json_decode($emails_json, true) ?: [];
foreach ($emails as $em) {
if (!empty($em['primary']) && !empty($em['email'])) {
$email = $em['email'];
break;
}
}
}
return [
'provider' => 'github',
'provider_id' => (string) ($userInfo['id'] ?? ''),
'username' => $userInfo['login'] ?? '',
'name' => $userInfo['name'] ?? '',
'email' => $email,
'avatar_url' => $userInfo['avatar_url'] ?? '',
'bio' => $userInfo['bio'] ?? '',
];
case 'gitee':
$oauth = new \Yurun\OAuthLogin\Gitee\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$userInfo = $oauth->getUserInfo();
return [
'provider' => 'gitee',
'provider_id' => (string) ($userInfo['id'] ?? ''),
'username' => $userInfo['login'] ?? '',
'name' => $userInfo['name'] ?? '',
'email' => $userInfo['email'] ?? '',
'avatar_url' => $userInfo['avatar_url'] ?? '',
'bio' => $userInfo['bio'] ?? '',
];
case 'qq':
$oauth = new \Yurun\OAuthLogin\QQ\OAuth2(
$config['client_id'],
$config['client_secret'],
$redirect_uri
);
$oauth->getAccessToken($_GET['state'] ?? '', $code, $_GET['state'] ?? null);
$openid = $oauth->getOpenID();
$userInfo = $oauth->getUserInfo();
return [
'provider' => 'qq',
'provider_id' => $openid,
'username' => $userInfo['nickname'] ?? '',
'name' => $userInfo['nickname'] ?? '',
'email' => '',
'avatar_url' => $userInfo['figureurl_qq_2'] ?? $userInfo['figureurl_2'] ?? '',
];
case 'google':
$response = wp_remote_post('https://oauth2.googleapis.com/token', [
'body' => [
'code' => $code,
'client_id' => $config['client_id'],
'client_secret' => $config['client_secret'],
'redirect_uri' => $redirect_uri,
'grant_type' => 'authorization_code',
],
]);
if (is_wp_error($response)) throw new \Exception($response->get_error_message());
$token_data = json_decode(wp_remote_retrieve_body($response), true);
if (empty($token_data['access_token'])) throw new \Exception(__('Google token 获取失败', 'aksrt'));
$user_response = wp_remote_get('https://www.googleapis.com/oauth2/v2/userinfo', [
'headers' => ['Authorization' => 'Bearer ' . $token_data['access_token']],
]);
if (is_wp_error($user_response)) throw new \Exception($user_response->get_error_message());
$user_info = json_decode(wp_remote_retrieve_body($user_response), true);
return [
'provider' => 'google',
'provider_id' => (string) ($user_info['id'] ?? ''),
'username' => $user_info['email'] ?? '',
'name' => $user_info['name'] ?? '',
'email' => $user_info['email'] ?? '',
'avatar_url' => $user_info['picture'] ?? '',
];
default:
throw new \Exception(__('不支持的 OAuth 平台', 'aksrt'));
}
}
private function sign(array $data, string $secret): string {
unset($data['sign']);
ksort($data);
return hash_hmac('sha256', http_build_query($data), $secret);
}
private function verify_sign(array $data, string $secret, string $expected_sign): bool {
return hash_equals($this->sign($data, $secret), $expected_sign);
}
private function redirect_callback(string $agent_back_url, array $fields): void {
$url = add_query_arg($fields, $agent_back_url);
wp_redirect($url); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
exit;
}
}
+208
View File
@@ -0,0 +1,208 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Auth;
defined('ABSPATH') || exit;
final class OAuthTransactionStore {
private const PREFIX = 'aksrt_oauth_tx_';
private const COOKIE = 'aksrt_oauth_browser';
private const LOCK_TTL = 30;
public static function browser_id(): string {
$value = isset($_COOKIE[self::COOKIE]) ? sanitize_text_field(wp_unslash((string) $_COOKIE[self::COOKIE])) : '';
if (preg_match('/^[A-Za-z0-9_-]{32,80}$/', $value) === 1) {
return $value;
}
$value = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
if (!headers_sent()) {
setcookie(self::COOKIE, $value, [
'expires' => time() + MONTH_IN_SECONDS,
'path' => defined('COOKIEPATH') && COOKIEPATH ? COOKIEPATH : '/',
'domain' => defined('COOKIE_DOMAIN') ? COOKIE_DOMAIN : '',
'secure' => is_ssl(),
'httponly' => true,
'samesite' => 'Lax',
]);
}
$_COOKIE[self::COOKIE] = $value;
return $value;
}
public static function issue(string $kind, array $payload, int $ttl = 600, bool $bind_browser = true): string {
$token = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
$key = self::key($token);
$row = [
'kind' => sanitize_key($kind),
'payload' => $payload,
'browser_hash' => $bind_browser ? hash('sha256', self::browser_id()) : '',
'created_at' => time(),
'expires_at' => time() + max(30, $ttl),
'claimed_at' => 0,
];
if (!add_option($key, $row, '', false)) {
throw new \RuntimeException('oauth_transaction_issue_failed');
}
return $token;
}
public static function peek(string $token, string $kind = '', bool $require_browser = true): ?array {
$key = self::key($token);
$row = get_option($key, null);
if (is_array($row) && (int) ($row['expires_at'] ?? 0) < time()) {
delete_option($key);
return null;
}
if (!self::valid_row($row, $kind, $require_browser)) {
return null;
}
return $row;
}
public static function claim(string $token, string $kind = '', bool $require_browser = true): ?array {
global $wpdb;
$key = self::key($token);
$row = get_option($key, null);
if (is_array($row) && (int) ($row['expires_at'] ?? 0) < time()) {
delete_option($key);
return null;
}
if (!self::valid_row($row, $kind, $require_browser)) {
return null;
}
$serialized = maybe_serialize($row);
$row['claimed_at'] = time();
$deleted = $wpdb->query($wpdb->prepare(
"DELETE FROM {$wpdb->options} WHERE option_name = %s AND option_value = %s",
$key,
$serialized
));
if ($deleted !== 1) {
return null;
}
wp_cache_delete($key, 'options');
return $row;
}
public static function update(string $token, string $kind, callable $mutator, bool $require_browser = false): bool {
global $wpdb;
$key = self::key($token);
$current = get_option($key, null);
if (is_array($current) && (int) ($current['expires_at'] ?? 0) < time()) {
delete_option($key);
return false;
}
if (!self::valid_row($current, $kind, $require_browser)) {
return false;
}
$next = $mutator($current);
if (!is_array($next)) {
return false;
}
$updated = $wpdb->query($wpdb->prepare(
"UPDATE {$wpdb->options} SET option_value = %s WHERE option_name = %s AND option_value = %s",
maybe_serialize($next),
$key,
maybe_serialize($current)
));
if ($updated === 1) {
wp_cache_delete($key, 'options');
return true;
}
return false;
}
public static function delete(string $token): void {
delete_option(self::key($token));
}
public static function acquire_lock(string $scope, int $ttl = self::LOCK_TTL) {
$key = self::lock_key($scope);
$token = wp_generate_uuid4();
$value = ['token' => $token, 'expires_at' => time() + max(5, $ttl)];
if (add_option($key, $value, '', false)) {
return $token;
}
$current = get_option($key, null);
if (!is_array($current) || (int) ($current['expires_at'] ?? 0) >= time()) {
return false;
}
global $wpdb;
$updated = $wpdb->query($wpdb->prepare(
"UPDATE {$wpdb->options} SET option_value = %s WHERE option_name = %s AND option_value = %s",
maybe_serialize($value),
$key,
maybe_serialize($current)
));
if ($updated === 1) {
wp_cache_delete($key, 'options');
return $token;
}
return false;
}
public static function release_lock(string $scope, string $token): void {
global $wpdb;
$key = self::lock_key($scope);
$current = get_option($key, null);
if (!is_array($current) || !hash_equals((string) ($current['token'] ?? ''), $token)) {
return;
}
$deleted = $wpdb->query($wpdb->prepare(
"DELETE FROM {$wpdb->options} WHERE option_name = %s AND option_value = %s",
$key,
maybe_serialize($current)
));
if ($deleted === 1) {
wp_cache_delete($key, 'options');
}
}
public static function cleanup(int $limit = 200): int {
global $wpdb;
$rows = $wpdb->get_results($wpdb->prepare(
"SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s LIMIT %d",
$wpdb->esc_like(self::PREFIX) . '%',
max(1, min(1000, $limit))
), ARRAY_A);
$removed = 0;
foreach (is_array($rows) ? $rows : [] as $row) {
$value = maybe_unserialize($row['option_value'] ?? '');
if (!is_array($value) || (int) ($value['expires_at'] ?? 0) >= time()) {
continue;
}
if (delete_option((string) $row['option_name'])) {
$removed++;
}
}
return $removed;
}
private static function valid_row($row, string $kind, bool $require_browser): bool {
if (!is_array($row) || (int) ($row['expires_at'] ?? 0) < time()) {
return false;
}
if ($kind !== '' && !hash_equals(sanitize_key($kind), (string) ($row['kind'] ?? ''))) {
return false;
}
if ($require_browser) {
$expected = (string) ($row['browser_hash'] ?? '');
if ($expected === '' || !hash_equals($expected, hash('sha256', self::browser_id()))) {
return false;
}
}
return true;
}
private static function key(string $token): string {
return self::PREFIX . hash('sha256', trim($token));
}
private static function lock_key(string $scope): string {
return self::PREFIX . 'lock_' . hash('sha256', $scope);
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
/**
* @package AKSRT
*/
namespace AKSRT\Auth;
defined('ABSPATH') || exit;
final class OAuthUrlPolicy {
public static function public_https(string $url, string $required_path = ''): string {
$url = esc_url_raw(trim($url));
$parts = wp_parse_url($url);
if (!is_array($parts) || strtolower((string) ($parts['scheme'] ?? '')) !== 'https') {
return '';
}
if (!empty($parts['user']) || !empty($parts['pass']) || !empty($parts['fragment'])) {
return '';
}
$host = strtolower((string) ($parts['host'] ?? ''));
if ($host === '' || $host === 'localhost' || str_ends_with($host, '.localhost')) {
return '';
}
if ($required_path !== '' && rtrim((string) ($parts['path'] ?? ''), '/') !== rtrim($required_path, '/')) {
return '';
}
if (!self::host_is_public($host)) {
return '';
}
return $url;
}
private static function host_is_public(string $host): bool {
$addresses = [];
if (filter_var($host, FILTER_VALIDATE_IP)) {
$addresses[] = $host;
} elseif (function_exists('dns_get_record')) {
$records = @dns_get_record($host, DNS_A | DNS_AAAA);
foreach (is_array($records) ? $records : [] as $record) {
$address = (string) ($record['ip'] ?? $record['ipv6'] ?? '');
if ($address !== '') {
$addresses[] = $address;
}
}
} elseif (function_exists('gethostbynamel')) {
$resolved = @gethostbynamel($host);
$addresses = is_array($resolved) ? $resolved : [];
}
if ($addresses === []) {
return false;
}
foreach ($addresses as $address) {
if (filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
return false;
}
}
return true;
}
public static function validated_redirect(string $url, string $fallback = ''): string {
$fallback = $fallback !== '' ? $fallback : home_url('/');
return wp_validate_redirect(wp_unslash($url), $fallback);
}
}
+19 -9
View File
@@ -20,20 +20,26 @@ final class Service {
return null;
}
$data = get_transient($obk);
$row = OAuthTransactionStore::peek($obk, 'obk');
$data = is_array($row['payload'] ?? null) ? $row['payload'] : null;
return is_array($data) ? $data : null;
}
public static function get_oauth_provider_name(string $provider): string {
$provider_names = [
'github' => 'GitHub',
'gitee' => 'Gitee',
'qq' => 'QQ',
'google' => 'Google',
];
public static function claim_oauth_bind_context(string $obk): ?array {
$obk = sanitize_text_field($obk);
$row = $obk !== '' ? OAuthTransactionStore::claim($obk, 'obk') : null;
$data = is_array($row['payload'] ?? null) ? $row['payload'] : null;
if (!is_array($data)) {
return null;
}
$data['_oauth_claimed'] = true;
return $data;
}
public static function get_oauth_provider_name(string $provider): string {
$provider = sanitize_key($provider);
return $provider_names[$provider] ?? ucfirst($provider);
return OAuthProviderCatalog::label($provider);
}
public static function resolve_email_to_username(string $login): string {
@@ -87,6 +93,10 @@ final class Service {
return sprintf(__('登录失败:%s', 'aksrt'), wp_strip_all_tags($raw_message));
}
public static function mark_verified_email(int $user_id): void {
self::mark_email_verified($user_id);
}
public static function validate_password(string $password, string $confirm = '') {
if ($password === '') {
return __('请输入密码', 'aksrt');
+29 -26
View File
@@ -143,9 +143,18 @@ trait ServicePart1a {
return ['success' => false, 'error' => __('注册成功,但读取用户信息失败,请联系管理员', 'aksrt')];
}
self::mark_email_verified($user_id);
wp_set_auth_cookie((int) $user_id, true);
do_action('wp_login', $user->user_login, $user);
if (
empty($post['_defer_login'])
&& !empty($post['_auth_code_verified'])
&& class_exists('\AKSRT\Settings\Settings')
&& \AKSRT\Settings\Settings::signup_verification_enabled()
) {
self::mark_email_verified($user_id);
}
if (empty($post['_defer_login'])) {
wp_set_auth_cookie((int) $user_id, true);
do_action('wp_login', $user->user_login, $user);
}
return [
'success' => true,
'user_id' => (int) $user_id,
@@ -156,35 +165,29 @@ trait ServicePart1a {
];
}
public static function finalize_oauth_binding(int $user_id, array $oauth_data, string $obk = ''): void {
if ($user_id <= 0) {
return;
public static function finalize_oauth_binding(int $user_id, array $oauth_data, string $obk = '') {
if ($user_id <= 0 || $obk === '') {
return new \WP_Error('oauth_binding_invalid', __('绑定会话无效', 'aksrt'));
}
$provider = sanitize_key((string) ($oauth_data['provider'] ?? ''));
if ($provider === '') {
return;
$payload = $oauth_data;
if (empty($payload['_oauth_claimed'])) {
$row = OAuthTransactionStore::claim(sanitize_text_field($obk), 'obk');
$payload = is_array($row['payload'] ?? null) ? $row['payload'] : [];
if (!$row || $payload === []) {
return new \WP_Error('oauth_binding_consumed', __('绑定会话已过期或已使用,请重新授权', 'aksrt'));
}
}
update_user_meta($user_id, "aksrt_{$provider}_id", $oauth_data['provider_id'] ?? '');
$bindings = get_user_meta($user_id, 'aksrt_oauth_bindings', true);
$bindings = is_array($bindings) ? $bindings : [];
if (!in_array($provider, $bindings, true)) {
$bindings[] = $provider;
unset($payload['_oauth_claimed']);
$provider = sanitize_key((string) ($payload['provider'] ?? ''));
$identity = is_array($payload['user_data'] ?? null) ? $payload['user_data'] : [];
if ($provider === '' || empty($identity['provider_id'])) {
return new \WP_Error('oauth_binding_invalid', __('第三方账号信息无效', 'aksrt'));
}
update_user_meta($user_id, 'aksrt_oauth_bindings', array_values($bindings));
if (!empty($oauth_data['user_data']['avatar_url'])) {
update_user_meta($user_id, 'aksrt_oauth_avatar', esc_url_raw($oauth_data['user_data']['avatar_url']));
}
if ($obk !== '') {
delete_transient(sanitize_text_field($obk));
}
wp_set_auth_cookie($user_id, true);
return OAuthAccountService::bind($user_id, $provider, $identity);
}
private static function mark_email_verified(int $user_id): void {
update_user_meta($user_id, self::EMAIL_VERIFIED_META, '1');
do_action('aksrt_email_verified', $user_id);
+6 -6
View File
@@ -109,14 +109,14 @@ trait ServicePart1b {
update_user_meta($user_id, 'aksrt_phone', $phone);
update_user_meta($user_id, 'aksrt_phone_verified', '1');
self::mark_email_verified((int) $user_id);
// 自动登录
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id, true);
$user = get_userdata($user_id);
if ($user instanceof \WP_User) {
do_action('wp_login', $user->user_login, $user);
if (empty($post['_defer_login'])) {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id, true);
if ($user instanceof \WP_User) {
do_action('wp_login', $user->user_login, $user);
}
}
$redirect = function_exists('aksrt_get_user_center_url')
+785 -400
View File
File diff suppressed because it is too large Load Diff
+6 -1
View File
@@ -56,7 +56,12 @@ trait AuthReader {
return (bool) self::get_value('close_signup', false) || self::close_signin();
}
/** 是否关闭账密登录(仅允许社交登录) */
/** OAuth 辅助注册只受总开关和明确的注册开关控制。 */
public static function oauth_registration_enabled(): bool {
return !self::close_sign() && !(bool) self::get_value('close_signup', false);
}
/** 是否关闭账密登录(仅允许社交登录) */
public static function close_signin(): bool {
if (self::close_sign()) return true;
return (bool) self::get_value('close_signin', false);
+22 -154
View File
@@ -9,160 +9,28 @@ defined('ABSPATH') || exit;
class Integration {
/** 获取OAuth配置 */
public static function get_oauth(): array {
return get_option('aksrt_oauth', []);
}
/** 检查OAuth平台是否已配置 */
public static function oauth_configured(string $provider): bool {
$oauth = self::get_oauth();
return !empty($oauth[$provider]['client_id']) && !empty($oauth[$provider]['client_secret']);
}
/** OAuth 代理登录模式: 'off' | 'server' | 'client' (schema 存 'close'→映射为 'off') */
public static function oauth_proxy_mode(): string {
$settings = Settings::get_all();
$mode = sanitize_key((string) ($settings['oauth_proxy_mode'] ?? ''));
if ($mode === '') {
$oauth = self::get_oauth();
$mode = $oauth['proxy']['mode'] ?? (!empty($settings['oauth_agent']) ? 'client' : 'off');
}
if ($mode === 'close') {
$mode = 'off';
}
return in_array($mode, ['off', 'server', 'client'], true) ? $mode : 'off';
}
/** OAuth 代理登录 HMAC 密钥 */
public static function oauth_proxy_secret(): string {
$settings = Settings::get_all();
if (!empty($settings['oauth_proxy_secret'])) {
return (string) $settings['oauth_proxy_secret'];
}
$oauth = self::get_oauth();
return (string) ($oauth['proxy']['secret'] ?? '');
}
/** OAuth 代理登录服务端地址(客户端模式使用) */
public static function oauth_proxy_server_url(): string {
$settings = Settings::get_all();
if (!empty($settings['oauth_proxy_server_url'])) {
return esc_url_raw((string) $settings['oauth_proxy_server_url']);
}
$oauth = self::get_oauth();
return esc_url_raw((string) ($oauth['proxy']['server_url'] ?? ''));
}
/** OAuth 代理登录允许的平台列表(服务端模式使用) */
public static function oauth_proxy_allowed_providers(): array {
$settings = Settings::get_all();
$valid = ['github', 'gitee', 'qq', 'google', 'weibo', 'weixin', 'baidu', 'alipay'];
if (isset($settings['oauth_proxy_server_providers']) && is_array($settings['oauth_proxy_server_providers'])) {
return array_values(array_intersect($settings['oauth_proxy_server_providers'], $valid));
}
$oauth = self::get_oauth();
$allowed = $oauth['proxy']['allowed_providers'] ?? ['github', 'gitee', 'qq', 'google'];
return array_values(array_intersect($allowed, $valid));
}
/** OAuth 代理登录启用的平台列表(客户端模式使用) */
public static function oauth_proxy_client_providers(): array {
$settings = Settings::get_all();
$valid = ['github', 'gitee', 'qq', 'google', 'weibo', 'weixin', 'baidu', 'alipay'];
if (isset($settings['oauth_proxy_client_providers']) && is_array($settings['oauth_proxy_client_providers'])) {
return array_values(array_intersect($settings['oauth_proxy_client_providers'], $valid));
}
$oauth = self::get_oauth();
$enabled = $oauth['proxy']['client_providers'] ?? ['github', 'gitee', 'qq', 'google'];
return array_values(array_intersect($enabled, $valid));
}
/**
* 获取微信公众号登录完整配置
*
* @return array{gzh_type:string,token:string,token_nocheck:bool,encoding_aes_key:string,appid:string,appsecret:string,code_qrcode:string,code_keyword:string,code_reply:string,code_subscribe_reply:string,subscribe_msg:string,new_subscribe_msg:string,scan_msg:string,auto_reply_text:string,auto_reply_search:string,auto_reply_image:string,auto_reply_voice:string,auto_reply_default:string,gzh_menu:string,priority:bool,auto:bool,auto_expires:int}
*/
public static function get_weixingzh_settings(): array {
$settings = Settings::get_all();
$gzh_type = sanitize_key((string) ($settings['weixingzh_gzh_type'] ?? 'service'));
if (!in_array($gzh_type, ['service', 'subscribe'], true)) {
$gzh_type = 'service';
}
$auto_expires = max(0, min(86400, (int) ($settings['weixingzh_auto_expires'] ?? 3600)));
return [
'gzh_type' => $gzh_type,
'token' => (string) ($settings['weixingzh_token'] ?? ''),
'token_nocheck' => !empty($settings['weixingzh_token_nocheck']),
'encoding_aes_key' => (string) ($settings['weixingzh_encoding_aes_key'] ?? ''),
'appid' => (string) ($settings['weixingzh_appid'] ?? ''),
'appsecret' => (string) ($settings['weixingzh_appsecret'] ?? ''),
'code_qrcode' => (string) ($settings['weixingzh_code_qrcode'] ?? ''),
'code_keyword' => (string) ($settings['weixingzh_code_keyword'] ?? '登录'),
'code_reply' => (string) ($settings['weixingzh_code_reply'] ?? ''),
'code_subscribe_reply' => (string) ($settings['weixingzh_code_subscribe_reply'] ?? ''),
'subscribe_msg' => (string) ($settings['weixingzh_subscribe_msg'] ?? ''),
'new_subscribe_msg' => (string) ($settings['weixingzh_new_subscribe_msg'] ?? ''),
'scan_msg' => (string) ($settings['weixingzh_scan_msg'] ?? ''),
'auto_reply_text' => (string) ($settings['weixingzh_auto_reply_text'] ?? ''),
'auto_reply_search' => (string) ($settings['weixingzh_auto_reply_search'] ?? ''),
'auto_reply_image' => (string) ($settings['weixingzh_auto_reply_image'] ?? ''),
'auto_reply_voice' => (string) ($settings['weixingzh_auto_reply_voice'] ?? ''),
'auto_reply_default' => (string) ($settings['weixingzh_auto_reply_default'] ?? ''),
'gzh_menu' => (string) ($settings['weixingzh_gzh_menu'] ?? ''),
'priority' => !empty($settings['weixingzh_priority']),
'auto' => !empty($settings['weixingzh_auto']),
'auto_expires' => $auto_expires,
];
}
/**
* 获取 OAuth 代理登录完整配置(aksrt_settings 优先,BC fallback aksrt_oauth)
*
* @return array{mode:string,secret:string,server_url:string,server_providers:array,client_providers:array,gzh_type:string}
*/
public static function get_oauth_proxy_settings(): array {
$settings = Settings::get_all();
$oauth = self::get_oauth();
$mode = sanitize_key((string) ($settings['oauth_proxy_mode'] ?? ''));
if ($mode === '') {
$mode = $oauth['proxy']['mode'] ?? (!empty($settings['oauth_agent']) ? 'client' : 'close');
}
if (!in_array($mode, ['close', 'server', 'client'], true)) {
$mode = 'close';
}
$secret = (string) ($settings['oauth_proxy_secret'] ?? ($oauth['proxy']['secret'] ?? ''));
$server_url = esc_url_raw((string) ($settings['oauth_proxy_server_url'] ?? ($oauth['proxy']['server_url'] ?? '')));
$valid_providers = ['github', 'gitee', 'qq', 'google', 'weibo', 'weixin', 'baidu', 'alipay'];
$server_providers = array_values(array_intersect(
(array) ($settings['oauth_proxy_server_providers'] ?? ($oauth['proxy']['allowed_providers'] ?? ['github', 'gitee', 'qq', 'google'])),
$valid_providers
));
$client_providers = array_values(array_intersect(
(array) ($settings['oauth_proxy_client_providers'] ?? ($oauth['proxy']['client_providers'] ?? ['github', 'gitee', 'qq', 'google'])),
$valid_providers
));
$gzh_type = sanitize_key((string) ($settings['oauth_proxy_gzh_type'] ?? 'service'));
if (!in_array($gzh_type, ['service', 'subscribe'], true)) {
$gzh_type = 'service';
}
return [
'mode' => $mode,
'secret' => $secret,
'server_url' => $server_url,
'server_providers' => $server_providers,
'client_providers' => $client_providers,
'gzh_type' => $gzh_type,
];
}
/**
* 获取微信公众号登录完整配置。
*/
public static function get_weixingzh_settings(): array {
$settings = Settings::get_all();
$gzh_type = sanitize_key((string) ($settings['weixingzh_gzh_type'] ?? 'service'));
if (!in_array($gzh_type, ['service', 'subscribe'], true)) {
$gzh_type = 'service';
}
return [
'gzh_type' => $gzh_type,
'token' => (string) ($settings['weixingzh_token'] ?? ''),
'appid' => (string) ($settings['weixingzh_appid'] ?? ''),
'appsecret' => (string) ($settings['weixingzh_appsecret'] ?? ''),
'code_qrcode' => (string) ($settings['weixingzh_code_qrcode'] ?? ''),
'code_keyword' => (string) ($settings['weixingzh_code_keyword'] ?? '登录'),
'code_reply' => (string) ($settings['weixingzh_code_reply'] ?? ''),
'subscribe_msg' => (string) ($settings['weixingzh_subscribe_msg'] ?? ''),
'scan_msg' => (string) ($settings['weixingzh_scan_msg'] ?? ''),
'priority' => !empty($settings['weixingzh_priority']),
];
}
/**
* 获取底部Tab完整配置
+4 -74
View File
@@ -35,7 +35,6 @@ class Settings {
*/
public const STANDALONE_OPTION_KEYS = [
'aksrt_mail_smtp',
'aksrt_oauth',
'aksrt_captcha_config',
'aksrt_moderation_config',
'aksrt_download_config',
@@ -53,7 +52,6 @@ class Settings {
*/
public const SECRET_OPTION_KEYS = [
'aksrt_mail_smtp',
'aksrt_oauth',
'aksrt_identity_secrets',
];
@@ -730,78 +728,10 @@ class Settings {
DisplayRuntime::save_friend_links($links);
}
/** 获取OAuth配置 */
public static function get_oauth(): array {
return Integration::get_oauth();
}
/** 检查OAuth平台是否已配置 */
public static function oauth_configured(string $provider): bool {
return Integration::oauth_configured($provider);
}
// ============================================
// OAuth 代理登录 & 自动创建用户
// ============================================
/** OAuth 代理登录模式: 'off' | 'server' | 'client' (schema 存 'close'→映射为 'off') */
public static function oauth_proxy_mode(): string {
return Integration::oauth_proxy_mode();
}
/** OAuth 代理登录 HMAC 密钥 */
public static function oauth_proxy_secret(): string {
return Integration::oauth_proxy_secret();
}
/** OAuth 代理登录服务端地址(客户端模式使用) */
public static function oauth_proxy_server_url(): string {
return Integration::oauth_proxy_server_url();
}
/** OAuth 代理登录允许的平台列表(服务端模式使用) */
public static function oauth_proxy_allowed_providers(): array {
return Integration::oauth_proxy_allowed_providers();
}
/** OAuth 代理登录启用的平台列表(客户端模式使用) */
public static function oauth_proxy_client_providers(): array {
return Integration::oauth_proxy_client_providers();
}
/**
* 获取微信公众号登录完整配置
*
* @return array{gzh_type:string,token:string,token_nocheck:bool,encoding_aes_key:string,appid:string,appsecret:string,code_qrcode:string,code_keyword:string,code_reply:string,code_subscribe_reply:string,subscribe_msg:string,new_subscribe_msg:string,scan_msg:string,auto_reply_text:string,auto_reply_search:string,auto_reply_image:string,auto_reply_voice:string,auto_reply_default:string,gzh_menu:string,priority:bool,auto:bool,auto_expires:int}
*/
public static function get_weixingzh_settings(): array {
return Integration::get_weixingzh_settings();
}
/**
* 获取 OAuth 代理登录完整配置(aksrt_settings 优先,BC fallback aksrt_oauth)
*
* @return array{mode:string,secret:string,server_url:string,server_providers:array,client_providers:array,gzh_type:string}
*/
public static function get_oauth_proxy_settings(): array {
return Integration::get_oauth_proxy_settings();
}
/** 获取微信公众号登录完整配置。 */
public static function get_weixingzh_settings(): array {
return Integration::get_weixingzh_settings();
}