Merge pull request '优化了一些问题' (#13) from worktree/oauth-hard-cut into main
Reviewed-on: #13
This commit was merged in pull request #13.
This commit is contained in:
@@ -25,6 +25,8 @@
|
||||
!/tests/widget-system/page-display-save-harness.php
|
||||
!/tests/widget-system/admin-ui-contract.test.cjs
|
||||
!/tests/widget-system/auth-source-contract.test.cjs
|
||||
!/tests/widget-system/oauth-security-contract.test.cjs
|
||||
!/tests/widget-system/oauth-security-harness.php
|
||||
!/tests/widget-system/user-badges-contract.test.cjs
|
||||
!/tests/widget-system/user-features-contract.test.cjs
|
||||
!/tests/widget-system/zibll-modern-widgets-contract.test.cjs
|
||||
|
||||
@@ -210,17 +210,29 @@ WordPress 后台左侧 **Admin Bar** → ⚡ **AKSRT 主题设置**
|
||||
|
||||
### 支持的平台
|
||||
|
||||
GitHub | Gitee | QQ | Google
|
||||
:---:|:---:|:---:|:---:
|
||||
✅ | ✅ | ✅ | ✅
|
||||
GitHub | Gitee | QQ | Google | 微博 | 微信开放平台 | 微信公众号
|
||||
:---:|:---:|:---:|:---:|:---:|:---:|:---:
|
||||
✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅
|
||||
|
||||
### 回调地址格式
|
||||
|
||||
直连 OAuth:
|
||||
|
||||
```
|
||||
https://你的域名.com/?aksrt_oauth_callback={provider}
|
||||
https://你的域名.com/oauth/callback/
|
||||
```
|
||||
|
||||
`{provider}`: `github` / `gitee` / `qq` / `google`
|
||||
代理服务端按平台配置:
|
||||
|
||||
```
|
||||
https://代理服务端域名.com/oauth/proxy/{provider}/callback/
|
||||
```
|
||||
|
||||
彩虹聚合登录:
|
||||
|
||||
```
|
||||
https://你的域名.com/oauth/clogin/callback/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -6,9 +6,6 @@ export const usersApiMethods = {
|
||||
getAuthSettings() { return this.request('/settings/auth') },
|
||||
saveAuthSettings(data) { return this.request('/settings/auth', { method: 'POST', body: JSON.stringify(data) }) },
|
||||
|
||||
getOAuthSettings() { return this.request('/settings/oauth') },
|
||||
saveOAuthSettings(data) { return this.request('/settings/oauth', { method: 'POST', body: JSON.stringify(data) }) },
|
||||
|
||||
getNotificationSettings() { return this.request('/settings/notifications') },
|
||||
saveNotificationSettings(data) { return this.request('/settings/notifications', { method: 'POST', body: JSON.stringify(data) }) },
|
||||
getNotificationOverview(params = {}) {
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
<template>
|
||||
<n-card class="oauth-provider-card" title="">
|
||||
<!-- 平台信息头部 -->
|
||||
<div class="oauth-provider-header">
|
||||
<div class="oauth-header-left">
|
||||
<span class="oauth-platform-icon">
|
||||
<img v-if="icon" :src="icon" :alt="name" class="oauth-platform-img" />
|
||||
<span v-else class="oauth-platform-text">{{ name.charAt(0) }}</span>
|
||||
</span>
|
||||
<div class="oauth-platform-info">
|
||||
<h4>{{ name }}</h4>
|
||||
<a :href="docUrl" target="_blank" class="oauth-doc-link">
|
||||
前往 {{ name }} 创建应用 ↗
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<n-switch v-model:value="modelValue.enabled" class="oauth-enable-switch">
|
||||
<template #checked>启用</template>
|
||||
<template #unchecked>停用</template>
|
||||
</n-switch>
|
||||
</div>
|
||||
|
||||
<!-- 表单区域(启用后才展开) -->
|
||||
<div v-if="modelValue.enabled" class="oauth-form-body">
|
||||
<n-form label-placement="top" class="aksrt-form oauth-form-grid">
|
||||
<n-form-item
|
||||
v-for="field in fields"
|
||||
:key="field.key"
|
||||
:label="field.label"
|
||||
>
|
||||
<n-input
|
||||
v-if="!field.readonly"
|
||||
v-model:value="modelValue[field.key]"
|
||||
:type="field.secret ? 'password' : 'text'"
|
||||
:show-password-on-click="field.secret"
|
||||
:placeholder="'输入 ' + field.label"
|
||||
size="large"
|
||||
/>
|
||||
<n-input
|
||||
v-else
|
||||
:value="callbackUrl"
|
||||
readonly
|
||||
size="large"
|
||||
style='font-family: "SF Mono", Consolas, monospace; font-size:13px;'
|
||||
/>
|
||||
<template v-if="field.hint" #feedback>
|
||||
<span class="aksrt-hint-text">{{ field.hint }}</span>
|
||||
</template>
|
||||
<template v-if="field.readonly && !field.hint" #feedback>
|
||||
<span class="aksrt-hint-text">将此地址填写到对应平台的「授权回调域 / 回调 URL」中</span>
|
||||
</template>
|
||||
</n-form-item>
|
||||
</n-form>
|
||||
</div>
|
||||
|
||||
<!-- 未启用时的提示 -->
|
||||
<div v-else class="oauth-disabled-hint">
|
||||
<p>开启开关以配置此平台的 OAuth 凭证</p>
|
||||
</div>
|
||||
</n-card>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
modelValue: { type: Object, required: true },
|
||||
name: { type: String, required: true },
|
||||
docUrl: { type: String, required: true },
|
||||
fields: { type: Array, required: true },
|
||||
icon: { type: String, default: '' },
|
||||
})
|
||||
|
||||
defineEmits(['update:modelValue'])
|
||||
|
||||
const callbackUrl = computed(() => {
|
||||
const siteUrl = window.aksrtAdminData?.siteUrl || window.location.origin
|
||||
return `${siteUrl}/oauth/callback/`
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.oauth-provider-card {
|
||||
border-radius: 12px !important;
|
||||
}
|
||||
|
||||
/* 平台头部 */
|
||||
.oauth-provider-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding-bottom: 20px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.oauth-header-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.oauth-platform-icon {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--aksrt-color-canvas);
|
||||
border-radius: 12px;
|
||||
}
|
||||
|
||||
.oauth-platform-img {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.oauth-platform-text {
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
color: var(--aksrt-color-muted);
|
||||
}
|
||||
|
||||
.oauth-platform-info h4 {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--aksrt-color-text);
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.oauth-doc-link {
|
||||
font-size: 12px;
|
||||
color: var(--aksrt-color-primary);
|
||||
text-decoration: none;
|
||||
}
|
||||
.oauth-doc-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* 启用开关 */
|
||||
.oauth-enable-switch {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* 表单体 */
|
||||
.oauth-form-body {
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid var(--aksrt-color-border);
|
||||
}
|
||||
|
||||
.oauth-form-grid :deep(.n-form-item) {
|
||||
max-width: 520px;
|
||||
}
|
||||
|
||||
/* 禁用提示 */
|
||||
.oauth-disabled-hint {
|
||||
text-align: center;
|
||||
padding: 28px 0 10px;
|
||||
}
|
||||
.oauth-disabled-hint p {
|
||||
font-size: 13px;
|
||||
color: var(--aksrt-color-border-strong);
|
||||
}
|
||||
</style>
|
||||
@@ -25,17 +25,28 @@
|
||||
/>
|
||||
|
||||
<!-- Input (text, email, url, password) -->
|
||||
<n-input
|
||||
v-else-if="schema.type === 'input' || schema.type === 'text' || schema.type === 'url'"
|
||||
:value="modelValue"
|
||||
:placeholder="schema.placeholder || ''"
|
||||
:type="schema.inputType || 'text'"
|
||||
:disabled="schema.disabled"
|
||||
@update:value="emit('update:modelValue', $event)"
|
||||
>
|
||||
<template v-if="schema.prefix" #prefix>{{ schema.prefix }}</template>
|
||||
<template v-if="schema.suffix" #suffix>{{ schema.suffix }}</template>
|
||||
</n-input>
|
||||
<div v-else-if="schema.type === 'input' || schema.type === 'text' || schema.type === 'url'" class="aksrt-field__input-wrap">
|
||||
<n-input
|
||||
:value="secretDisplayValue"
|
||||
:placeholder="schema.placeholder || ''"
|
||||
:type="schema.inputType || 'text'"
|
||||
:disabled="schema.disabled"
|
||||
@update:value="emit('update:modelValue', $event)"
|
||||
>
|
||||
<template v-if="schema.prefix" #prefix>{{ schema.prefix }}</template>
|
||||
<template v-if="schema.suffix" #suffix>{{ schema.suffix }}</template>
|
||||
</n-input>
|
||||
<n-button
|
||||
v-if="schema.secret && (modelValue === '***' || secretMarkedForClear)"
|
||||
size="small"
|
||||
secondary
|
||||
:type="secretMarkedForClear ? 'warning' : 'error'"
|
||||
@click="toggleSecretClear"
|
||||
>
|
||||
{{ secretMarkedForClear ? '取消清除' : '清除已配置密钥' }}
|
||||
</n-button>
|
||||
<span v-if="secretMarkedForClear" class="aksrt-field__secret-clear-hint">保存后将删除此密钥</span>
|
||||
</div>
|
||||
|
||||
<!-- Textarea -->
|
||||
<n-input
|
||||
@@ -636,6 +647,13 @@ const props = defineProps({
|
||||
|
||||
const emit = defineEmits(['update:modelValue'])
|
||||
|
||||
const secretMarkedForClear = computed(() => props.schema.secret && props.modelValue === '__AKSRT_CLEAR_SECRET__')
|
||||
const secretDisplayValue = computed(() => secretMarkedForClear.value ? '' : props.modelValue)
|
||||
|
||||
function toggleSecretClear() {
|
||||
emit('update:modelValue', secretMarkedForClear.value ? '***' : '__AKSRT_CLEAR_SECRET__')
|
||||
}
|
||||
|
||||
const repeaterLength = computed(() => Array.isArray(props.modelValue) ? props.modelValue.length : 0)
|
||||
const reachedRepeaterMinimum = computed(() => repeaterLength.value <= Number(props.schema.min || 0))
|
||||
const reachedRepeaterMaximum = computed(() => Number(props.schema.max || 0) > 0 && repeaterLength.value >= Number(props.schema.max))
|
||||
@@ -1014,6 +1032,20 @@ function confirmRepeaterModal() {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.aksrt-field__input-wrap {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.aksrt-field__input-wrap .n-button {
|
||||
justify-self: start;
|
||||
}
|
||||
|
||||
.aksrt-field__secret-clear-hint {
|
||||
color: var(--aksrt-color-warning, #d97706);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.aksrt-field__label-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -200,7 +200,20 @@ const {
|
||||
}
|
||||
return response
|
||||
},
|
||||
submit: (data) => api.saveSchemaPage(resolvedDomain.value, resolvedSection.value, data),
|
||||
submit: async (data) => {
|
||||
const payload = { ...data }
|
||||
const clearSecrets = []
|
||||
Object.keys(payload).forEach((key) => {
|
||||
if (payload[key] === '__AKSRT_CLEAR_SECRET__') {
|
||||
clearSecrets.push(key)
|
||||
delete payload[key]
|
||||
}
|
||||
})
|
||||
if (clearSecrets.length) payload.__clear_secrets = clearSecrets
|
||||
const response = await api.saveSchemaPage(resolvedDomain.value, resolvedSection.value, payload)
|
||||
clearSecrets.forEach((key) => { data[key] = '' })
|
||||
return response
|
||||
},
|
||||
defaults: defaults.value,
|
||||
onSaved: () => {
|
||||
message.success('设置已保存')
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
<template>
|
||||
<div class="aksrt-page-container">
|
||||
<PageHeader :title="title" :desc="desc">
|
||||
<template #actions>
|
||||
<n-space v-if="links.length">
|
||||
<n-button v-for="link in links" :key="link.path" quaternary @click="go(link.path)">
|
||||
{{ link.label }}
|
||||
</n-button>
|
||||
</n-space>
|
||||
</template>
|
||||
</PageHeader>
|
||||
|
||||
<n-card v-if="note" class="aksrt-section-card">
|
||||
<n-alert type="info" :show-icon="false">
|
||||
{{ note }}
|
||||
</n-alert>
|
||||
</n-card>
|
||||
|
||||
<slot name="before-form" />
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { useRouter } from 'vue-router'
|
||||
import PageHeader from '@/components/PageHeader.vue'
|
||||
|
||||
defineProps({
|
||||
title: { type: String, required: true },
|
||||
desc: { type: String, default: '' },
|
||||
note: { type: String, default: '' },
|
||||
links: { type: Array, default: () => [] },
|
||||
})
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
function go(path) {
|
||||
router.push(path)
|
||||
}
|
||||
</script>
|
||||
@@ -2,7 +2,7 @@ export const oauthSchema = {
|
||||
key: 'users.oauth',
|
||||
title: '第三方登录',
|
||||
icon: 'fa fas fa-share-alt',
|
||||
description: 'GitHub、Gitee、QQ、Google 等第三方登录配置。',
|
||||
description: 'GitHub、Gitee、QQ、Google、微博和微信第三方登录配置。',
|
||||
defaults: {
|
||||
oauth_s: false,
|
||||
oauth_proxy_mode: 'close',
|
||||
@@ -10,59 +10,42 @@ export const oauthSchema = {
|
||||
oauth_proxy_server_url: '',
|
||||
oauth_proxy_server_providers: ['github', 'gitee', 'qq', 'google'],
|
||||
oauth_proxy_client_providers: ['github', 'gitee', 'qq', 'google'],
|
||||
oauth_proxy_gzh_type: 'service',
|
||||
oauth_bind_type: 'auto',
|
||||
oauth_button_lg: false,
|
||||
weixingzh_priority: false,
|
||||
weixingzh_auto: false,
|
||||
weixingzh_auto_expires: 3600,
|
||||
oauth_github_s: false,
|
||||
oauth_gitee_s: false,
|
||||
oauth_qq_s: false,
|
||||
oauth_weixingzh_s: false,
|
||||
oauth_weixin_s: false,
|
||||
oauth_google_s: false,
|
||||
oauth_weibo_s: false,
|
||||
oauth_baidu_s: false,
|
||||
oauth_alipay_s: false,
|
||||
oauth_weixin_s: false,
|
||||
oauth_weixingzh_s: false,
|
||||
clogin_s: false,
|
||||
clogin_url: '',
|
||||
clogin_id: '',
|
||||
clogin_key: '',
|
||||
clogin_oauth_s: ['qq', 'weixin', 'weibo', 'alipay'],
|
||||
github_appid: '',
|
||||
github_appkey: '',
|
||||
gitee_appid: '',
|
||||
gitee_appkey: '',
|
||||
qq_appid: '',
|
||||
qq_appkey: '',
|
||||
google_client_id: '',
|
||||
google_client_secret: '',
|
||||
weibo_appid: '',
|
||||
weibo_appkey: '',
|
||||
weixin_appid: '',
|
||||
weixin_appsecret: '',
|
||||
weixingzh_gzh_type: 'service',
|
||||
weixingzh_token: '',
|
||||
weixingzh_token_nocheck: false,
|
||||
weixingzh_encoding_aes_key: '',
|
||||
weixingzh_appid: '',
|
||||
weixingzh_appsecret: '',
|
||||
weixingzh_code_qrcode: '',
|
||||
weixingzh_code_keyword: '登录',
|
||||
weixingzh_code_reply: '您的验证码是:%s,有效期 %d 分钟。',
|
||||
weixingzh_code_subscribe_reply: '欢迎关注!回复「%s」获取登录验证码。',
|
||||
weixingzh_subscribe_msg: '',
|
||||
weixingzh_new_subscribe_msg: '',
|
||||
weixingzh_scan_msg: '',
|
||||
weixingzh_auto_reply_text: '',
|
||||
weixingzh_auto_reply_search: '',
|
||||
weixingzh_auto_reply_image: '',
|
||||
weixingzh_auto_reply_voice: '',
|
||||
weixingzh_auto_reply_default: '暂不支持此类型的消息',
|
||||
weixingzh_gzh_menu: '',
|
||||
weibo_appid: '',
|
||||
weibo_appkey: '',
|
||||
baidu_appid: '',
|
||||
baidu_appkey: '',
|
||||
alipay_appid: '',
|
||||
alipay_privatekey: '',
|
||||
alipay_publickey: '',
|
||||
clogin_url: '',
|
||||
clogin_id: '',
|
||||
clogin_key: '',
|
||||
clogin_oauth_s: ['qq', 'weixin', 'weibo'],
|
||||
},
|
||||
groups: [
|
||||
{
|
||||
@@ -72,16 +55,13 @@ export const oauthSchema = {
|
||||
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_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', 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_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: '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 } },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -92,12 +72,11 @@ export const oauthSchema = {
|
||||
{ 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_google_s', label: 'Google登录', 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, help: '通过第三方聚合登录平台统一接入 QQ/微信/微博/支付宝等' },
|
||||
{ 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, help: '通过第三方聚合登录平台统一接入 QQ、微信和微博' },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -106,7 +85,7 @@ export const oauthSchema = {
|
||||
icon: 'fa fab fa-github',
|
||||
fields: [
|
||||
{ key: 'github_appid', label: 'Client ID', type: 'input', default: '' },
|
||||
{ key: 'github_appkey', label: 'Client Secret', type: 'input', default: '' },
|
||||
{ key: 'github_appkey', label: 'Client Secret', type: 'input', inputType: 'password', secret: true, default: '' },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -115,7 +94,7 @@ export const oauthSchema = {
|
||||
icon: 'fa fas fa-code-branch',
|
||||
fields: [
|
||||
{ key: 'gitee_appid', label: 'Client ID', type: 'input', default: '' },
|
||||
{ key: 'gitee_appkey', label: 'Client Secret', type: 'input', default: '' },
|
||||
{ key: 'gitee_appkey', label: 'Client Secret', type: 'input', inputType: 'password', secret: true, default: '' },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -124,42 +103,16 @@ export const oauthSchema = {
|
||||
icon: 'fa fab fa-qq',
|
||||
fields: [
|
||||
{ key: 'qq_appid', label: 'App ID', type: 'input', default: '' },
|
||||
{ key: 'qq_appkey', label: 'App Key', type: 'input', default: '' },
|
||||
{ key: 'qq_appkey', label: 'App Key', type: 'input', inputType: 'password', secret: true, default: '' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'weixin',
|
||||
title: '微信开放平台配置',
|
||||
icon: 'fa fab fa-weixin',
|
||||
key: 'google',
|
||||
title: 'Google配置',
|
||||
icon: 'fa fab fa-google',
|
||||
fields: [
|
||||
{ key: 'weixin_appid', label: 'AppID', type: 'input', default: '' },
|
||||
{ key: 'weixin_appsecret', label: 'AppSecret', type: 'input', default: '' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'weixingzh',
|
||||
title: '微信公众号配置',
|
||||
icon: 'fa fab fa-weixin',
|
||||
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: 'google_client_id', label: 'Client ID', type: 'input', default: '' },
|
||||
{ key: 'google_client_secret', label: 'Client Secret', type: 'input', inputType: 'password', secret: true, default: '' },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -168,16 +121,32 @@ export const oauthSchema = {
|
||||
icon: 'fa fab fa-weibo',
|
||||
fields: [
|
||||
{ key: 'weibo_appid', label: 'App Key', type: 'input', default: '' },
|
||||
{ key: 'weibo_appkey', label: 'App Secret', type: 'input', default: '' },
|
||||
{ key: 'weibo_appkey', label: 'App Secret', type: 'input', inputType: 'password', secret: true, default: '' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'baidu',
|
||||
title: '百度配置',
|
||||
icon: 'fa fas fa-paw',
|
||||
key: 'weixin',
|
||||
title: '微信开放平台配置',
|
||||
icon: 'fa fab fa-weixin',
|
||||
fields: [
|
||||
{ key: 'baidu_appid', label: 'API Key', type: 'input', default: '' },
|
||||
{ key: 'baidu_appkey', label: 'Secret Key', type: 'input', default: '' },
|
||||
{ key: 'weixin_appid', label: 'AppID', type: 'input', default: '' },
|
||||
{ key: 'weixin_appsecret', label: 'AppSecret', type: 'input', inputType: 'password', secret: true, default: '' },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'weixingzh',
|
||||
title: '微信公众号配置',
|
||||
icon: 'fa fab fa-weixin',
|
||||
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: '用户扫码关注公众号后的回复文案' },
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -185,27 +154,15 @@ export const oauthSchema = {
|
||||
title: '彩虹聚合登录',
|
||||
icon: 'fa fas fa-cloud',
|
||||
fields: [
|
||||
{ key: 'clogin_url', label: '接口地址', type: 'input', default: '', help: '如 https://xxx.com 不要带 connect.php', dependsOn: { key: 'clogin_s', value: true } },
|
||||
{ key: 'clogin_url', label: '接口地址', type: 'input', default: '', help: '如 https://xxx.com,不要带 connect.php', dependsOn: { key: 'clogin_s', value: true } },
|
||||
{ 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: [
|
||||
{ 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' },
|
||||
{ label: '支付宝', value: 'alipay' },
|
||||
{ label: '百度', value: 'baidu' },
|
||||
], dependsOn: { key: 'clogin_s', value: true } },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'alipay',
|
||||
title: '支付宝配置',
|
||||
icon: 'fa fas fa-credit-card',
|
||||
fields: [
|
||||
{ key: 'alipay_appid', label: 'AppID', type: 'input', default: '' },
|
||||
{ key: 'alipay_privatekey', label: '应用私钥', type: 'textarea', rows: 3, default: '' },
|
||||
{ key: 'alipay_publickey', label: '支付宝公钥', type: 'input', default: '' },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -5366,10 +5366,6 @@ body:has(.modal.in) .float-btn,
|
||||
font-size: 1.2em;
|
||||
}
|
||||
|
||||
.social-login-item.button-lg.baidu .icon {
|
||||
font-size: 1.2em;
|
||||
}
|
||||
|
||||
.social-login-item,
|
||||
.social-login-item svg {
|
||||
color: #fff !important;
|
||||
@@ -5389,14 +5385,6 @@ body:has(.modal.in) .float-btn,
|
||||
background: #1296db;
|
||||
}
|
||||
|
||||
.social-login-item.alipay {
|
||||
background: #1296db;
|
||||
}
|
||||
|
||||
.social-login-item.baidu {
|
||||
background: #4e6ef2;
|
||||
}
|
||||
|
||||
.social-login-item.github {
|
||||
background: #505050;
|
||||
}
|
||||
@@ -5446,8 +5434,6 @@ body:has(.modal.in) .float-btn,
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.social-login-item.toggle-radius.baidu,
|
||||
.social-login-item.toggle-radius.alipay,
|
||||
.social-login-item.toggle-radius.github {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -70,13 +70,12 @@
|
||||
.social-login-item.weibo { background: #ea5d5c; }
|
||||
.social-login-item.weixingzh,
|
||||
.social-login-item.weixin { background: #24b76a; }
|
||||
.social-login-item.qq,
|
||||
.social-login-item.alipay { background: #1296db; }
|
||||
.social-login-item.baidu { background: #4e6ef2; }
|
||||
.social-login-item.qq { background: #1296db; }
|
||||
.social-login-item.github { background: #505050; }
|
||||
.social-login-item.gitee { background: #c2292f; }
|
||||
.social-login-item.google { background: var(--main-shadow, rgba(116, 116, 116, .08)); color: var(--main-color, #4e5358); }
|
||||
.auth-qrcode { display: grid; place-items: center; width: 180px; min-height: 180px; margin: 20px auto; background: #fff; color: #38b766; text-align: center; }
|
||||
.auth-qrcode [data-auth-qr-content] { display: grid; place-items: center; width: 100%; min-height: 180px; }
|
||||
.auth-qrcode i { font-size: 46px; }
|
||||
.auth-qrcode span { color: #777; font-size: 12px; }
|
||||
|
||||
|
||||
+438
-89
@@ -5,13 +5,50 @@
|
||||
var config = window.aksrtData || {};
|
||||
var apiRoot = String(config.apiUrl || config.restUrl || '/wp-json/aksrt/v1').replace(/\/$/, '');
|
||||
var nonce = config.restNonce || '';
|
||||
var modal = null;
|
||||
var lastModalTrigger = null;
|
||||
var qrStates = [];
|
||||
var oauthErrorMessages = {
|
||||
access_denied: '已取消第三方授权',
|
||||
cancelled: '已取消第三方授权',
|
||||
canceled: '已取消第三方授权',
|
||||
invalid_state: '授权状态已失效,请重新尝试',
|
||||
state_invalid: '授权状态已失效,请重新尝试',
|
||||
state_mismatch: '授权状态已失效,请重新尝试',
|
||||
state_user_mismatch: '当前账号与授权发起账号不一致,请重新尝试',
|
||||
provider_disabled: '该登录方式暂未启用',
|
||||
provider_unavailable: '该登录方式暂时不可用',
|
||||
provider_cancelled: '已取消第三方授权',
|
||||
provider_error: '第三方授权失败,请稍后重试',
|
||||
callback_failed: '第三方授权失败,请稍后重试',
|
||||
code_missing: '授权回调缺少必要信息,请重新尝试',
|
||||
proxy_config: '代理登录配置不可用,请联系管理员',
|
||||
account_match_failed: '第三方账号匹配失败,请重试',
|
||||
login_failed: '第三方登录失败,请重试',
|
||||
bind_failed: '第三方账号绑定失败,请重试',
|
||||
binding_conflict: '该第三方账号已绑定其他账号',
|
||||
account_conflict: '该第三方账号无法绑定到当前账号',
|
||||
already_bound: '该第三方账号已绑定其他账号',
|
||||
timeout: '第三方授权已超时,请重试',
|
||||
};
|
||||
var oauthProviderLabels = {
|
||||
github: 'GitHub',
|
||||
gitee: 'Gitee',
|
||||
qq: 'QQ',
|
||||
google: 'Google',
|
||||
weibo: '微博',
|
||||
weixin: '微信',
|
||||
weixingzh: '微信公众号',
|
||||
};
|
||||
|
||||
function request(path, data) {
|
||||
function request(path, data, options) {
|
||||
options = options || {};
|
||||
return fetch(apiRoot + '/auth/' + path, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
|
||||
body: JSON.stringify(data),
|
||||
signal: options.signal,
|
||||
}).then(function (response) {
|
||||
return response.json().catch(function () { return {}; }).then(function (body) {
|
||||
if (!response.ok || body.success === false) {
|
||||
@@ -37,74 +74,295 @@
|
||||
}
|
||||
|
||||
function notify(text, type) {
|
||||
if (!text) return;
|
||||
if (!text || typeof window.notyf !== 'function') return;
|
||||
window.notyf(escapeHtml(text), type || 'info');
|
||||
}
|
||||
|
||||
function cleanOAuthResult(url) {
|
||||
['oauth_action', 'oauth_provider', 'oauth_error', 'oauth_bound'].forEach(function (key) {
|
||||
url.searchParams.delete(key);
|
||||
});
|
||||
if (window.history && window.history.replaceState) {
|
||||
window.history.replaceState({}, '', url.pathname + url.search + url.hash);
|
||||
}
|
||||
}
|
||||
|
||||
function showOAuthResultToast() {
|
||||
if (!window.URL || document.documentElement.dataset.aksrtOauthResultHandled === 'true') return;
|
||||
var url = new URL(window.location.href);
|
||||
var action = url.searchParams.get('oauth_action');
|
||||
if (['login', 'bind', 'error'].indexOf(action) === -1) return;
|
||||
var userCenterOwnsBind = action === 'bind' && /\/user(?:\/settings)?\/?$/.test(url.pathname) && document.querySelector('[data-identity-root], .settings-section');
|
||||
if (userCenterOwnsBind) return;
|
||||
document.documentElement.dataset.aksrtOauthResultHandled = 'true';
|
||||
|
||||
var provider = url.searchParams.get('oauth_provider') || '';
|
||||
var providerLabel = oauthProviderLabels[provider] || '';
|
||||
var message = '';
|
||||
var type = 'success';
|
||||
if (action === 'login') message = providerLabel ? providerLabel + '登录成功' : '登录成功';
|
||||
if (action === 'bind') message = providerLabel ? providerLabel + '绑定成功' : '第三方账号绑定成功';
|
||||
if (action === 'error') {
|
||||
type = 'danger';
|
||||
message = oauthErrorMessages[url.searchParams.get('oauth_error') || ''] || '第三方授权失败,请重试';
|
||||
}
|
||||
|
||||
notify(message, type);
|
||||
cleanOAuthResult(url);
|
||||
}
|
||||
|
||||
function qrState(root) {
|
||||
if (root._aksrtQrState) return root._aksrtQrState;
|
||||
root._aksrtQrState = {
|
||||
root: root,
|
||||
timer: null,
|
||||
timeout: null,
|
||||
controller: null,
|
||||
inFlight: false,
|
||||
sequence: 0,
|
||||
token: '',
|
||||
startedAt: 0,
|
||||
backoff: 0,
|
||||
terminal: false,
|
||||
};
|
||||
qrStates.push(root._aksrtQrState);
|
||||
return root._aksrtQrState;
|
||||
}
|
||||
|
||||
function qrNodes(root) {
|
||||
var box = root.querySelector('[data-auth-qrcode]');
|
||||
return {
|
||||
box: box,
|
||||
content: box && box.querySelector('[data-auth-qr-content]'),
|
||||
status: box && box.querySelector('[data-auth-qr-status]'),
|
||||
};
|
||||
}
|
||||
|
||||
function setQrStatus(root, message) {
|
||||
var nodes = qrNodes(root);
|
||||
if (nodes.status) nodes.status.textContent = message || '';
|
||||
}
|
||||
|
||||
function setQrRefresh(root, message) {
|
||||
var nodes = qrNodes(root);
|
||||
if (!nodes.box) return;
|
||||
nodes.box.dataset.loading = '0';
|
||||
nodes.box.dataset.loaded = '0';
|
||||
if (nodes.content) nodes.content.innerHTML = '<button type="button" data-auth-refresh-qr>' + escapeHtml(message) + '</button>';
|
||||
setQrStatus(root, message);
|
||||
}
|
||||
|
||||
function isRootActive(root) {
|
||||
if (!root || root.dataset.activeTab !== 'oauth' || document.visibilityState !== 'visible') return false;
|
||||
if (root.dataset.surface !== 'modal') return document.documentElement.contains(root);
|
||||
return !!modal && modal.classList.contains('is-open') && modal.contains(root);
|
||||
}
|
||||
|
||||
function stopQr(root) {
|
||||
var state = qrState(root);
|
||||
state.sequence += 1;
|
||||
if (state.timer) window.clearTimeout(state.timer);
|
||||
if (state.timeout) window.clearTimeout(state.timeout);
|
||||
state.timer = null;
|
||||
state.timeout = null;
|
||||
if (state.controller) {
|
||||
try { state.controller.abort(); } catch (_) {}
|
||||
}
|
||||
state.controller = null;
|
||||
state.inFlight = false;
|
||||
}
|
||||
|
||||
function finishQr(root, status, message) {
|
||||
var state = qrState(root);
|
||||
stopQr(root);
|
||||
state.terminal = true;
|
||||
state.token = '';
|
||||
setQrRefresh(root, message || (status === 'expired' ? '二维码已过期,点击刷新' : '二维码登录已结束,点击刷新'));
|
||||
}
|
||||
|
||||
function qrRequest(root, path, payload) {
|
||||
var state = qrState(root);
|
||||
if (state.inFlight) return Promise.resolve(null);
|
||||
state.inFlight = true;
|
||||
var controller = window.AbortController ? new window.AbortController() : null;
|
||||
var timedOut = false;
|
||||
state.controller = controller;
|
||||
state.timeout = window.setTimeout(function () {
|
||||
timedOut = true;
|
||||
if (controller) controller.abort();
|
||||
}, 15000);
|
||||
|
||||
return request(path, payload, { signal: controller ? controller.signal : undefined }).catch(function (error) {
|
||||
if (timedOut) {
|
||||
var timeoutError = new Error('二维码请求超时');
|
||||
timeoutError.code = 'QR_TIMEOUT';
|
||||
throw timeoutError;
|
||||
}
|
||||
throw error;
|
||||
}).finally(function () {
|
||||
if (state.controller !== controller) return;
|
||||
if (state.timeout) window.clearTimeout(state.timeout);
|
||||
state.timeout = null;
|
||||
state.controller = null;
|
||||
state.inFlight = false;
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleQrPoll(root, delay) {
|
||||
var state = qrState(root);
|
||||
if (!state.token || state.terminal || !isRootActive(root)) return;
|
||||
if (state.startedAt && Date.now() - state.startedAt >= 300000) {
|
||||
finishQr(root, 'timeout', '二维码登录已超时,点击刷新');
|
||||
return;
|
||||
}
|
||||
if (state.timer) window.clearTimeout(state.timer);
|
||||
var wait = delay === 0
|
||||
? 0
|
||||
: Math.min(30000, Math.max(3000, Number(delay) || 3000) * Math.pow(2, Math.min(3, state.backoff)));
|
||||
state.timer = window.setTimeout(function () {
|
||||
state.timer = null;
|
||||
pollQr(root);
|
||||
}, wait);
|
||||
}
|
||||
|
||||
function pollQr(root) {
|
||||
var state = qrState(root);
|
||||
if (!state.token || state.terminal || state.inFlight || !isRootActive(root)) return;
|
||||
qrRequest(root, 'check-qrcode-login', {
|
||||
token: state.token,
|
||||
action: root.dataset.oauthIntent || 'login',
|
||||
redirect_to: root.dataset.redirectTo || window.location.href,
|
||||
}).then(function (result) {
|
||||
if (!result || !isRootActive(root)) return;
|
||||
if (result.needs_binding && result.redirect) {
|
||||
stopQr(root);
|
||||
setQrStatus(root, '需要绑定本地账号,正在跳转');
|
||||
notify('请绑定已有账号或注册新账号', 'info');
|
||||
window.location.assign(result.redirect);
|
||||
return;
|
||||
}
|
||||
if (result.bound && result.redirect) {
|
||||
stopQr(root);
|
||||
setQrStatus(root, '绑定成功,正在跳转');
|
||||
notify('微信公众号绑定成功', 'success');
|
||||
window.location.assign(result.redirect);
|
||||
return;
|
||||
}
|
||||
if (result.logged_in || result.status === 'logged_in') {
|
||||
stopQr(root);
|
||||
setQrStatus(root, '登录成功,正在跳转');
|
||||
notify('登录成功', 'success');
|
||||
window.location.assign(result.redirect || window.location.href);
|
||||
return;
|
||||
}
|
||||
if (result.status === 'expired') {
|
||||
finishQr(root, 'expired', '二维码已过期,点击刷新');
|
||||
notify('二维码已过期,请刷新后重试', 'warning');
|
||||
return;
|
||||
}
|
||||
if (['denied', 'cancelled', 'canceled', 'failed', 'error'].indexOf(result.status) !== -1) {
|
||||
finishQr(root, result.status, '二维码登录未完成,点击刷新');
|
||||
notify('二维码登录未完成,请刷新后重试', 'danger');
|
||||
return;
|
||||
}
|
||||
state.backoff = 0;
|
||||
setQrStatus(root, result.message || (result.status === 'scanned' ? '已扫码,请在微信中确认' : '等待扫码确认'));
|
||||
scheduleQrPoll(root, result.poll_interval ? Number(result.poll_interval) * 1000 : 3000);
|
||||
}).catch(function (error) {
|
||||
if (!isRootActive(root) || (error && error.name === 'AbortError')) return;
|
||||
state.backoff = Math.min(3, state.backoff + 1);
|
||||
setQrStatus(root, error && error.code === 'QR_TIMEOUT' ? '状态检查超时,正在重试' : '状态检查失败,正在重试');
|
||||
scheduleQrPoll(root, 3000);
|
||||
});
|
||||
}
|
||||
|
||||
function loadQr(root, force) {
|
||||
var nodes = qrNodes(root);
|
||||
if (!nodes.box) return;
|
||||
var state = qrState(root);
|
||||
if (force) {
|
||||
stopQr(root);
|
||||
state.token = '';
|
||||
state.startedAt = 0;
|
||||
state.backoff = 0;
|
||||
state.terminal = false;
|
||||
nodes.box.dataset.loaded = '0';
|
||||
}
|
||||
if (state.inFlight || nodes.box.dataset.loading === '1') return;
|
||||
if (state.token && !state.terminal) {
|
||||
scheduleQrPoll(root, 0);
|
||||
return;
|
||||
}
|
||||
if (nodes.box.dataset.loaded === '1' && state.terminal) return;
|
||||
|
||||
nodes.box.dataset.loading = '1';
|
||||
setQrStatus(root, '正在获取二维码');
|
||||
qrRequest(root, 'qrcode-login', {
|
||||
action: root.dataset.oauthIntent || 'login',
|
||||
redirect_to: root.dataset.redirectTo || window.location.href,
|
||||
}).then(function (result) {
|
||||
if (!result || !isRootActive(root)) return;
|
||||
nodes.box.dataset.loading = '0';
|
||||
nodes.box.dataset.loaded = '1';
|
||||
if (nodes.content) nodes.content.innerHTML = result.qr_html || '';
|
||||
state.token = result.token || '';
|
||||
state.startedAt = Date.now();
|
||||
state.backoff = 0;
|
||||
state.terminal = result.mode !== 'scan' || !state.token;
|
||||
setQrStatus(root, state.terminal ? '请按页面提示完成登录' : '请使用微信扫描二维码');
|
||||
if (!state.terminal) scheduleQrPoll(root, result.poll_interval ? Number(result.poll_interval) * 1000 : 3000);
|
||||
}).catch(function (error) {
|
||||
if (!isRootActive(root) || (error && error.name === 'AbortError')) return;
|
||||
state.terminal = true;
|
||||
setQrRefresh(root, '二维码加载失败,点击重试');
|
||||
notify(error.message, 'danger');
|
||||
});
|
||||
}
|
||||
|
||||
function activate(root, tab, updateUrl) {
|
||||
var panel = root.querySelector('[data-auth-panel="' + tab + '"]');
|
||||
if (!panel) return;
|
||||
root.querySelectorAll('[data-auth-panel]').forEach(function (item) { item.hidden = item !== panel; });
|
||||
if (root.dataset.activeTab === 'oauth' && tab !== 'oauth') stopQr(root);
|
||||
root.querySelectorAll('[data-auth-panel]').forEach(function (item) {
|
||||
var active = item === panel;
|
||||
item.hidden = !active;
|
||||
item.setAttribute('aria-hidden', active ? 'false' : 'true');
|
||||
});
|
||||
root.querySelectorAll('[data-auth-tab]').forEach(function (item) {
|
||||
item.setAttribute('aria-selected', item.dataset.authTab === tab ? 'true' : 'false');
|
||||
});
|
||||
root.dataset.activeTab = tab;
|
||||
if (updateUrl && root.dataset.surface === 'page' && window.history && window.URL) {
|
||||
var url = new URL(window.location.href);
|
||||
url.searchParams.set('tab', tab);
|
||||
window.history.replaceState({}, '', url.toString());
|
||||
}
|
||||
var focus = panel.querySelector('input:not([type="hidden"])');
|
||||
var focus = panel.querySelector('input:not([type="hidden"]), button, a[href], [tabindex]:not([tabindex="-1"])');
|
||||
if (focus) window.setTimeout(function () { focus.focus(); }, 30);
|
||||
if (tab === 'oauth') loadQr(root);
|
||||
if (tab === 'oauth') loadQr(root, false);
|
||||
}
|
||||
|
||||
function loadQr(root) {
|
||||
var box = root.querySelector('[data-auth-qrcode]');
|
||||
if (!box || box.dataset.loading === '1' || box.dataset.loaded === '1') return;
|
||||
box.dataset.loading = '1';
|
||||
request('qrcode-login', {}).then(function (result) {
|
||||
box.dataset.loading = '0';
|
||||
box.dataset.loaded = '1';
|
||||
box.innerHTML = result.qr_html || '';
|
||||
if (result.mode === 'scan' && result.token) pollQr(box, result.token, 0);
|
||||
}).catch(function (error) {
|
||||
box.dataset.loading = '0';
|
||||
box.dataset.loaded = '0';
|
||||
box.innerHTML = '<button type="button" data-auth-refresh-qr>二维码加载失败,点击重试</button>';
|
||||
notify(error.message, 'danger');
|
||||
});
|
||||
}
|
||||
|
||||
function pollQr(box, token, count) {
|
||||
if (!document.documentElement.contains(box) || count >= 100) return;
|
||||
window.setTimeout(function () {
|
||||
request('check-qrcode-login', { token: token }).then(function (result) {
|
||||
if (result.logged_in) {
|
||||
notify('登录成功', 'success');
|
||||
window.location.assign(result.redirect || window.location.href);
|
||||
return;
|
||||
}
|
||||
if (result.status === 'expired') {
|
||||
box.dataset.loaded = '0';
|
||||
box.innerHTML = '<button type="button" data-auth-refresh-qr>二维码已过期,点击刷新</button>';
|
||||
notify('二维码已过期,请刷新后重试', 'warning');
|
||||
return;
|
||||
}
|
||||
pollQr(box, token, count + 1);
|
||||
}).catch(function () { pollQr(box, token, count + 1); });
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
function submitQrCode(form) {
|
||||
var data = formData(form);
|
||||
var button = form.querySelector('button[type="submit"]');
|
||||
if (button) button.disabled = true;
|
||||
request('weixingzh-code', data).then(function (result) {
|
||||
notify('登录成功', 'success');
|
||||
window.location.assign(result.redirect || window.location.href);
|
||||
}).catch(function (error) {
|
||||
if (button) button.disabled = false;
|
||||
notify(error.message, 'danger');
|
||||
});
|
||||
}
|
||||
function submitQrCode(form) {
|
||||
var data = formData(form);
|
||||
var root = form.closest('[data-aksrt-auth]');
|
||||
data.action = root ? (root.dataset.oauthIntent || 'login') : 'login';
|
||||
data.redirect_to = root ? (root.dataset.redirectTo || window.location.href) : window.location.href;
|
||||
var button = form.querySelector('button[type="submit"]');
|
||||
if (button) button.disabled = true;
|
||||
request('weixingzh-code', data).then(function (result) {
|
||||
if (result.needs_binding) {
|
||||
notify('请绑定已有账号或注册新账号', 'info');
|
||||
} else if (result.bound) {
|
||||
notify('微信公众号绑定成功', 'success');
|
||||
} else {
|
||||
notify('登录成功', 'success');
|
||||
}
|
||||
window.location.assign(result.redirect || window.location.href);
|
||||
}).catch(function (error) {
|
||||
if (button) button.disabled = false;
|
||||
notify(error.message, 'danger');
|
||||
});
|
||||
}
|
||||
|
||||
function setBusy(form, busy) {
|
||||
var button = form.querySelector('.sign-submit');
|
||||
@@ -189,9 +447,7 @@
|
||||
function submit(form) {
|
||||
var action = form.dataset.authForm;
|
||||
var payload = formData(form);
|
||||
if (action === 'register' && payload.channel !== 'phone') {
|
||||
payload.user_email = payload.target;
|
||||
}
|
||||
if (action === 'register' && payload.channel !== 'phone') payload.user_email = payload.target;
|
||||
setBusy(form, true);
|
||||
request(action, payload).then(function (result) {
|
||||
notify(result.message || '操作成功', 'success');
|
||||
@@ -212,38 +468,82 @@
|
||||
button.textContent = showCode ? '使用账号密码登录' : '使用验证码登录';
|
||||
}
|
||||
|
||||
function setOAuthRedirect(root, redirect) {
|
||||
if (!redirect || !window.URL) return;
|
||||
root.querySelectorAll('a[data-provider][href]').forEach(function (link) {
|
||||
var url;
|
||||
try { url = new URL(link.href, window.location.href); } catch (_) { return; }
|
||||
if (url.origin !== window.location.origin) return;
|
||||
if (!link.dataset.oauthStartHref) link.dataset.oauthStartHref = url.toString();
|
||||
url = new URL(link.dataset.oauthStartHref, window.location.href);
|
||||
url.searchParams.set('redirect_to', redirect);
|
||||
link.href = url.toString();
|
||||
});
|
||||
}
|
||||
|
||||
function initRoot(root) {
|
||||
root.querySelectorAll('input').forEach(function (input) {
|
||||
if (!input.hasAttribute('placeholder')) input.setAttribute('placeholder', ' ');
|
||||
});
|
||||
root.querySelectorAll('form').forEach(function (form) { form.noValidate = true; });
|
||||
var initial = root.dataset.initialTab || 'signin';
|
||||
if (initial === 'oauth' && window.matchMedia && window.matchMedia('(max-width: 767px)').matches) initial = 'signin';
|
||||
activate(root, initial, false);
|
||||
root.querySelectorAll('form').forEach(function (form) { form.noValidate = true; });
|
||||
root.querySelectorAll('[data-auth-tab]').forEach(function (tab) {
|
||||
tab.setAttribute('role', 'tab');
|
||||
var panel = root.querySelector('[data-auth-panel="' + tab.dataset.authTab + '"]');
|
||||
if (panel && panel.id) tab.setAttribute('aria-controls', panel.id);
|
||||
});
|
||||
root.querySelectorAll('[data-password-show]').forEach(function (button) {
|
||||
button.setAttribute('aria-pressed', 'false');
|
||||
if (!button.getAttribute('aria-label')) button.setAttribute('aria-label', '显示密码');
|
||||
});
|
||||
setOAuthRedirect(root, root.dataset.redirectTo || '');
|
||||
var initial = root.dataset.initialTab || 'signin';
|
||||
if (initial === 'oauth' && window.matchMedia && window.matchMedia('(max-width: 767px)').matches) initial = 'signin';
|
||||
var mayActivateQr = initial !== 'oauth' || document.visibilityState === 'visible';
|
||||
if (root.dataset.surface === 'modal' && (!modal || !modal.classList.contains('is-open'))) mayActivateQr = false;
|
||||
if (!mayActivateQr) initial = 'signin';
|
||||
activate(root, initial, false);
|
||||
root.addEventListener('click', function (event) {
|
||||
var tab = event.target.closest('[data-auth-tab]');
|
||||
if (tab) { event.preventDefault(); activate(root, tab.dataset.authTab, true); return; }
|
||||
if (tab) {
|
||||
event.preventDefault();
|
||||
activate(root, tab.dataset.authTab, true);
|
||||
return;
|
||||
}
|
||||
var password = event.target.closest('[data-password-show]');
|
||||
if (password) {
|
||||
var input = password.closest('.floating-input').querySelector('input');
|
||||
input.type = input.type === 'password' ? 'text' : 'password';
|
||||
password.querySelector('i').className = input.type === 'password' ? 'fa fas fa-eye' : 'fa fas fa-eye-slash';
|
||||
var visible = input.type === 'password';
|
||||
input.type = visible ? 'text' : 'password';
|
||||
password.setAttribute('aria-label', visible ? '隐藏密码' : '显示密码');
|
||||
password.setAttribute('aria-pressed', visible ? 'true' : 'false');
|
||||
password.querySelector('i').className = visible ? 'fa fas fa-eye-slash' : 'fa fas fa-eye';
|
||||
return;
|
||||
}
|
||||
var send = event.target.closest('[data-send-code]');
|
||||
if (send) { event.preventDefault(); sendCode(send); return; }
|
||||
if (send) {
|
||||
event.preventDefault();
|
||||
sendCode(send);
|
||||
return;
|
||||
}
|
||||
var mode = event.target.closest('[data-login-mode]');
|
||||
if (mode) { event.preventDefault(); toggleLoginMode(root, mode); }
|
||||
var refreshQr = event.target.closest('[data-auth-refresh-qr]');
|
||||
if (refreshQr) { event.preventDefault(); loadQr(root); }
|
||||
if (mode) {
|
||||
event.preventDefault();
|
||||
toggleLoginMode(root, mode);
|
||||
return;
|
||||
}
|
||||
var refreshQr = event.target.closest('[data-auth-refresh-qr]');
|
||||
if (refreshQr) {
|
||||
event.preventDefault();
|
||||
loadQr(root, true);
|
||||
}
|
||||
});
|
||||
root.addEventListener('submit', function (event) {
|
||||
var qrForm = event.target.closest('[data-aksrt-weixingzh-code]');
|
||||
if (qrForm) {
|
||||
event.preventDefault();
|
||||
if (validateForm(qrForm)) submitQrCode(qrForm);
|
||||
return;
|
||||
}
|
||||
var qrForm = event.target.closest('[data-aksrt-weixingzh-code]');
|
||||
if (qrForm) {
|
||||
event.preventDefault();
|
||||
if (validateForm(qrForm)) submitQrCode(qrForm);
|
||||
return;
|
||||
}
|
||||
var form = event.target.closest('[data-auth-form]');
|
||||
if (!form) return;
|
||||
event.preventDefault();
|
||||
@@ -252,15 +552,14 @@
|
||||
});
|
||||
}
|
||||
|
||||
function validateForm(form) {
|
||||
if (!form.checkValidity || form.checkValidity()) return true;
|
||||
var field = form.querySelector(':invalid');
|
||||
notify((field && field.validationMessage) || '请完整填写表单', 'warning');
|
||||
if (field && typeof field.focus === 'function') field.focus();
|
||||
return false;
|
||||
}
|
||||
function validateForm(form) {
|
||||
if (!form.checkValidity || form.checkValidity()) return true;
|
||||
var field = form.querySelector(':invalid');
|
||||
notify((field && field.validationMessage) || '请完整填写表单', 'warning');
|
||||
if (field && typeof field.focus === 'function') field.focus();
|
||||
return false;
|
||||
}
|
||||
|
||||
var modal;
|
||||
function authPageUrl(tab, redirect) {
|
||||
var routes = config.routes || {};
|
||||
var base = tab === 'signup' ? routes.register : routes.login;
|
||||
@@ -270,24 +569,37 @@
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function openModal(tab, redirect) {
|
||||
function focusableModalItems() {
|
||||
if (!modal) return [];
|
||||
return Array.prototype.filter.call(modal.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'), function (item) {
|
||||
return item.offsetParent !== null && !item.closest('[hidden]');
|
||||
});
|
||||
}
|
||||
|
||||
function openModal(tab, redirect, trigger) {
|
||||
if (!modal) {
|
||||
window.location.assign(authPageUrl(tab, redirect));
|
||||
return;
|
||||
}
|
||||
lastModalTrigger = trigger || document.activeElement;
|
||||
modal.classList.add('is-open');
|
||||
modal.setAttribute('aria-hidden', 'false');
|
||||
document.body.classList.add('auth-modal-open');
|
||||
var root = modal.querySelector('[data-aksrt-auth]');
|
||||
if (root) {
|
||||
var targetRedirect = redirect || window.location.href;
|
||||
root.dataset.redirectTo = targetRedirect;
|
||||
root.dataset.oauthIntent = tab === 'oauth' && trigger && trigger.dataset.oauthIntent === 'bind' ? 'bind' : 'login';
|
||||
root.querySelectorAll('[name="redirect_to"]').forEach(function (input) { input.value = targetRedirect; });
|
||||
setOAuthRedirect(root, targetRedirect);
|
||||
activate(root, tab || 'signin', false);
|
||||
var redirectInput = root.querySelector('[name="redirect_to"]');
|
||||
if (redirectInput && redirect) redirectInput.value = redirect;
|
||||
}
|
||||
}
|
||||
|
||||
function closeModal(storeDismissal) {
|
||||
if (!modal) return;
|
||||
if (!modal || !modal.classList.contains('is-open')) return;
|
||||
var root = modal.querySelector('[data-aksrt-auth]');
|
||||
if (root) stopQr(root);
|
||||
modal.classList.remove('is-open');
|
||||
modal.setAttribute('aria-hidden', 'true');
|
||||
document.body.classList.remove('auth-modal-open');
|
||||
@@ -295,9 +607,38 @@
|
||||
var until = Date.now() + Number(modal.dataset.autoExpires) * 3600000;
|
||||
window.localStorage.setItem('aksrtAuthAutoUntil', String(until));
|
||||
}
|
||||
var restore = lastModalTrigger;
|
||||
lastModalTrigger = null;
|
||||
if (restore && document.documentElement.contains(restore) && typeof restore.focus === 'function') restore.focus();
|
||||
}
|
||||
|
||||
function handleModalKeydown(event) {
|
||||
if (!modal || !modal.classList.contains('is-open')) return;
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
closeModal(true);
|
||||
return;
|
||||
}
|
||||
if (event.key !== 'Tab') return;
|
||||
var items = focusableModalItems();
|
||||
if (!items.length) {
|
||||
event.preventDefault();
|
||||
modal.focus();
|
||||
return;
|
||||
}
|
||||
var first = items[0];
|
||||
var last = items[items.length - 1];
|
||||
if (event.shiftKey && (document.activeElement === first || !modal.contains(document.activeElement))) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && document.activeElement === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function init() {
|
||||
showOAuthResultToast();
|
||||
document.querySelectorAll('[data-aksrt-auth]').forEach(initRoot);
|
||||
modal = document.querySelector('[data-auth-modal]');
|
||||
document.addEventListener('click', function (event) {
|
||||
@@ -305,17 +646,25 @@
|
||||
if (!trigger) return;
|
||||
event.preventDefault();
|
||||
var tab = trigger.classList.contains('signup-loader') ? 'signup' : (trigger.classList.contains('qrcode-signin') ? 'oauth' : 'signin');
|
||||
openModal(tab, trigger.dataset.authRedirect || '');
|
||||
openModal(tab, trigger.dataset.authRedirect || window.location.href, trigger);
|
||||
});
|
||||
if (modal) {
|
||||
modal.addEventListener('click', function (event) {
|
||||
if (event.target.closest('[data-auth-close]')) closeModal(true);
|
||||
});
|
||||
document.addEventListener('keydown', function (event) { if (event.key === 'Escape') closeModal(true); });
|
||||
document.addEventListener('keydown', handleModalKeydown);
|
||||
if (modal.dataset.auto === '1' && Number(window.localStorage.getItem('aksrtAuthAutoUntil') || 0) < Date.now()) {
|
||||
window.setTimeout(function () { openModal(modal.querySelector('[data-aksrt-auth]').dataset.initialTab || 'signin'); }, Math.max(1, Number(modal.dataset.autoWait) || 5) * 1000);
|
||||
window.setTimeout(function () {
|
||||
openModal(modal.querySelector('[data-aksrt-auth]').dataset.initialTab || 'signin', window.location.href, null);
|
||||
}, Math.max(1, Number(modal.dataset.autoWait) || 5) * 1000);
|
||||
}
|
||||
}
|
||||
document.addEventListener('visibilitychange', function () {
|
||||
qrStates.forEach(function (state) {
|
||||
if (document.visibilityState !== 'visible') stopQr(state.root);
|
||||
else if (isRootActive(state.root)) loadQr(state.root, false);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
|
||||
|
||||
@@ -875,25 +875,33 @@
|
||||
data.set('nonce', unbindNonce ? unbindNonce.value : '');
|
||||
data.set('provider', p);
|
||||
data.set('userId', String(userId));
|
||||
fetch(ajaxUrl, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: data.toString()
|
||||
})
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(d) {
|
||||
if (d.success) {
|
||||
notyf((d.data && d.data.message) || i18n.unbindSuccess || '解除成功', 'success', 5, toastId);
|
||||
setTimeout(function() {
|
||||
window.location.href = tabUrls.settings || new URL('/user/settings/', window.location.origin).toString();
|
||||
}, 1000);
|
||||
} else {
|
||||
notyf((d.data && d.data.message) || i18n.unbindFailed || '解除失败', 'danger', 5, toastId);
|
||||
self.disabled = false;
|
||||
self.textContent = i18n.unbind || '解除';
|
||||
}
|
||||
})
|
||||
fetch(ajaxUrl, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: data.toString()
|
||||
})
|
||||
.then(function(response) {
|
||||
return response.json().catch(function() { return {}; }).then(function(payload) {
|
||||
return { ok: response.ok, status: response.status, payload: payload || {} };
|
||||
});
|
||||
})
|
||||
.then(function(result) {
|
||||
var d = result.payload;
|
||||
if (result.ok && d.success) {
|
||||
notyf((d.data && d.data.message) || d.message || i18n.unbindSuccess || '解除成功', 'success', 5, toastId);
|
||||
setTimeout(function() {
|
||||
window.location.href = tabUrls.settings || new URL('/user/settings/', window.location.origin).toString();
|
||||
}, 1000);
|
||||
} else {
|
||||
var message = result.status === 409
|
||||
? (d.message || (d.data && d.data.message) || i18n.unbindFailed || '解除失败')
|
||||
: ((d.data && d.data.message) || d.message || i18n.unbindFailed || '解除失败');
|
||||
notyf(message, 'danger', 5, toastId);
|
||||
self.disabled = false;
|
||||
self.textContent = i18n.unbind || '解除';
|
||||
}
|
||||
})
|
||||
.catch(function() {
|
||||
notyf(i18n.networkError || '网络错误', 'danger', 5, toastId);
|
||||
self.disabled = false;
|
||||
@@ -903,22 +911,57 @@
|
||||
});
|
||||
}
|
||||
|
||||
function initSettingsCallbackToast() {
|
||||
if (document.documentElement.dataset.aksrtSettingsCallbackInitialized === 'true') return;
|
||||
document.documentElement.dataset.aksrtSettingsCallbackInitialized = 'true';
|
||||
var currentUrl = new URL(window.location.href);
|
||||
var provider = currentUrl.searchParams.get('oauth_bound');
|
||||
var isBindingCallback = currentUrl.searchParams.get('oauth_action') === 'bind'
|
||||
|| currentUrl.searchParams.get('tab') === 'settings'
|
||||
|| /\/user\/settings\/?$/.test(currentUrl.pathname);
|
||||
if (!provider || !isBindingCallback) return;
|
||||
function initSettingsCallbackToast() {
|
||||
if (document.documentElement.dataset.aksrtSettingsCallbackInitialized === 'true') return;
|
||||
var currentUrl = new URL(window.location.href);
|
||||
var action = currentUrl.searchParams.get('oauth_action');
|
||||
if (['login', 'bind', 'error'].indexOf(action) === -1) return;
|
||||
if (action !== 'bind' && document.documentElement.dataset.aksrtOauthResultHandled === 'true') return;
|
||||
document.documentElement.dataset.aksrtSettingsCallbackInitialized = 'true';
|
||||
|
||||
notyf(i18n.bindSuccess || '绑定成功', 'success');
|
||||
if (window.history.replaceState) {
|
||||
var cleanUrl = new URL(tabUrls.settings || '/user/settings/', window.location.origin);
|
||||
window.history.replaceState({}, '', cleanUrl.pathname + cleanUrl.search + cleanUrl.hash);
|
||||
var provider = currentUrl.searchParams.get('oauth_provider') || '';
|
||||
var providerLabels = {
|
||||
github: 'GitHub',
|
||||
gitee: 'Gitee',
|
||||
qq: 'QQ',
|
||||
google: 'Google',
|
||||
weibo: '微博',
|
||||
weixin: '微信',
|
||||
weixingzh: '微信公众号'
|
||||
};
|
||||
var errorMessages = {
|
||||
access_denied: '已取消第三方授权',
|
||||
cancelled: '已取消第三方授权',
|
||||
canceled: '已取消第三方授权',
|
||||
invalid_state: '授权状态已失效,请重新尝试',
|
||||
state_mismatch: '授权状态已失效,请重新尝试',
|
||||
provider_unavailable: '该登录方式暂时不可用',
|
||||
provider_error: '第三方授权失败,请稍后重试',
|
||||
callback_failed: '第三方授权失败,请稍后重试',
|
||||
login_failed: '第三方登录失败,请重试',
|
||||
bind_failed: '第三方账号绑定失败,请重试',
|
||||
account_conflict: '该第三方账号无法绑定到当前账号',
|
||||
already_bound: '该第三方账号已绑定其他账号',
|
||||
timeout: '第三方授权已超时,请重试'
|
||||
};
|
||||
var providerLabel = providerLabels[provider] || '';
|
||||
var message = '';
|
||||
var type = 'success';
|
||||
if (action === 'login') message = providerLabel ? providerLabel + '登录成功' : '登录成功';
|
||||
if (action === 'bind') message = providerLabel ? providerLabel + '绑定成功' : (i18n.bindSuccess || '绑定成功');
|
||||
if (action === 'error') {
|
||||
type = 'danger';
|
||||
message = errorMessages[currentUrl.searchParams.get('oauth_error') || ''] || '第三方授权失败,请重试';
|
||||
}
|
||||
notyf(message, type);
|
||||
|
||||
if (window.history.replaceState) {
|
||||
['oauth_action', 'oauth_provider', 'oauth_error', 'oauth_bound'].forEach(function(key) {
|
||||
currentUrl.searchParams.delete(key);
|
||||
});
|
||||
window.history.replaceState({}, '', currentUrl.pathname + currentUrl.search + currentUrl.hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (window.AksrtFrontend && typeof window.AksrtFrontend.register === 'function') {
|
||||
window.AksrtFrontend.register('aksrt-settings', function(root) {
|
||||
|
||||
+1
-1
@@ -152,7 +152,7 @@ if (class_exists('\AKSRT\Frontend\WeChatShare')) {
|
||||
}
|
||||
|
||||
// 初始化代理登录(根据配置模式选择性加载)
|
||||
$aksrt_proxy_mode = \AKSRT\Settings\Settings::oauth_proxy_mode();
|
||||
$aksrt_proxy_mode = \AKSRT\Auth\OAuthProviderCatalog::proxy_mode();
|
||||
if ($aksrt_proxy_mode === 'client' && class_exists('\AKSRT\Auth\OAuthProxyClient')) {
|
||||
\AKSRT\Auth\OAuthProxyClient::get_instance()->init();
|
||||
}
|
||||
|
||||
@@ -16,32 +16,35 @@ $binding_name_map = [
|
||||
'gitee' => 'Gitee',
|
||||
'qq' => 'QQ',
|
||||
'google' => 'Google',
|
||||
'weibo' => '微博',
|
||||
'weixin' => '微信',
|
||||
'weixingzh' => '微信公众号',
|
||||
];
|
||||
$binding_rows = [];
|
||||
foreach ((array) ($oauth_data['bindings'] ?? []) as $binding) {
|
||||
$key = $binding['key'] ?? '';
|
||||
$key = sanitize_key((string) ($binding['provider'] ?? $binding['key'] ?? $binding['name'] ?? ''));
|
||||
if (!$key) {
|
||||
continue;
|
||||
}
|
||||
$binding_rows[$key] = [
|
||||
'key' => $key,
|
||||
'name' => $binding_name_map[$key] ?? ($binding['name'] ?? ucfirst($key)),
|
||||
'name' => (string) ($binding['label'] ?? $binding_name_map[$key] ?? $binding['name'] ?? ucfirst($key)),
|
||||
'icon' => $binding['icon'] ?? '',
|
||||
'is_bound' => true,
|
||||
'url' => '',
|
||||
];
|
||||
}
|
||||
foreach ((array) ($oauth_data['available'] ?? []) as $binding) {
|
||||
$key = $binding['key'] ?? '';
|
||||
$key = sanitize_key((string) ($binding['provider'] ?? $binding['key'] ?? $binding['name'] ?? ''));
|
||||
if (!$key) {
|
||||
continue;
|
||||
}
|
||||
$binding_rows[$key] = [
|
||||
'key' => $key,
|
||||
'name' => $binding_name_map[$key] ?? ($binding['name'] ?? ucfirst($key)),
|
||||
'name' => (string) ($binding['label'] ?? $binding_name_map[$key] ?? $binding['name'] ?? ucfirst($key)),
|
||||
'icon' => $binding['icon'] ?? '',
|
||||
'is_bound' => false,
|
||||
'url' => $binding['url'] ?? '',
|
||||
'url' => $binding['start_url'] ?? $binding['url'] ?? '',
|
||||
];
|
||||
}
|
||||
?>
|
||||
@@ -70,7 +73,7 @@ foreach ((array) ($oauth_data['available'] ?? []) as $binding) {
|
||||
</button>
|
||||
</div>
|
||||
<?php else : ?>
|
||||
<a href="<?php echo esc_url($binding['url']); ?>" class="binding-item binding-item--linkable" target="_self">
|
||||
<a href="<?php echo esc_url($binding['url']); ?>" class="binding-item binding-item--linkable" target="_self" data-provider="<?php echo esc_attr($binding['key']); ?>">
|
||||
<span class="binding-item__icon"><?php echo $binding['icon']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
|
||||
<span class="binding-item__meta">
|
||||
<span class="binding-status binding-status--idle"><?php esc_html_e('未绑定', 'aksrt'); ?></span>
|
||||
|
||||
@@ -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
@@ -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) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
@@ -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
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -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;">✓ <?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('/');
|
||||
}
|
||||
}
|
||||
@@ -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'));
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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);
|
||||
|
||||
@@ -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
File diff suppressed because it is too large
Load Diff
@@ -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
@@ -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完整配置
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -16,7 +16,9 @@ $settings = class_exists('\AKSRT\Settings\Settings') ? '\AKSRT\Settings\Settings
|
||||
$obk = sanitize_text_field((string) ($aksrt_auth_context['obk'] ?? ''));
|
||||
$oauth_bind_data = $obk !== '' && class_exists('\AKSRT\Auth\Service') ? \AKSRT\Auth\Service::get_oauth_bind_context($obk) : null;
|
||||
$is_oauth_bind = is_array($oauth_bind_data);
|
||||
$registration_open = ($settings ? $settings::registration_enabled() : (bool) get_option('users_can_register')) || $is_oauth_bind;
|
||||
$registration_open = $is_oauth_bind
|
||||
? ($settings ? $settings::oauth_registration_enabled() : (bool) get_option('users_can_register'))
|
||||
: ($settings ? $settings::registration_enabled() : (bool) get_option('users_can_register'));
|
||||
$close_signin = $settings ? $settings::close_signin() : false;
|
||||
$signin_phone = $settings ? $settings::signin_phone_enabled() : false;
|
||||
$passwordless = $settings ? $settings::passwordless_login_enabled() : false;
|
||||
@@ -48,19 +50,21 @@ $oauth_user_data = $is_oauth_bind && !empty($oauth_bind_data['user_data']) && is
|
||||
$oauth_name = sanitize_user((string) ($oauth_user_data['name'] ?? $oauth_user_data['nickname'] ?? $oauth_user_data['login'] ?? ''), true);
|
||||
$oauth_email = sanitize_email((string) ($oauth_user_data['email'] ?? ''));
|
||||
$oauth_provider_name = $is_oauth_bind ? \AKSRT\Auth\Service::get_oauth_provider_name((string) ($oauth_bind_data['provider'] ?? '')) : '';
|
||||
$oauth_intent = sanitize_key((string) ($aksrt_auth_context['oauth_intent'] ?? ($_GET['oauth_intent'] ?? 'login')));
|
||||
$oauth_intent = $oauth_intent === 'bind' ? 'bind' : 'login';
|
||||
?>
|
||||
<div class="sign aksrt-auth<?php echo $oauth_large ? ' oauth-button-lg' : ''; ?>" data-aksrt-auth data-surface="<?php echo esc_attr($unique); ?>" data-initial-tab="<?php echo esc_attr($auth_tab); ?>" data-passwordless-mode="<?php echo esc_attr($passwordless_mode); ?>">
|
||||
<div class="sign aksrt-auth<?php echo $oauth_large ? ' oauth-button-lg' : ''; ?>" data-aksrt-auth data-surface="<?php echo esc_attr($unique); ?>" data-initial-tab="<?php echo esc_attr($auth_tab); ?>" data-passwordless-mode="<?php echo esc_attr($passwordless_mode); ?>" data-redirect-to="<?php echo esc_attr($redirect_to); ?>" data-oauth-intent="<?php echo esc_attr($oauth_intent); ?>">
|
||||
<?php if ($show_logo) : ?>
|
||||
<div class="sign-logo"><?php echo function_exists('aksrt_get_auth_sign_logo_html') ? aksrt_get_auth_sign_logo_html() : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></div>
|
||||
<?php endif; ?>
|
||||
|
||||
<section class="sign-panel" data-auth-panel="signin" <?php echo $auth_tab !== 'signin' ? 'hidden' : ''; ?>>
|
||||
<section id="<?php echo esc_attr($unique); ?>-auth-panel-signin" class="sign-panel" role="tabpanel" data-auth-panel="signin" <?php echo $auth_tab !== 'signin' ? 'hidden' : ''; ?>>
|
||||
<div class="sign-header"><h2><?php esc_html_e('登录', 'aksrt'); ?></h2><?php if ($registration_open) : ?><span><?php esc_html_e('没有账号?', 'aksrt'); ?> <button type="button" data-auth-tab="signup"><?php esc_html_e('立即注册', 'aksrt'); ?></button></span><?php endif; ?></div>
|
||||
<?php if (!$close_signin) : ?>
|
||||
<form class="sign-form" data-auth-form="login">
|
||||
<div class="floating-input"><input name="target" id="<?php echo esc_attr($unique); ?>-login-target" autocomplete="username" required><label for="<?php echo esc_attr($unique); ?>-login-target"><?php echo ($passwordless || $signin_phone) ? esc_html__('邮箱 / 手机号 / 用户名', 'aksrt') : esc_html__('邮箱 / 用户名', 'aksrt'); ?></label></div>
|
||||
<div data-auth-password-fields <?php echo $passwordless && $passwordless_mode !== 'pas' ? 'hidden' : ''; ?>>
|
||||
<div class="floating-input has-action"><input type="password" name="password" id="<?php echo esc_attr($unique); ?>-login-password" autocomplete="current-password"><label for="<?php echo esc_attr($unique); ?>-login-password"><?php esc_html_e('密码', 'aksrt'); ?></label><button type="button" class="password-show" data-password-show aria-label="<?php esc_attr_e('显示密码', 'aksrt'); ?>"><i class="fa fas fa-eye"></i></button></div>
|
||||
<div class="floating-input has-action"><input type="password" name="password" id="<?php echo esc_attr($unique); ?>-login-password" autocomplete="current-password"><label for="<?php echo esc_attr($unique); ?>-login-password"><?php esc_html_e('密码', 'aksrt'); ?></label><button type="button" class="password-show" data-password-show aria-label="<?php esc_attr_e('显示密码', 'aksrt'); ?>" aria-pressed="false"><i class="fa fas fa-eye"></i></button></div>
|
||||
</div>
|
||||
<?php if ($passwordless) : ?>
|
||||
<div data-auth-code-fields <?php echo $passwordless_mode === 'pas' ? 'hidden' : ''; ?>>
|
||||
@@ -78,14 +82,14 @@ $oauth_provider_name = $is_oauth_bind ? \AKSRT\Auth\Service::get_oauth_provider_
|
||||
</section>
|
||||
|
||||
<?php if ($registration_open) : ?>
|
||||
<section class="sign-panel" data-auth-panel="signup" <?php echo $auth_tab !== 'signup' ? 'hidden' : ''; ?>>
|
||||
<section id="<?php echo esc_attr($unique); ?>-auth-panel-signup" class="sign-panel" role="tabpanel" data-auth-panel="signup" <?php echo $auth_tab !== 'signup' ? 'hidden' : ''; ?>>
|
||||
<div class="sign-header"><h2><?php echo $is_oauth_bind ? esc_html__('注册并绑定', 'aksrt') : esc_html__('注册', 'aksrt'); ?></h2><span><?php esc_html_e('已有账号?', 'aksrt'); ?> <button type="button" data-auth-tab="<?php echo $is_oauth_bind ? 'bind' : 'signin'; ?>"><?php esc_html_e('立即登录', 'aksrt'); ?></button></span></div>
|
||||
<form class="sign-form" data-auth-form="register">
|
||||
<div class="floating-input"><input name="user_login" value="<?php echo esc_attr($oauth_name); ?>" id="<?php echo esc_attr($unique); ?>-register-name" autocomplete="username" required><label for="<?php echo esc_attr($unique); ?>-register-name"><?php esc_html_e('用户名', 'aksrt'); ?></label></div>
|
||||
<div class="floating-input"><input name="target" value="<?php echo esc_attr($oauth_email); ?>" id="<?php echo esc_attr($unique); ?>-register-target" autocomplete="<?php echo $signup_type === 'phone' ? 'tel' : 'email'; ?>" required><label for="<?php echo esc_attr($unique); ?>-register-target"><?php echo $signup_type === 'phone' ? esc_html__('手机号', 'aksrt') : ($signup_type === 'email_phone' ? esc_html__('邮箱 / 手机号', 'aksrt') : esc_html__('邮箱', 'aksrt')); ?></label></div>
|
||||
<?php if ($signup_verify) : ?><div class="floating-input has-action"><input name="code" inputmode="numeric" maxlength="6" id="<?php echo esc_attr($unique); ?>-register-code" required><label for="<?php echo esc_attr($unique); ?>-register-code"><?php esc_html_e('验证码', 'aksrt'); ?></label><button type="button" class="send-code" data-send-code="register"><?php esc_html_e('发送验证码', 'aksrt'); ?></button></div><?php endif; ?>
|
||||
<div class="floating-input has-action"><input type="password" name="password" id="<?php echo esc_attr($unique); ?>-register-password" autocomplete="new-password" minlength="6" required><label for="<?php echo esc_attr($unique); ?>-register-password"><?php esc_html_e('密码', 'aksrt'); ?></label><button type="button" class="password-show" data-password-show><i class="fa fas fa-eye"></i></button></div>
|
||||
<?php if (!$omit_confirm) : ?><div class="floating-input has-action"><input type="password" name="password_confirm" id="<?php echo esc_attr($unique); ?>-register-confirm" autocomplete="new-password" minlength="6" required><label for="<?php echo esc_attr($unique); ?>-register-confirm"><?php esc_html_e('重复密码', 'aksrt'); ?></label><button type="button" class="password-show" data-password-show><i class="fa fas fa-eye"></i></button></div><?php endif; ?>
|
||||
<div class="floating-input has-action"><input type="password" name="password" id="<?php echo esc_attr($unique); ?>-register-password" autocomplete="new-password" minlength="6" required><label for="<?php echo esc_attr($unique); ?>-register-password"><?php esc_html_e('密码', 'aksrt'); ?></label><button type="button" class="password-show" data-password-show aria-label="<?php esc_attr_e('显示密码', 'aksrt'); ?>" aria-pressed="false"><i class="fa fas fa-eye"></i></button></div>
|
||||
<?php if (!$omit_confirm) : ?><div class="floating-input has-action"><input type="password" name="password_confirm" id="<?php echo esc_attr($unique); ?>-register-confirm" autocomplete="new-password" minlength="6" required><label for="<?php echo esc_attr($unique); ?>-register-confirm"><?php esc_html_e('重复密码', 'aksrt'); ?></label><button type="button" class="password-show" data-password-show aria-label="<?php esc_attr_e('显示密码', 'aksrt'); ?>" aria-pressed="false"><i class="fa fas fa-eye"></i></button></div><?php endif; ?>
|
||||
<?php if ($ref_mode !== 'hidden') : ?><div class="floating-input"><input name="ref" value="<?php echo esc_attr($ref_value); ?>" id="<?php echo esc_attr($unique); ?>-register-ref" <?php echo $ref_mode === 'required' ? 'required' : ''; ?>><label for="<?php echo esc_attr($unique); ?>-register-ref"><?php echo $ref_mode === 'required' ? esc_html__('推广码', 'aksrt') : esc_html__('推广码(选填)', 'aksrt'); ?></label></div><?php if ($ref_hint !== '') : ?><div class="sign-hint"><?php echo wp_kses_post($ref_hint); ?></div><?php endif; ?><?php endif; ?>
|
||||
<?php if (!empty($agreement['enabled']) && !empty($agreement['required'])) : ?><label class="sign-agreement"><input type="checkbox" name="agree_terms" value="1" required><span><?php echo $agreement['label_html']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span></label><?php elseif (!empty($agreement['enabled'])) : ?><div class="sign-agreement sign-agreement-implicit"><?php esc_html_e('注册即表示', 'aksrt'); ?><?php echo $agreement['label_html']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></div><?php endif; ?>
|
||||
<?php if (function_exists('aksrt_render_captcha')) { aksrt_render_captcha('register'); } ?>
|
||||
@@ -97,31 +101,31 @@ $oauth_provider_name = $is_oauth_bind ? \AKSRT\Auth\Service::get_oauth_provider_
|
||||
</section>
|
||||
<?php endif; ?>
|
||||
|
||||
<section class="sign-panel" data-auth-panel="resetpassword" <?php echo $auth_tab !== 'resetpassword' ? 'hidden' : ''; ?>>
|
||||
<section id="<?php echo esc_attr($unique); ?>-auth-panel-resetpassword" class="sign-panel" role="tabpanel" data-auth-panel="resetpassword" <?php echo $auth_tab !== 'resetpassword' ? 'hidden' : ''; ?>>
|
||||
<div class="sign-header"><h2><?php esc_html_e('找回密码', 'aksrt'); ?></h2><span><button type="button" data-auth-tab="signin"><?php esc_html_e('返回登录', 'aksrt'); ?></button></span></div>
|
||||
<form class="sign-form" data-auth-form="reset-password">
|
||||
<div class="floating-input"><input name="target" id="<?php echo esc_attr($unique); ?>-reset-target" required><label for="<?php echo esc_attr($unique); ?>-reset-target"><?php echo $reset_type === 'phone' ? esc_html__('手机号', 'aksrt') : ($reset_type === 'email_phone' ? esc_html__('邮箱 / 手机号', 'aksrt') : esc_html__('邮箱', 'aksrt')); ?></label></div>
|
||||
<div class="floating-input has-action"><input name="code" inputmode="numeric" maxlength="6" id="<?php echo esc_attr($unique); ?>-reset-code" required><label for="<?php echo esc_attr($unique); ?>-reset-code"><?php esc_html_e('验证码', 'aksrt'); ?></label><button type="button" class="send-code" data-send-code="resetpassword"><?php esc_html_e('发送验证码', 'aksrt'); ?></button></div>
|
||||
<div class="floating-input has-action"><input type="password" name="password" id="<?php echo esc_attr($unique); ?>-reset-password" minlength="6" required><label for="<?php echo esc_attr($unique); ?>-reset-password"><?php esc_html_e('新密码', 'aksrt'); ?></label><button type="button" class="password-show" data-password-show><i class="fa fas fa-eye"></i></button></div>
|
||||
<div class="floating-input has-action"><input type="password" name="password_confirm" id="<?php echo esc_attr($unique); ?>-reset-confirm" minlength="6" required><label for="<?php echo esc_attr($unique); ?>-reset-confirm"><?php esc_html_e('重复新密码', 'aksrt'); ?></label><button type="button" class="password-show" data-password-show><i class="fa fas fa-eye"></i></button></div>
|
||||
<div class="floating-input has-action"><input type="password" name="password" id="<?php echo esc_attr($unique); ?>-reset-password" minlength="6" required><label for="<?php echo esc_attr($unique); ?>-reset-password"><?php esc_html_e('新密码', 'aksrt'); ?></label><button type="button" class="password-show" data-password-show aria-label="<?php esc_attr_e('显示密码', 'aksrt'); ?>" aria-pressed="false"><i class="fa fas fa-eye"></i></button></div>
|
||||
<div class="floating-input has-action"><input type="password" name="password_confirm" id="<?php echo esc_attr($unique); ?>-reset-confirm" minlength="6" required><label for="<?php echo esc_attr($unique); ?>-reset-confirm"><?php esc_html_e('重复新密码', 'aksrt'); ?></label><button type="button" class="password-show" data-password-show aria-label="<?php esc_attr_e('显示密码', 'aksrt'); ?>" aria-pressed="false"><i class="fa fas fa-eye"></i></button></div>
|
||||
<?php if (function_exists('aksrt_render_captcha')) { aksrt_render_captcha('lostpassword'); } ?>
|
||||
<input type="hidden" name="channel" value="<?php echo esc_attr($reset_type === 'phone' ? 'phone' : ''); ?>">
|
||||
<button type="submit" class="sign-submit jb-blue"><span><?php esc_html_e('重置密码', 'aksrt'); ?></span><i class="fa fas fa-spinner fa-spin" hidden></i></button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="sign-panel" data-auth-panel="oauth" <?php echo $auth_tab !== 'oauth' ? 'hidden' : ''; ?>>
|
||||
<section id="<?php echo esc_attr($unique); ?>-auth-panel-oauth" class="sign-panel" role="tabpanel" data-auth-panel="oauth" <?php echo $auth_tab !== 'oauth' ? 'hidden' : ''; ?>>
|
||||
<div class="sign-header"><h2><?php esc_html_e('社交登录', 'aksrt'); ?></h2><span><button type="button" data-auth-tab="signin"><?php esc_html_e('返回登录', 'aksrt'); ?></button></span></div>
|
||||
<?php if ($wechat_qr) : ?><div class="auth-qrcode" data-auth-qrcode><i class="fa fab fa-weixin"></i><span><?php esc_html_e('获取二维码中…', 'aksrt'); ?></span></div><?php endif; ?>
|
||||
<?php if ($wechat_qr) : ?><div class="auth-qrcode" data-auth-qrcode><div data-auth-qr-content><i class="fa fab fa-weixin" aria-hidden="true"></i><span><?php esc_html_e('获取二维码中…', 'aksrt'); ?></span></div><p class="auth-qrcode-status screen-reader-text" data-auth-qr-status role="status" aria-live="polite" aria-atomic="true"><?php esc_html_e('正在获取二维码', 'aksrt'); ?></p></div><?php endif; ?>
|
||||
</section>
|
||||
|
||||
<section class="sign-panel" data-auth-panel="bind" <?php echo $auth_tab !== 'bind' ? 'hidden' : ''; ?>>
|
||||
<section id="<?php echo esc_attr($unique); ?>-auth-panel-bind" class="sign-panel" role="tabpanel" data-auth-panel="bind" <?php echo $auth_tab !== 'bind' ? 'hidden' : ''; ?>>
|
||||
<div class="sign-header"><h2><?php esc_html_e('绑定账号', 'aksrt'); ?></h2><?php if ($is_oauth_bind && $registration_open) : ?><span><?php esc_html_e('没有账号?', 'aksrt'); ?> <button type="button" data-auth-tab="signup"><?php esc_html_e('立即注册', 'aksrt'); ?></button></span><?php endif; ?></div>
|
||||
<?php if ($is_oauth_bind) : ?>
|
||||
<div class="sign-notice"><?php printf(esc_html__('通过 %s 登录,请绑定已有账号。', 'aksrt'), esc_html($oauth_provider_name)); ?></div>
|
||||
<form class="sign-form" data-auth-form="login">
|
||||
<div class="floating-input"><input name="target" id="<?php echo esc_attr($unique); ?>-bind-target" autocomplete="username" required><label for="<?php echo esc_attr($unique); ?>-bind-target"><?php echo $signin_phone ? esc_html__('邮箱 / 手机号 / 用户名', 'aksrt') : esc_html__('邮箱 / 用户名', 'aksrt'); ?></label></div>
|
||||
<div class="floating-input has-action"><input type="password" name="password" id="<?php echo esc_attr($unique); ?>-bind-password" autocomplete="current-password" required><label for="<?php echo esc_attr($unique); ?>-bind-password"><?php esc_html_e('密码', 'aksrt'); ?></label><button type="button" class="password-show" data-password-show><i class="fa fas fa-eye"></i></button></div>
|
||||
<div class="floating-input has-action"><input type="password" name="password" id="<?php echo esc_attr($unique); ?>-bind-password" autocomplete="current-password" required><label for="<?php echo esc_attr($unique); ?>-bind-password"><?php esc_html_e('密码', 'aksrt'); ?></label><button type="button" class="password-show" data-password-show aria-label="<?php esc_attr_e('显示密码', 'aksrt'); ?>" aria-pressed="false"><i class="fa fas fa-eye"></i></button></div>
|
||||
<?php if (function_exists('aksrt_render_captcha')) { aksrt_render_captcha('bind'); } ?>
|
||||
<input type="hidden" name="obk" value="<?php echo esc_attr($obk); ?>">
|
||||
<input type="hidden" name="rememberme" value="1">
|
||||
@@ -133,8 +137,8 @@ $oauth_provider_name = $is_oauth_bind ? \AKSRT\Auth\Service::get_oauth_provider_
|
||||
|
||||
<?php if (!empty($oauth_providers) && !$is_oauth_bind) : ?>
|
||||
<div class="social-login"><span><?php esc_html_e('其他登录方式', 'aksrt'); ?></span><div class="social-login-buttons">
|
||||
<?php foreach ($oauth_providers as $provider) : ?><a class="social-login-item <?php echo esc_attr((string) ($provider['name'] ?? '')); ?>" href="<?php echo esc_url((string) ($provider['url'] ?? '#')); ?>" title="<?php echo esc_attr((string) ($provider['label'] ?? '')); ?>"><?php echo $provider['icon'] ?? ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?><?php if ($oauth_large) : ?><span><?php printf(esc_html__('%s登录', 'aksrt'), esc_html((string) ($provider['label'] ?? ''))); ?></span><?php endif; ?></a><?php endforeach; ?>
|
||||
<?php if ($wechat_qr) : ?><button type="button" class="social-login-item weixingzh" data-auth-tab="oauth" title="<?php esc_attr_e('微信扫码登录', 'aksrt'); ?>"><i class="fa fab fa-weixin"></i><?php if ($oauth_large) : ?><span><?php esc_html_e('微信登录', 'aksrt'); ?></span><?php endif; ?></button><?php endif; ?>
|
||||
<?php foreach ($oauth_providers as $provider) : ?><?php if (($provider['name'] ?? '') === 'weixingzh') continue; ?><?php $provider_label = (string) ($provider['label'] ?? $provider['name'] ?? ''); ?><a class="social-login-item <?php echo esc_attr((string) ($provider['name'] ?? '')); ?>" href="<?php echo esc_url((string) ($provider['url'] ?? '#')); ?>" data-provider="<?php echo esc_attr((string) ($provider['name'] ?? '')); ?>" aria-label="<?php echo esc_attr(sprintf(__('%s登录', 'aksrt'), $provider_label)); ?>" title="<?php echo esc_attr($provider_label); ?>"><?php echo $provider['icon'] ?? ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?><?php if ($oauth_large) : ?><span><?php printf(esc_html__('%s登录', 'aksrt'), esc_html($provider_label)); ?></span><?php endif; ?></a><?php endforeach; ?>
|
||||
<?php if ($wechat_qr) : ?><button type="button" class="social-login-item weixingzh" data-auth-tab="oauth" aria-label="<?php esc_attr_e('微信扫码登录', 'aksrt'); ?>" title="<?php esc_attr_e('微信扫码登录', 'aksrt'); ?>"><i class="fa fab fa-weixin" aria-hidden="true"></i><?php if ($oauth_large) : ?><span><?php esc_html_e('微信登录', 'aksrt'); ?></span><?php endif; ?></button><?php endif; ?>
|
||||
</div></div>
|
||||
<?php if (!empty($agreement['enabled'])) : ?><div class="sign-agreement sign-agreement-implicit"><?php esc_html_e('使用社交账号登录即表示', 'aksrt'); ?><?php echo $agreement['label_html']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></div><?php endif; ?>
|
||||
<?php endif; ?>
|
||||
|
||||
@@ -30,7 +30,8 @@ $aksrt_auth_context = [
|
||||
'redirect_to' => home_url('/'),
|
||||
];
|
||||
?>
|
||||
<div id="u_sign" class="aksrt-auth-modal<?php echo $image_html !== '' ? ' has-sign-img' : ''; ?>" aria-hidden="true" role="dialog" aria-modal="true" data-auth-modal data-auto="<?php echo !empty($auto['enabled']) ? '1' : '0'; ?>" data-auto-wait="<?php echo esc_attr((string) $auto['waiting']); ?>" data-auto-expires="<?php echo esc_attr((string) $auto['expires']); ?>">
|
||||
<div id="u_sign" class="aksrt-auth-modal<?php echo $image_html !== '' ? ' has-sign-img' : ''; ?>" aria-hidden="true" role="dialog" aria-modal="true" aria-labelledby="aksrt-auth-modal-title" tabindex="-1" data-auth-modal data-auto="<?php echo !empty($auto['enabled']) ? '1' : '0'; ?>" data-auto-wait="<?php echo esc_attr((string) $auto['waiting']); ?>" data-auto-expires="<?php echo esc_attr((string) $auto['expires']); ?>">
|
||||
<h2 id="aksrt-auth-modal-title" class="screen-reader-text"><?php esc_html_e('账户登录与注册', 'aksrt'); ?></h2>
|
||||
<div class="auth-modal-backdrop" data-auth-close></div>
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
|
||||
@@ -173,6 +173,12 @@ test('shared renderer contracts every configured authentication state', () => {
|
||||
assert.match(client, /aksrtAuthAutoUntil/);
|
||||
assert.match(client, /data-password-show/);
|
||||
assert.match(client, /pollQr/);
|
||||
assert.match(client, /AbortController/);
|
||||
assert.match(client, /refreshInFlight|inFlight/);
|
||||
assert.match(client, /visibilitychange/);
|
||||
assert.match(client, /Math\.pow\(2/);
|
||||
assert.match(client, /QR_TIMEOUT/);
|
||||
assert.match(client, /stopQr\(root\)/);
|
||||
assert.match(client, /window\.notyf\(escapeHtml\(text\), type \|\| 'info'\)/);
|
||||
assert.match(client, /notify\('请先完成人机验证', 'warning'\)/);
|
||||
assert.match(client, /form\.noValidate = true/);
|
||||
@@ -182,3 +188,47 @@ test('shared renderer contracts every configured authentication state', () => {
|
||||
assert.match(settings, /invitation_mode/);
|
||||
assert.match(settings, /\['close', 'open', 'must'\]/);
|
||||
});
|
||||
|
||||
test('OAuth frontend is accessible, redirect-aware, and removes retired providers', () => {
|
||||
const shared = read('templates/parts/auth-content.php');
|
||||
const modal = read('templates/parts/modal-auth.php');
|
||||
const client = read('assets/js/auth.js');
|
||||
const userCenter = read('assets/js/routes/user-center.js');
|
||||
const bindings = read('inc/helpers/user-center-renderers/settings-bindings.php');
|
||||
const signCss = read('assets/css/routes/sign.css');
|
||||
const mainCss = read('assets/css/main.css');
|
||||
|
||||
assert.match(modal, /role="dialog"[^>]*aria-modal="true"[^>]*aria-labelledby="aksrt-auth-modal-title"/);
|
||||
assert.match(modal, /id="aksrt-auth-modal-title"/);
|
||||
assert.match(client, /focusableModalItems/);
|
||||
assert.match(client, /lastModalTrigger/);
|
||||
assert.match(client, /restore\.focus\(\)/);
|
||||
assert.match(shared, /role="tabpanel"[^>]*data-auth-panel="signin"/);
|
||||
assert.match(shared, /role="tabpanel"[^>]*data-auth-panel="oauth"/);
|
||||
assert.match(client, /setAttribute\('role', 'tab'\)/);
|
||||
assert.match(client, /aria-controls/);
|
||||
assert.match(client, /aria-selected/);
|
||||
assert.match(shared, /data-password-show[^>]*aria-label=/);
|
||||
assert.match(shared, /aria-pressed="false"/);
|
||||
assert.match(client, /setAttribute\('aria-label', visible \? '隐藏密码' : '显示密码'\)/);
|
||||
assert.match(client, /setAttribute\('aria-pressed', visible \? 'true' : 'false'\)/);
|
||||
assert.match(shared, /data-auth-qr-status[^>]*role="status"[^>]*aria-live="polite"/);
|
||||
assert.match(shared, /data-provider=/);
|
||||
assert.match(shared, /aria-label="<\?php echo esc_attr\(sprintf/);
|
||||
assert.match(client, /searchParams\.set\('redirect_to', redirect\)/);
|
||||
|
||||
assert.match(client, /oauth_action/);
|
||||
assert.match(client, /oauth_provider/);
|
||||
assert.match(client, /oauth_error/);
|
||||
assert.match(client, /oauthErrorMessages/);
|
||||
assert.doesNotMatch(client, /notify\([^\n;]*searchParams\.get\('oauth_error'/);
|
||||
assert.match(userCenter, /errorMessages\[currentUrl\.searchParams\.get\('oauth_error'\)/);
|
||||
assert.match(userCenter, /result\.status === 409/);
|
||||
assert.match(userCenter, /d\.message \|\| \(d\.data && d\.data\.message\)/);
|
||||
assert.match(bindings, /\$binding\['provider'\] \?\? \$binding\['key'\]/);
|
||||
assert.match(bindings, /\$binding\['start_url'\] \?\? \$binding\['url'\]/);
|
||||
assert.match(bindings, /data-provider=/);
|
||||
|
||||
assert.doesNotMatch(signCss + mainCss, /social-login-item[^\n{]*(?:baidu|alipay)|social-login-item\.(?:baidu|alipay)/i);
|
||||
assert.match(mainCss, /\.pay-box \.but\.baidu/);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const test = require('node:test')
|
||||
const vm = require('node:vm')
|
||||
const { execFileSync } = require('node:child_process')
|
||||
|
||||
const root = path.resolve(__dirname, '..', '..')
|
||||
const read = (file) => fs.readFileSync(path.join(root, file), 'utf8')
|
||||
const walkFiles = (dir, extensions) => {
|
||||
const result = []
|
||||
for (const entry of fs.readdirSync(path.join(root, dir), { withFileTypes: true })) {
|
||||
const relative = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) result.push(...walkFiles(relative, extensions))
|
||||
else if (extensions.some((ext) => entry.name.endsWith(ext))) result.push(relative)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
const oauthScope = [
|
||||
'src/Auth/OAuth.php',
|
||||
'src/Auth/OAuthProviderCatalog.php',
|
||||
'src/Auth/OAuthProviderBroker.php',
|
||||
'src/Auth/OAuthAccountService.php',
|
||||
'src/Auth/OAuthProxyClient.php',
|
||||
'src/Auth/OAuthProxyServer.php',
|
||||
'src/Auth/CLoginClient.php',
|
||||
'src/Admin/Schema/SchemaUsers.php',
|
||||
'assets/admin/src/schema/sections/users/oauth.js',
|
||||
].map(read).join('\n')
|
||||
|
||||
test('OAuth PHP behavior harness passes', () => {
|
||||
const output = execFileSync('php', [path.join(root, 'tests/widget-system/oauth-security-harness.php')], { encoding: 'utf8' })
|
||||
assert.match(output, /OAuth security harness passed/)
|
||||
})
|
||||
test('Baidu and Alipay are absent from the OAuth surface', () => {
|
||||
for (const needle of [
|
||||
'oauth_baidu_s',
|
||||
'oauth_alipay_s',
|
||||
'get_baidu_user_data',
|
||||
'get_alipay_user_data',
|
||||
'OAuthLogin\\Baidu',
|
||||
'OAuthLogin\\Alipay',
|
||||
"'baidu' => [",
|
||||
"'alipay' => [",
|
||||
]) {
|
||||
assert.equal(oauthScope.includes(needle), false, `unexpected OAuth reference: ${needle}`)
|
||||
}
|
||||
})
|
||||
|
||||
test('Alipay payment remains available', () => {
|
||||
const functions = read('functions.php')
|
||||
const paymentSchema = read('src/Admin/Schema/SchemaPayment.php')
|
||||
const gateway = read('src/Payment/Gateways/AlipayGateway.php')
|
||||
assert.match(functions, /AlipayGateway/)
|
||||
assert.match(paymentSchema, /alipay_appid/)
|
||||
assert.match(paymentSchema, /alipay_privatekey/)
|
||||
assert.match(gateway, /class AlipayGateway/)
|
||||
})
|
||||
|
||||
test('OAuth uses one-time transactions and no PHP sessions', () => {
|
||||
const auth = fs.readdirSync(path.join(root, 'src', 'Auth'))
|
||||
.filter((name) => name.endsWith('.php'))
|
||||
.map((name) => read(path.join('src', 'Auth', name)))
|
||||
.join('\n')
|
||||
assert.match(auth, /OAuthTransactionStore::issue/)
|
||||
assert.match(auth, /OAuthTransactionStore::claim/)
|
||||
assert.equal(auth.includes('session_start('), false)
|
||||
assert.equal(auth.includes('$_SESSION'), false)
|
||||
})
|
||||
|
||||
test('provider catalog is the canonical provider list', () => {
|
||||
const catalog = read('src/Auth/OAuthProviderCatalog.php')
|
||||
for (const provider of ['github', 'gitee', 'qq', 'google', 'weibo', 'weixin']) {
|
||||
assert.match(catalog, new RegExp(`'${provider}'\\s*=>`))
|
||||
}
|
||||
assert.match(catalog, /CLOGIN_TYPES = \['qq', 'weixin', 'weibo'\]/)
|
||||
assert.match(catalog, /oauth_s/)
|
||||
assert.match(catalog, /oauth_bind_type/)
|
||||
})
|
||||
|
||||
test('verified email is required for email auto-linking', () => {
|
||||
const account = read('src/Auth/OAuthAccountService.php')
|
||||
const broker = read('src/Auth/OAuthProviderBroker.php')
|
||||
assert.match(account, /!empty\(\$identity\['email_verified'\]\)/)
|
||||
assert.match(broker, /primary.*verified/s)
|
||||
assert.match(broker, /email_verified.*Google|Google.*email_verified/s)
|
||||
})
|
||||
|
||||
test('OAuth secrets are marked and masked by the schema provider', () => {
|
||||
const phpSchema = read('src/Admin/Schema/SchemaUsers.php')
|
||||
const jsSchema = read('assets/admin/src/schema/sections/users/oauth.js')
|
||||
const provider = read('src/Admin/SchemaProvider.php')
|
||||
for (const key of [
|
||||
'oauth_proxy_secret',
|
||||
'github_appkey',
|
||||
'gitee_appkey',
|
||||
'qq_appkey',
|
||||
'google_client_secret',
|
||||
'weibo_appkey',
|
||||
'weixin_appsecret',
|
||||
'weixingzh_token',
|
||||
'weixingzh_appsecret',
|
||||
'clogin_key',
|
||||
]) {
|
||||
assert.match(phpSchema, new RegExp(`${key}[^\\n]+secret`))
|
||||
assert.match(jsSchema, new RegExp(`${key}[^\\n]+secret`))
|
||||
}
|
||||
assert.match(provider, /\*\*\*/)
|
||||
assert.match(provider, /!empty\(\$field\['secret'\]\)/)
|
||||
})
|
||||
|
||||
test('PHP and JavaScript OAuth schema field keys stay in parity', () => {
|
||||
const php = read('src/Admin/Schema/SchemaUsers.php')
|
||||
const js = read('assets/admin/src/schema/sections/users/oauth.js')
|
||||
const start = php.indexOf("'oauth' => [")
|
||||
const phpSection = php.slice(start, php.indexOf("'sms' => [", start))
|
||||
const phpKeys = [...phpSection.matchAll(/\['key' => '([^']+)', 'label'/g)].map((match) => match[1])
|
||||
const jsKeys = [...js.matchAll(/\{ key: '([^']+)', label:/g)].map((match) => match[1])
|
||||
assert.deepEqual([...new Set(phpKeys)].sort(), [...new Set(jsKeys)].sort())
|
||||
})
|
||||
test('OAuth result handler maps safe errors and preserves unrelated URL state', () => {
|
||||
const notices = []
|
||||
let replaced = ''
|
||||
const listeners = {}
|
||||
const location = new URL('https://site.test/sign/?oauth_action=error&oauth_provider=github&oauth_error=%3Cscript%3E&keep=1#section')
|
||||
const documentElement = { dataset: {}, contains: () => true }
|
||||
const document = {
|
||||
readyState: 'complete',
|
||||
documentElement,
|
||||
visibilityState: 'visible',
|
||||
querySelectorAll: () => [],
|
||||
querySelector: () => null,
|
||||
addEventListener: (name, fn) => { listeners[name] = fn },
|
||||
activeElement: null,
|
||||
body: { classList: { add() {}, remove() {} } },
|
||||
}
|
||||
const window = {
|
||||
aksrtData: {},
|
||||
URL,
|
||||
location,
|
||||
history: { replaceState: (_state, _title, value) => { replaced = value } },
|
||||
notyf: (message, type) => notices.push({ message, type }),
|
||||
matchMedia: () => ({ matches: false }),
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
setInterval,
|
||||
clearInterval,
|
||||
localStorage: { getItem: () => null, setItem() {} },
|
||||
}
|
||||
vm.runInNewContext(read('assets/js/auth.js'), {
|
||||
window,
|
||||
document,
|
||||
URL,
|
||||
FormData: class {},
|
||||
fetch: () => Promise.reject(new Error('unexpected fetch')),
|
||||
console,
|
||||
CustomEvent: class {},
|
||||
AbortController,
|
||||
Date,
|
||||
Math,
|
||||
Promise,
|
||||
})
|
||||
assert.deepEqual(notices, [{ message: '第三方授权失败,请重试', type: 'danger' }])
|
||||
assert.equal(replaced, '/sign/?keep=1#section')
|
||||
assert.equal(replaced.includes('script'), false)
|
||||
})
|
||||
test('obsolete OAuth admin routes and components are removed', () => {
|
||||
const controller = read('src/Admin/UserController.php')
|
||||
const usersApi = read('assets/admin/src/api/modules/users.js')
|
||||
assert.equal(controller.includes("'/settings/oauth'"), false)
|
||||
assert.equal(controller.includes("'/settings/oauth-proxy'"), false)
|
||||
assert.equal(usersApi.includes('getOAuthSettings'), false)
|
||||
assert.equal(usersApi.includes('saveOAuthSettings'), false)
|
||||
assert.equal(fs.existsSync(path.join(root, 'assets/admin/src/components/OAuthProviderForm.vue')), false)
|
||||
assert.equal(fs.existsSync(path.join(root, 'assets/admin/src/pages/users/UsersSectionPage.vue')), false)
|
||||
})
|
||||
@@ -0,0 +1,156 @@
|
||||
<?php
|
||||
/**
|
||||
* Minimal executable harness for OAuth transaction, proxy, URL, and secret behavior.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace {
|
||||
|
||||
define('ABSPATH', __DIR__ . '/');
|
||||
define('MINUTE_IN_SECONDS', 60);
|
||||
define('MONTH_IN_SECONDS', 2592000);
|
||||
define('ARRAY_A', 'ARRAY_A');
|
||||
|
||||
$GLOBALS['wp_options'] = [];
|
||||
$GLOBALS['wp_cache'] = [];
|
||||
|
||||
function __(string $text, string $domain = ''): string { return $text; }
|
||||
function sanitize_key(string $value): string { return preg_replace('/[^a-z0-9_\-]/', '', strtolower($value)) ?? ''; }
|
||||
function sanitize_text_field(string $value): string { return trim(strip_tags($value)); }
|
||||
function esc_url_raw(string $value): string { return trim($value); }
|
||||
function wp_unslash($value) { return $value; }
|
||||
function wp_parse_url(string $url) { return parse_url($url); }
|
||||
function wp_generate_uuid4(): string { return '00000000-0000-4000-8000-' . substr(bin2hex(random_bytes(6)), 0, 12); }
|
||||
function wp_salt(string $scheme = 'auth'): string { return 'harness-salt-' . $scheme; }
|
||||
function is_ssl(): bool { return true; }
|
||||
function maybe_serialize($value): string { return serialize($value); }
|
||||
function maybe_unserialize($value) { $result = @unserialize((string) $value); return $result === false && $value !== serialize(false) ? $value : $result; }
|
||||
function wp_cache_delete(string $key, string $group = ''): void { unset($GLOBALS['wp_cache'][$group][$key]); }
|
||||
function get_option(string $key, $default = false) { return array_key_exists($key, $GLOBALS['wp_options']) ? $GLOBALS['wp_options'][$key] : $default; }
|
||||
function add_option(string $key, $value, string $deprecated = '', bool $autoload = true): bool {
|
||||
if (array_key_exists($key, $GLOBALS['wp_options'])) return false;
|
||||
$GLOBALS['wp_options'][$key] = $value;
|
||||
return true;
|
||||
}
|
||||
function update_option(string $key, $value, $autoload = null): bool {
|
||||
$changed = !array_key_exists($key, $GLOBALS['wp_options']) || $GLOBALS['wp_options'][$key] !== $value;
|
||||
$GLOBALS['wp_options'][$key] = $value;
|
||||
return $changed;
|
||||
}
|
||||
function delete_option(string $key): bool {
|
||||
if (!array_key_exists($key, $GLOBALS['wp_options'])) return false;
|
||||
unset($GLOBALS['wp_options'][$key]);
|
||||
return true;
|
||||
}
|
||||
function get_template_directory_uri(): string { return 'https://example.com/theme'; }
|
||||
function get_theme_file_uri(string $path = ''): string { return 'https://example.com/theme/' . ltrim($path, '/'); }
|
||||
function get_theme_file_path(string $path = ''): string { return dirname(__DIR__, 2) . '/' . ltrim($path, '/'); }
|
||||
function sanitize_email(string $value): string { return filter_var($value, FILTER_VALIDATE_EMAIL) ? $value : ''; }
|
||||
function esc_html__(string $value, string $domain = ''): string { return $value; }
|
||||
|
||||
final class HarnessWpdb {
|
||||
public string $options = 'wp_options';
|
||||
public function prepare(string $query, ...$args): array { return [$query, $args]; }
|
||||
public function esc_like(string $value): string { return $value; }
|
||||
public function query($prepared): int {
|
||||
[$query, $args] = $prepared;
|
||||
if (str_starts_with(ltrim($query), 'DELETE')) {
|
||||
[$key, $serialized] = $args;
|
||||
if (!array_key_exists($key, $GLOBALS['wp_options']) || serialize($GLOBALS['wp_options'][$key]) !== $serialized) return 0;
|
||||
unset($GLOBALS['wp_options'][$key]);
|
||||
return 1;
|
||||
}
|
||||
if (str_starts_with(ltrim($query), 'UPDATE')) {
|
||||
[$new, $key, $old] = $args;
|
||||
if (!array_key_exists($key, $GLOBALS['wp_options']) || serialize($GLOBALS['wp_options'][$key]) !== $old) return 0;
|
||||
$GLOBALS['wp_options'][$key] = unserialize($new);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
public function get_results($prepared, $format): array { return []; }
|
||||
}
|
||||
$GLOBALS['wpdb'] = new HarnessWpdb();
|
||||
}
|
||||
|
||||
namespace AKSRT\Settings {
|
||||
final class Settings {
|
||||
public static function flush_settings_cache(): void {}
|
||||
public static function sync_native_site_icon(string $value): void {}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__, 2) . '/src/Auth/OAuthTransactionStore.php';
|
||||
require dirname(__DIR__, 2) . '/src/Auth/OAuthUrlPolicy.php';
|
||||
require dirname(__DIR__, 2) . '/src/Auth/OAuthProxyProtocol.php';
|
||||
require dirname(__DIR__, 2) . '/src/Admin/Schema/SchemaUsers.php';
|
||||
require dirname(__DIR__, 2) . '/src/Admin/SchemaProvider.php';
|
||||
|
||||
function check(bool $condition, string $message): void {
|
||||
if (!$condition) throw new RuntimeException($message);
|
||||
}
|
||||
|
||||
$_COOKIE['aksrt_oauth_browser'] = str_repeat('A', 43);
|
||||
$token = \AKSRT\Auth\OAuthTransactionStore::issue('direct', ['provider' => 'github'], 60, true);
|
||||
check(\AKSRT\Auth\OAuthTransactionStore::peek($token, 'direct', true) !== null, 'transaction peek failed');
|
||||
check(\AKSRT\Auth\OAuthTransactionStore::peek($token, 'other', true) === null, 'transaction kind mismatch accepted');
|
||||
$_COOKIE['aksrt_oauth_browser'] = str_repeat('B', 43);
|
||||
check(\AKSRT\Auth\OAuthTransactionStore::claim($token, 'direct', true) === null, 'wrong browser claimed transaction');
|
||||
$_COOKIE['aksrt_oauth_browser'] = str_repeat('A', 43);
|
||||
check(\AKSRT\Auth\OAuthTransactionStore::claim($token, 'direct', true) !== null, 'valid browser failed claim');
|
||||
check(\AKSRT\Auth\OAuthTransactionStore::claim($token, 'direct', true) === null, 'transaction replay accepted');
|
||||
|
||||
$expired = \AKSRT\Auth\OAuthTransactionStore::issue('direct', [], 30, true);
|
||||
foreach ($GLOBALS['wp_options'] as $key => $row) {
|
||||
if (is_array($row) && ($row['kind'] ?? '') === 'direct') $GLOBALS['wp_options'][$key]['expires_at'] = time() - 1;
|
||||
}
|
||||
check(\AKSRT\Auth\OAuthTransactionStore::peek($expired, 'direct', true) === null, 'expired transaction accepted');
|
||||
|
||||
$request = [
|
||||
'v' => '2', 'request_id' => str_repeat('C', 43), 'provider' => 'github', 'action' => 'login',
|
||||
'agent_back_url' => 'https://example.com/oauth/proxy/callback/', 'ts' => (string) time(),
|
||||
];
|
||||
$secret = 'test-secret-value';
|
||||
$requestSign = \AKSRT\Auth\OAuthProxyProtocol::sign_request($request, $secret);
|
||||
check(\AKSRT\Auth\OAuthProxyProtocol::verify_request($request, $secret, $requestSign), 'request signature failed');
|
||||
check(!\AKSRT\Auth\OAuthProxyProtocol::verify_callback($request, $secret, $requestSign), 'direction-separated HMAC failed');
|
||||
$tampered = $request; $tampered['provider'] = 'qq';
|
||||
check(!\AKSRT\Auth\OAuthProxyProtocol::verify_request($tampered, $secret, $requestSign), 'tampered request accepted');
|
||||
check(!\AKSRT\Auth\OAuthProxyProtocol::timestamp_valid((string) (time() - 1000)), 'expired timestamp accepted');
|
||||
|
||||
check(\AKSRT\Auth\OAuthUrlPolicy::public_https('http://example.com') === '', 'HTTP URL accepted');
|
||||
check(\AKSRT\Auth\OAuthUrlPolicy::public_https('https://user@example.com') === '', 'userinfo URL accepted');
|
||||
check(\AKSRT\Auth\OAuthUrlPolicy::public_https('https://127.0.0.1') === '', 'loopback URL accepted');
|
||||
check(\AKSRT\Auth\OAuthUrlPolicy::public_https('https://10.0.0.1') === '', 'private URL accepted');
|
||||
check(\AKSRT\Auth\OAuthProxyProtocol::callback_url('https://example.com/wrong') === '', 'wrong callback path accepted');
|
||||
|
||||
$provider = \AKSRT\Admin\SchemaProvider::get_instance();
|
||||
$base = $provider->get_defaults('users', 'oauth');
|
||||
$base['oauth_s'] = true;
|
||||
$base['oauth_weixingzh_s'] = true;
|
||||
$base['weixingzh_gzh_type'] = 'service';
|
||||
$base['weixingzh_appid'] = 'appid';
|
||||
$base['weixingzh_appsecret'] = 'secret';
|
||||
$base['weixingzh_token'] = '***';
|
||||
$GLOBALS['wp_options']['aksrt_settings'] = [];
|
||||
check(!$provider->validate('users', $base, 'oauth')['valid'], 'masked missing token treated as configured');
|
||||
$GLOBALS['wp_options']['aksrt_settings'] = ['weixingzh_token' => 'stored-token'];
|
||||
check($provider->validate('users', $base, 'oauth')['valid'], 'stored token not preserved by mask validation');
|
||||
|
||||
$provider->write_settings('users', ['weixingzh_token' => '***'], 'oauth');
|
||||
check($GLOBALS['wp_options']['aksrt_settings']['weixingzh_token'] === 'stored-token', 'masked token overwrote stored secret');
|
||||
$provider->write_settings('users', ['weixingzh_token' => 'replacement'], 'oauth');
|
||||
check($GLOBALS['wp_options']['aksrt_settings']['weixingzh_token'] === 'replacement', 'new token failed to replace secret');
|
||||
$provider->write_settings('users', ['__clear_secrets' => ['weixingzh_token']], 'oauth');
|
||||
check(!isset($GLOBALS['wp_options']['aksrt_settings']['weixingzh_token']), 'explicit secret clear failed');
|
||||
$GLOBALS['wp_options']['aksrt_settings']['weixingzh_token'] = 'final-token';
|
||||
$clearData = $base;
|
||||
$clearData['weixingzh_token'] = '***';
|
||||
$clearData['__clear_secrets'] = ['weixingzh_token'];
|
||||
check(!$provider->validate('users', $clearData, 'oauth')['valid'], 'active provider allowed required secret clear');
|
||||
check($provider->read_settings('users', 'oauth')['weixingzh_token'] === '***', 'secret read was not masked');
|
||||
|
||||
echo "OAuth security harness passed.\n";
|
||||
}
|
||||
@@ -352,7 +352,7 @@ test('settings actions use rehydrated fixed-id notyf flows', () => {
|
||||
assert.match(userCenter, /notyf\([^;]+?'danger'[^;]+?toastId\);/);
|
||||
assert.match(userCenter, /register\('aksrt-settings',[\s\S]*?initSettings\(root\);[\s\S]*?initBindPhone\(root\);/);
|
||||
assert.match(userCenter, /aksrtSettingsInitialized/);
|
||||
assert.match(userCenter, /oauth_bound[\s\S]*?notyf\([^;]+?'success'\)[\s\S]*?history\.replaceState/);
|
||||
assert.match(userCenter, /oauth_action[\s\S]*?notyf\(message, type\)[\s\S]*?history\.replaceState/);
|
||||
assert.doesNotMatch(userCenter, /oauth_unbound/);
|
||||
|
||||
assert.match(userCenter, /'aksrt-settings-phone-code-toast'/);
|
||||
|
||||
Reference in New Issue
Block a user