feat: 人机验证可开关 + 登录注册入口白名单

- 系统设置新增「人机验证」页: 总开关 + 按入口勾选
- 客户端 verify/activate/check-update 永不校验 Turnstile
- 公开 GET /api/public/turnstile-config 供登录页按需展示组件
This commit is contained in:
root committed 2026-10-11 23:58:47 +08:00
1 parent 217c083544
commit 7c85ecdd2d
9 files changed
+262 -21

No files matched your search

+5 -4
View File
@@ -53,9 +53,10 @@ class AuthController extends Controller
$this->error('请输入用户名或邮箱');
}
// Cloudflare Turnstile 人机验证
// Cloudflare Turnstile(按系统配置开关与入口白名单)
$portalKey = $portal === 'agent' ? 'agent_login' : 'admin_login';
$turnstileToken = trim((string) ($input['turnstile_token'] ?? ''));
if (!TurnstileService::verify($turnstileToken !== '' ? $turnstileToken : null, clientIp())) {
if (!TurnstileService::verifyFor($portalKey, $turnstileToken !== '' ? $turnstileToken : null, clientIp())) {
$this->error('人机验证失败,请完成验证后重试');
}
@@ -132,9 +133,9 @@ class AuthController extends Controller
$this->error('两次输入的密码不一致');
}
// Cloudflare Turnstile 人机验证
// Cloudflare Turnstile(按系统配置开关与入口白名单)
$turnstileToken = trim((string) ($input['turnstile_token'] ?? ''));
if (!TurnstileService::verify($turnstileToken !== '' ? $turnstileToken : null, clientIp())) {
if (!TurnstileService::verifyFor('agent_register', $turnstileToken !== '' ? $turnstileToken : null, clientIp())) {
$this->error('人机验证失败,请完成验证后重试');
}
@@ -6,6 +6,7 @@ use App\Core\Database;
use App\Core\Validator;
use App\Services\InstallationService;
use App\Services\VersionService;
use App\Services\TurnstileService;
/**
* 公开接口控制器
@@ -746,6 +747,21 @@ class PublicController extends Controller
$this->success(['valid' => false, 'message' => '卡密状态异常'], 'ok');
}
/**
* 人机验证公开配置(前端登录页判断是否展示组件)
* GET /api/public/turnstile-config
* 注意:客户端 verify/activate/check-update 等接口从不校验 Turnstile
*/
public function turnstileConfig(): void
{
$c = \App\Services\TurnstileService::config();
$this->success([
'enabled' => $c['enabled'] === 1 && $c['site_key'] !== '',
'site_key' => $c['site_key'],
'endpoints' => $c['endpoints'],
], 'ok');
}
/**
* 获取公告列表(公开/客户端)
* GET /api/public/announcements?target=client&project_id=1&limit=10
+86
View File
@@ -1,13 +1,99 @@
<?php
namespace App\Services;
use App\Core\Database;
/**
* Cloudflare Turnstile 人机验证
* 可通过系统配置开关,并按登录/注册入口白名单启用
*/
class TurnstileService
{
/** 可选启用的入口标识 */
public const ENDPOINTS = [
'admin_login' => '管理员登录',
'agent_login' => '代理登录',
'agent_register'=> '代理注册',
];
/**
* 读取配置缓存
* @return array{enabled:int, endpoints:array<int,string>, secret:string, site_key:string}
*/
public static function config(): array
{
static $cache = null;
if ($cache !== null) {
return $cache;
}
$enabled = true;
$endpoints = array_keys(self::ENDPOINTS);
try {
$db = Database::getInstance();
$rows = $db->fetchAll(
"SELECT `key`, `value` FROM {$db->table('configs')} WHERE `key` IN ('turnstile_enabled','turnstile_endpoints')"
);
$map = [];
foreach ($rows as $r) {
$map[$r['key']] = $r['value'];
}
if (isset($map['turnstile_enabled'])) {
$enabled = (string) $map['turnstile_enabled'] === '1';
}
if (isset($map['turnstile_endpoints']) && trim($map['turnstile_endpoints']) !== '') {
$parts = array_filter(array_map('trim', explode(',', $map['turnstile_endpoints'])));
$endpoints = array_values(array_intersect(array_keys(self::ENDPOINTS), $parts));
}
} catch (\Throwable $e) {
// 配置表不可用时保持默认:启用且仅登录注册
}
$cache = [
'enabled' => $enabled ? 1 : 0,
'endpoints' => $endpoints,
'secret' => (string) config('app.turnstile.secret_key', ''),
'site_key' => (string) config('app.turnstile.site_key', ''),
];
return $cache;
}
/**
* 全局是否启用人机验证
*/
public static function isEnabled(): bool
{
$c = self::config();
return $c['enabled'] === 1 && $c['secret'] !== '';
}
/**
* 指定入口是否需要人机验证
* @param string $endpoint admin_login|agent_login|agent_register
*/
public static function requiredFor(string $endpoint): bool
{
if (!self::isEnabled()) {
return false;
}
$c = self::config();
return in_array($endpoint, $c['endpoints'], true);
}
/**
* 校验 Turnstile token
* @param string $endpoint 入口标识
*/
public static function verifyFor(string $endpoint, ?string $token, ?string $remoteIp = null): bool
{
if (!self::requiredFor($endpoint)) {
return true;
}
return self::verify($token, $remoteIp);
}
/**
* 校验 Turnstile token(强制)
* 未配置 secret 时跳过校验(便于本地开发)
*/
public static function verify(?string $token, ?string $remoteIp = null): bool
+3
View File
@@ -47,6 +47,9 @@ $router->group('api/public', function ($router) {
// 公告推送(客户端/商城)
$router->get('announcements', [PublicController::class, 'announcements']);
// 人机验证公开配置(登录页用;客户端激活/验证接口从不校验)
$router->get('turnstile-config', [PublicController::class, 'turnstileConfig']);
// 支付方式(前台展示用)
$router->get('payment/options', [PublicController::class, 'paymentOptions']);
+25 -4
View File
@@ -6,10 +6,12 @@
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
const props = defineProps({
siteKey: { type: String, default: '' }
siteKey: { type: String, default: '' },
/** 是否需要展示(由页面根据系统配置决定) */
required: { type: Boolean, default: true }
})
const emit = defineEmits(['update:token', 'expired', 'error'])
@@ -29,7 +31,8 @@ function loadScript() {
}
function renderWidget() {
if (!props.siteKey || !window.turnstile || !el.value) return
if (!props.required || !props.siteKey || !window.turnstile || !el.value) return
if (widgetId != null) return
widgetId = window.turnstile.render(el.value, {
sitekey: props.siteKey,
size: 'flexible',
@@ -48,7 +51,7 @@ function renderWidget() {
}
onMounted(async () => {
if (!props.siteKey) return
if (!props.required || !props.siteKey) return
try {
await loadScript()
renderWidget()
@@ -57,6 +60,24 @@ onMounted(async () => {
}
})
watch(() => props.required, async (v) => {
if (!v) {
emit('update:token', '')
if (widgetId != null && window.turnstile) {
try { window.turnstile.remove(widgetId) } catch {}
widgetId = null
}
return
}
try {
await loadScript()
// 等 DOM 挂载
setTimeout(renderWidget, 50)
} catch (e) {
console.error(e)
}
})
onBeforeUnmount(() => {
if (widgetId != null && window.turnstile) {
try { window.turnstile.remove(widgetId) } catch {}
+16 -4
View File
@@ -30,8 +30,8 @@
@keyup.enter="handleLogin"
/>
</el-form-item>
<el-form-item>
<TurnstileWidget ref="turnstileRef" :site-key="TURNSTILE_SITE_KEY" @update:token="onToken" />
<el-form-item v-if="tsEnabled">
<TurnstileWidget ref="turnstileRef" :site-key="TURNSTILE_SITE_KEY" :required="tsEnabled" @update:token="onToken" />
</el-form-item>
<el-form-item>
<el-button type="primary" :loading="loading" style="width:100%" size="large" @click="handleLogin">
@@ -44,12 +44,13 @@
</template>
<script setup>
import { ref, reactive } from 'vue'
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import TurnstileWidget from '@/components/TurnstileWidget.vue'
import { TURNSTILE_SITE_KEY } from '@/config/turnstile'
import request from '@/api'
const router = useRouter()
const userStore = useUserStore()
@@ -57,12 +58,23 @@ const loading = ref(false)
const formRef = ref(null)
const turnstileRef = ref(null)
const turnstileToken = ref('')
const tsEnabled = ref(false)
const form = reactive({ username: '', password: '' })
const rules = {
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}
onMounted(async () => {
try {
const res = await request.get('/public/turnstile-config')
const d = res.data || {}
tsEnabled.value = !!d.enabled && Array.isArray(d.endpoints) && d.endpoints.includes('admin_login')
} catch {
tsEnabled.value = false
}
})
function onToken(t) {
turnstileToken.value = t || ''
}
@@ -71,7 +83,7 @@ async function handleLogin() {
if (!formRef.value) return
await formRef.value.validate(async (valid) => {
if (!valid) return
if (TURNSTILE_SITE_KEY && !turnstileToken.value) {
if (tsEnabled.value && !turnstileToken.value) {
ElMessage.warning('请先完成人机验证')
turnstileRef.value?.reset?.()
return
+83 -1
View File
@@ -134,6 +134,45 @@
</el-form>
</el-card>
</el-tab-pane>
<!-- 人机验证 Turnstile -->
<el-tab-pane name="turnstile" label="人机验证">
<template #label>
<span><el-icon><Key /></el-icon> 人机验证</span>
</template>
<el-card shadow="never" class="config-card" v-loading="turnstileLoading">
<template #header>
<div class="card-header">
<span>Cloudflare Turnstile 人机验证</span>
<el-switch v-model="turnstileForm.turnstile_enabled" active-text="启用" inactive-text="关闭" :active-value="'1'" :inactive-value="'0'" inline-prompt style="--el-switch-on-color:#22c55e" />
</div>
</template>
<el-alert type="info" :closable="false" show-icon style="margin-bottom:16px">
<template #default>
<p style="margin:0">客户端 API(卡密验证 / 在线激活 / 安装检查更新等)<b>从不</b>启用人机验证,不影响终端客户使用。</p>
<p style="margin:4px 0 0">仅可选择对后台/代理<b>登录注册</b>入口启用。密钥在服务器 .env 中配置,此处只做开关。</p>
</template>
</el-alert>
<el-form label-width="140px" label-position="right">
<el-form-item label="启用入口">
<el-checkbox-group v-model="turnstileForm.turnstile_endpoints">
<el-checkbox value="admin_login">管理员登录</el-checkbox>
<el-checkbox value="agent_login">代理登录</el-checkbox>
<el-checkbox value="agent_register">代理注册</el-checkbox>
</el-checkbox-group>
<div class="form-tip">勾选的入口才会要求人机验证;客户端激活相关接口始终关闭</div>
</el-form-item>
<el-form-item label="状态">
<el-tag v-if="turnstileForm.turnstile_enabled==='1'" type="success">已启用人机验证</el-tag>
<el-tag v-else type="info">已关闭(全部入口跳过验证)</el-tag>
</el-form-item>
<el-form-item>
<el-button type="primary" :loading="turnstileSubmitting" @click="handleSaveTurnstile" :icon="Check">保存配置</el-button>
<el-button @click="fetchTurnstileConfig" :icon="RefreshRight">重置</el-button>
</el-form-item>
</el-form>
</el-card>
</el-tab-pane>
</el-tabs>
</div>
</template>
@@ -141,7 +180,7 @@
<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { OfficeBuilding, User, Check, RefreshRight, Message, Promotion } from '@element-plus/icons-vue'
import { OfficeBuilding, User, Check, RefreshRight, Message, Promotion, Key } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import request from '@/api'
@@ -190,6 +229,7 @@ onMounted(() => {
fetchSiteConfig()
fetchProfile()
fetchSmtpConfig()
fetchTurnstileConfig()
})
async function fetchSiteConfig() {
@@ -271,6 +311,48 @@ async function handleSaveProfile() {
})
}
// ========== 人机验证配置 ==========
const turnstileLoading = ref(false)
const turnstileSubmitting = ref(false)
const turnstileForm = ref({
turnstile_enabled: '1',
turnstile_endpoints: ['admin_login', 'agent_login', 'agent_register'],
})
async function fetchTurnstileConfig() {
turnstileLoading.value = true
try {
const res = await request.get('/system/configs', {
params: { keys: 'turnstile_enabled,turnstile_endpoints' }
})
const data = res.data || {}
turnstileForm.value.turnstile_enabled = data.turnstile_enabled ?? '1'
const ep = (data.turnstile_endpoints ?? 'admin_login,agent_login,agent_register') + ''
turnstileForm.value.turnstile_endpoints = ep
.split(',')
.map(s => s.trim())
.filter(Boolean)
} catch {
// defaults
} finally {
turnstileLoading.value = false
}
}
async function handleSaveTurnstile() {
turnstileSubmitting.value = true
try {
await request.post('/system/configs', {
configs: {
turnstile_enabled: turnstileForm.value.turnstile_enabled,
turnstile_endpoints: turnstileForm.value.turnstile_endpoints.join(','),
}
})
ElMessage.success('人机验证配置保存成功')
} catch (e) { /* handled */ }
finally { turnstileSubmitting.value = false }
}
// ========== SMTP 配置 ==========
const smtpFormRef = ref(null)
const smtpLoading = ref(false)
+13 -4
View File
@@ -43,8 +43,8 @@
<el-link type="primary" :underline="false" @click="handleForgotPassword">忘记密码?</el-link>
</div>
<el-form-item>
<TurnstileWidget ref="turnstileRef" :site-key="TURNSTILE_SITE_KEY" @update:token="onToken" />
<el-form-item v-if="tsEnabled">
<TurnstileWidget ref="turnstileRef" :site-key="TURNSTILE_SITE_KEY" :required="tsEnabled" @update:token="onToken" />
</el-form-item>
<el-form-item>
@@ -70,6 +70,7 @@ import { User, Lock, Avatar } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import TurnstileWidget from '@/components/TurnstileWidget.vue'
import { TURNSTILE_SITE_KEY } from '@/config/turnstile'
import request from '@/api'
const router = useRouter()
const userStore = useUserStore()
@@ -77,6 +78,7 @@ const loading = ref(false)
const formRef = ref(null)
const turnstileRef = ref(null)
const turnstileToken = ref('')
const tsEnabled = ref(false)
function onToken(t) {
turnstileToken.value = t || ''
@@ -93,19 +95,26 @@ const rules = {
password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}
onMounted(() => {
onMounted(async () => {
const saved = localStorage.getItem('agent_remember_account')
if (saved) {
form.account = saved
form.remember = true
}
try {
const res = await request.get('/public/turnstile-config')
const d = res.data || {}
tsEnabled.value = !!d.enabled && Array.isArray(d.endpoints) && d.endpoints.includes('agent_login')
} catch {
tsEnabled.value = false
}
})
async function handleLogin() {
if (!formRef.value) return
await formRef.value.validate(async (valid) => {
if (!valid) return
if (TURNSTILE_SITE_KEY && !turnstileToken.value) {
if (tsEnabled.value && !turnstileToken.value) {
ElMessage.warning('请先完成人机验证')
turnstileRef.value?.reset?.()
return
+15 -4
View File
@@ -73,8 +73,8 @@
</el-checkbox>
</el-form-item>
<el-form-item>
<TurnstileWidget ref="turnstileRef" :site-key="TURNSTILE_SITE_KEY" @update:token="onToken" />
<el-form-item v-if="tsEnabled">
<TurnstileWidget ref="turnstileRef" :site-key="TURNSTILE_SITE_KEY" :required="tsEnabled" @update:token="onToken" />
</el-form-item>
<el-form-item>
@@ -93,7 +93,7 @@
</template>
<script setup>
import { ref, reactive, computed } from 'vue'
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Phone, Ticket } from '@element-plus/icons-vue'
@@ -106,11 +106,22 @@ const loading = ref(false)
const formRef = ref(null)
const turnstileRef = ref(null)
const turnstileToken = ref('')
const tsEnabled = ref(false)
function onToken(t) {
turnstileToken.value = t || ''
}
onMounted(async () => {
try {
const res = await request.get('/public/turnstile-config')
const d = res.data || {}
tsEnabled.value = !!d.enabled && Array.isArray(d.endpoints) && d.endpoints.includes('agent_register')
} catch {
tsEnabled.value = false
}
})
const form = reactive({
username: '',
email: '',
@@ -197,7 +208,7 @@ async function handleRegister() {
if (!formRef.value) return
await formRef.value.validate(async (valid) => {
if (!valid) return
if (TURNSTILE_SITE_KEY && !turnstileToken.value) {
if (tsEnabled.value && !turnstileToken.value) {
ElMessage.warning('请先完成人机验证')
turnstileRef.value?.reset?.()
return