feat: 登录有效期24小时 + Cloudflare Turnstile 人机验证
- jwt_ttl 7200 → 86400 (24h) - 管理登录/代理登录/代理注册 接入 Turnstile - 前端 TurnstileWidget 组件, 未完成验证不可提交 - 密钥通过 env TURNSTILE_SITE_KEY/SECRET_KEY 配置
This commit is contained in:
1 parent
5b73d0921d
commit
e90ade2ba0
10 files changed
+230
-12
No files matched your search
@@ -236,7 +236,7 @@ curl -s http://your-domain/api/cron/notify-expiring
|
||||
|
||||
| 类型 | 说明 |
|
||||
|------|------|
|
||||
| **JWT Token** | 登录后获取,请求头 `Authorization: Bearer <token>`,有效期 24 小时 |
|
||||
| **JWT Token** | 登录后获取,请求头 `Authorization: Bearer <token>`,有效期 **24 小时** |
|
||||
| **API Key** | 项目密钥,仅用于授权验证接口,请求头 `X-Api-Key: <key>` |
|
||||
| **公开接口** | 无需认证,有频率限制(60秒内 30 次) |
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ use App\Core\Application;
|
||||
use App\Core\Database;
|
||||
use App\Core\Validator;
|
||||
use App\Services\JwtService;
|
||||
use App\Services\TurnstileService;
|
||||
|
||||
/**
|
||||
* 认证控制器
|
||||
@@ -52,6 +53,12 @@ class AuthController extends Controller
|
||||
$this->error('请输入用户名或邮箱');
|
||||
}
|
||||
|
||||
// Cloudflare Turnstile 人机验证
|
||||
$turnstileToken = trim((string) ($input['turnstile_token'] ?? ''));
|
||||
if (!TurnstileService::verify($turnstileToken !== '' ? $turnstileToken : null, clientIp())) {
|
||||
$this->error('人机验证失败,请完成验证后重试');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
|
||||
// 根据是否包含@选择查询方式
|
||||
@@ -125,6 +132,12 @@ class AuthController extends Controller
|
||||
$this->error('两次输入的密码不一致');
|
||||
}
|
||||
|
||||
// Cloudflare Turnstile 人机验证
|
||||
$turnstileToken = trim((string) ($input['turnstile_token'] ?? ''));
|
||||
if (!TurnstileService::verify($turnstileToken !== '' ? $turnstileToken : null, clientIp())) {
|
||||
$this->error('人机验证失败,请完成验证后重试');
|
||||
}
|
||||
|
||||
// 手机号格式验证
|
||||
if (!preg_match('/^1[3-9]\d{9}$/', $input['phone'])) {
|
||||
$this->error('手机号格式不正确');
|
||||
@@ -255,12 +268,18 @@ class AuthController extends Controller
|
||||
$this->error($validator->getFirstError());
|
||||
}
|
||||
|
||||
$user = $this->getCurrentUser();
|
||||
if (!passwordVerify($input['old_password'], $user['password'])) {
|
||||
$db = Database::getInstance();
|
||||
$user = $db->fetch(
|
||||
"SELECT * FROM {$db->table('users')} WHERE id = ? AND deleted_at IS NULL",
|
||||
[$this->getUserId()]
|
||||
);
|
||||
if (!$user) {
|
||||
$this->error('用户不存在');
|
||||
}
|
||||
if (empty($user['password']) || !passwordVerify($input['old_password'], $user['password'])) {
|
||||
$this->error('原密码错误');
|
||||
}
|
||||
|
||||
$db = Database::getInstance();
|
||||
$db->execute(
|
||||
"UPDATE {$db->table('users')} SET password = ? WHERE id = ?",
|
||||
[passwordHash($input['new_password']), $user['id']]
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
namespace App\Services;
|
||||
|
||||
/**
|
||||
* Cloudflare Turnstile 人机验证
|
||||
*/
|
||||
class TurnstileService
|
||||
{
|
||||
/**
|
||||
* 校验 Turnstile token
|
||||
* 未配置 secret 时跳过校验(便于本地开发)
|
||||
*/
|
||||
public static function verify(?string $token, ?string $remoteIp = null): bool
|
||||
{
|
||||
$secret = (string) config('app.turnstile.secret_key', '');
|
||||
if ($secret === '') {
|
||||
return true;
|
||||
}
|
||||
if ($token === null || $token === '') {
|
||||
return false;
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'secret' => $secret,
|
||||
'response' => $token,
|
||||
];
|
||||
if ($remoteIp) {
|
||||
$payload['remoteip'] = $remoteIp;
|
||||
}
|
||||
|
||||
$ch = curl_init('https://challenges.cloudflare.com/turnstile/v0/siteverify');
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => http_build_query($payload),
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
|
||||
]);
|
||||
$body = curl_exec($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($body === false) {
|
||||
return false;
|
||||
}
|
||||
$json = json_decode($body, true);
|
||||
return !empty($json['success']);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ return [
|
||||
'debug' => env('APP_DEBUG', false),
|
||||
'timezone' => 'Asia/Shanghai',
|
||||
'jwt_secret' => env('JWT_SECRET', ''),
|
||||
'jwt_ttl' => 7200, // Token有效期(秒)
|
||||
'jwt_ttl' => 86400, // Token有效期(秒)= 24小时
|
||||
'jwt_refresh_ttl' => 1209600, // 刷新Token有效期(秒)
|
||||
'rate_limit' => [
|
||||
'api' => 60, // 普通API每分钟请求数
|
||||
@@ -28,4 +28,8 @@ return [
|
||||
'return_url' => env('APP_URL', '') . '/#/result',
|
||||
],
|
||||
'allowed_origins' => ['*'],
|
||||
'turnstile' => [
|
||||
'site_key' => env('TURNSTILE_SITE_KEY', ''),
|
||||
'secret_key' => env('TURNSTILE_SECRET_KEY', ''),
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,85 @@
|
||||
<template>
|
||||
<div class="turnstile-wrap">
|
||||
<div ref="el" class="cf-turnstile" :data-sitekey="siteKey" data-size="flexible"></div>
|
||||
<div v-if="!siteKey" class="turnstile-off">未配置 Turnstile(开发模式跳过验证)</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, onBeforeUnmount } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
siteKey: { type: String, default: '' }
|
||||
})
|
||||
const emit = defineEmits(['update:token', 'expired', 'error'])
|
||||
|
||||
const el = ref(null)
|
||||
let widgetId = null
|
||||
|
||||
function loadScript() {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (window.turnstile) return resolve()
|
||||
const s = document.createElement('script')
|
||||
s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
|
||||
s.async = true
|
||||
s.onload = resolve
|
||||
s.onerror = () => reject(new Error('Turnstile 加载失败'))
|
||||
document.head.appendChild(s)
|
||||
})
|
||||
}
|
||||
|
||||
function renderWidget() {
|
||||
if (!props.siteKey || !window.turnstile || !el.value) return
|
||||
widgetId = window.turnstile.render(el.value, {
|
||||
sitekey: props.siteKey,
|
||||
size: 'flexible',
|
||||
callback(token) {
|
||||
emit('update:token', token)
|
||||
},
|
||||
'expired-callback'() {
|
||||
emit('update:token', '')
|
||||
emit('expired')
|
||||
},
|
||||
'error-callback'() {
|
||||
emit('update:token', '')
|
||||
emit('error')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
if (!props.siteKey) return
|
||||
try {
|
||||
await loadScript()
|
||||
renderWidget()
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (widgetId != null && window.turnstile) {
|
||||
try { window.turnstile.remove(widgetId) } catch {}
|
||||
}
|
||||
})
|
||||
|
||||
function reset() {
|
||||
if (widgetId != null && window.turnstile) {
|
||||
try { window.turnstile.reset(widgetId) } catch {}
|
||||
}
|
||||
emit('update:token', '')
|
||||
}
|
||||
|
||||
function getResponse() {
|
||||
if (widgetId == null || !window.turnstile) return ''
|
||||
try { return window.turnstile.getResponse(widgetId) || '' } catch { return '' }
|
||||
}
|
||||
|
||||
defineExpose({ reset, getResponse })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.turnstile-wrap { width: 100%; display: flex; justify-content: center; }
|
||||
.turnstile-off { font-size: 12px; color: #c0c4cc; }
|
||||
.cf-turnstile { min-height: 65px; width: 100%; display: flex; justify-content: center; }
|
||||
</style>
|
||||
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* Cloudflare Turnstile 站点密钥(公开,前端使用)
|
||||
* 服务端密钥在 backend/.env TURNSTILE_SECRET_KEY
|
||||
*/
|
||||
export const TURNSTILE_SITE_KEY = '0x4AAAAAAFTnj3DlAd5JS-An'
|
||||
@@ -11,10 +11,13 @@ export const useUserStore = defineStore('user', () => {
|
||||
* @param {string} account 用户名或邮箱
|
||||
* @param {string} password 密码
|
||||
* @param {'admin'|'agent'} portal 登录入口
|
||||
* @param {string} turnstileToken Turnstile 人机验证 token
|
||||
*/
|
||||
async function login(account, password, portal = 'admin') {
|
||||
async function login(account, password, portal = 'admin', turnstileToken = '') {
|
||||
const endpoint = portal === 'agent' ? '/auth/agent-login' : '/auth/admin-login'
|
||||
const res = await request.post(endpoint, { username: account, password })
|
||||
const body = { username: account, password }
|
||||
if (turnstileToken) body.turnstile_token = turnstileToken
|
||||
const res = await request.post(endpoint, body)
|
||||
user.value = res.data.user
|
||||
token.value = res.data.token.access_token
|
||||
localStorage.setItem('access_token', res.data.token.access_token)
|
||||
|
||||
@@ -30,6 +30,9 @@
|
||||
@keyup.enter="handleLogin"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<TurnstileWidget ref="turnstileRef" :site-key="TURNSTILE_SITE_KEY" @update:token="onToken" />
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="loading" style="width:100%" size="large" @click="handleLogin">
|
||||
登 录
|
||||
@@ -45,28 +48,42 @@ import { ref, reactive } 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'
|
||||
|
||||
const router = useRouter()
|
||||
const userStore = useUserStore()
|
||||
const loading = ref(false)
|
||||
const formRef = ref(null)
|
||||
const turnstileRef = ref(null)
|
||||
const turnstileToken = ref('')
|
||||
const form = reactive({ username: '', password: '' })
|
||||
const rules = {
|
||||
username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
|
||||
password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
|
||||
}
|
||||
|
||||
function onToken(t) {
|
||||
turnstileToken.value = t || ''
|
||||
}
|
||||
|
||||
async function handleLogin() {
|
||||
if (!formRef.value) return
|
||||
await formRef.value.validate(async (valid) => {
|
||||
if (!valid) return
|
||||
if (TURNSTILE_SITE_KEY && !turnstileToken.value) {
|
||||
ElMessage.warning('请先完成人机验证')
|
||||
turnstileRef.value?.reset?.()
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
try {
|
||||
await userStore.login(form.username, form.password, 'admin')
|
||||
await userStore.login(form.username, form.password, 'admin', turnstileToken.value)
|
||||
ElMessage.success('登录成功')
|
||||
router.push('/dashboard')
|
||||
} catch (e) {
|
||||
// error handled by interceptor
|
||||
turnstileRef.value?.reset?.()
|
||||
turnstileToken.value = ''
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
|
||||
@@ -43,6 +43,10 @@
|
||||
<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>
|
||||
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="loading" style="width:100%" size="large" @click="handleLogin">
|
||||
登 录
|
||||
@@ -64,11 +68,19 @@ import { useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
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'
|
||||
|
||||
const router = useRouter()
|
||||
const userStore = useUserStore()
|
||||
const loading = ref(false)
|
||||
const formRef = ref(null)
|
||||
const turnstileRef = ref(null)
|
||||
const turnstileToken = ref('')
|
||||
|
||||
function onToken(t) {
|
||||
turnstileToken.value = t || ''
|
||||
}
|
||||
|
||||
const form = reactive({
|
||||
account: '',
|
||||
@@ -93,9 +105,14 @@ async function handleLogin() {
|
||||
if (!formRef.value) return
|
||||
await formRef.value.validate(async (valid) => {
|
||||
if (!valid) return
|
||||
if (TURNSTILE_SITE_KEY && !turnstileToken.value) {
|
||||
ElMessage.warning('请先完成人机验证')
|
||||
turnstileRef.value?.reset?.()
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
try {
|
||||
await userStore.login(form.account, form.password, 'agent')
|
||||
await userStore.login(form.account, form.password, 'agent', turnstileToken.value)
|
||||
if (form.remember) {
|
||||
localStorage.setItem('agent_remember_account', form.account)
|
||||
} else {
|
||||
@@ -104,7 +121,8 @@ async function handleLogin() {
|
||||
ElMessage.success('登录成功')
|
||||
router.push('/dashboard')
|
||||
} catch (e) {
|
||||
// error handled by interceptor
|
||||
turnstileRef.value?.reset?.()
|
||||
turnstileToken.value = ''
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
|
||||
@@ -73,6 +73,10 @@
|
||||
</el-checkbox>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item>
|
||||
<TurnstileWidget ref="turnstileRef" :site-key="TURNSTILE_SITE_KEY" @update:token="onToken" />
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="loading" style="width:100%" size="large" @click="handleRegister">
|
||||
注 册
|
||||
@@ -94,10 +98,18 @@ import { useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { User, Lock, Message, Phone, Ticket } from '@element-plus/icons-vue'
|
||||
import request from '@/api'
|
||||
import TurnstileWidget from '@/components/TurnstileWidget.vue'
|
||||
import { TURNSTILE_SITE_KEY } from '@/config/turnstile'
|
||||
|
||||
const router = useRouter()
|
||||
const loading = ref(false)
|
||||
const formRef = ref(null)
|
||||
const turnstileRef = ref(null)
|
||||
const turnstileToken = ref('')
|
||||
|
||||
function onToken(t) {
|
||||
turnstileToken.value = t || ''
|
||||
}
|
||||
|
||||
const form = reactive({
|
||||
username: '',
|
||||
@@ -185,6 +197,11 @@ async function handleRegister() {
|
||||
if (!formRef.value) return
|
||||
await formRef.value.validate(async (valid) => {
|
||||
if (!valid) return
|
||||
if (TURNSTILE_SITE_KEY && !turnstileToken.value) {
|
||||
ElMessage.warning('请先完成人机验证')
|
||||
turnstileRef.value?.reset?.()
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
try {
|
||||
await request.post('/auth/agent-register', {
|
||||
@@ -194,11 +211,13 @@ async function handleRegister() {
|
||||
email: form.email,
|
||||
phone: form.phone,
|
||||
invite_code: form.inviteCode,
|
||||
turnstile_token: turnstileToken.value,
|
||||
})
|
||||
ElMessage.success('注册成功,请登录')
|
||||
router.push('/agent/login')
|
||||
} catch (e) {
|
||||
// error handled by interceptor
|
||||
turnstileRef.value?.reset?.()
|
||||
turnstileToken.value = ''
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user