eat: add reCAPTCHA v3 and Cloudflare Turnstile verification support

- Implement reCAPTCHA v3 with score-based validation
- Add Cloudflare Turnstile as captcha alternative
- Create reusable CaptchaService for unified validation
- Support switching between recaptcha, recaptcha-v3, and turnstile
- Maintain backward compatibility with existing configurations
This commit is contained in:
xboard
2025-06-28 18:01:59 +08:00
parent f1d1dd5684
commit 6d85736eea
18 changed files with 1097 additions and 836 deletions
@@ -18,11 +18,17 @@ class CommController extends Controller
'email_whitelist_suffix' => (int) admin_setting('email_whitelist_enable', 0) 'email_whitelist_suffix' => (int) admin_setting('email_whitelist_enable', 0)
? Helper::getEmailSuffix() ? Helper::getEmailSuffix()
: 0, : 0,
'is_recaptcha' => (int) admin_setting('recaptcha_enable', 0) ? 1 : 0, 'is_captcha' => (int) admin_setting('captcha_enable', 0) ? 1 : 0,
'captcha_type' => admin_setting('captcha_type', 'recaptcha'),
'recaptcha_site_key' => admin_setting('recaptcha_site_key'), 'recaptcha_site_key' => admin_setting('recaptcha_site_key'),
'recaptcha_v3_site_key' => admin_setting('recaptcha_v3_site_key'),
'recaptcha_v3_score_threshold' => admin_setting('recaptcha_v3_score_threshold', 0.5),
'turnstile_site_key' => admin_setting('turnstile_site_key'),
'app_description' => admin_setting('app_description'), 'app_description' => admin_setting('app_description'),
'app_url' => admin_setting('app_url'), 'app_url' => admin_setting('app_url'),
'logo' => admin_setting('logo'), 'logo' => admin_setting('logo'),
// 保持向后兼容
'is_recaptcha' => (int) admin_setting('captcha_enable', 0) ? 1 : 0,
]; ];
return $this->success($data); return $this->success($data);
} }
@@ -95,8 +95,8 @@ class AuthController extends Controller
return redirect()->to( return redirect()->to(
admin_setting('app_url') admin_setting('app_url')
? admin_setting('app_url') . $redirect ? admin_setting('app_url') . $redirect
: url($redirect) : url($redirect)
); );
} }
@@ -151,7 +151,7 @@ class AuthController extends Controller
], 401); ], 401);
} }
$url = $this->mailLinkService->getQuickLoginUrl($user, $request->input('redirect')); $url = $this->loginService->generateQuickLoginUrl($user, $request->input('redirect'));
return $this->success($url); return $this->success($url);
} }
@@ -7,23 +7,22 @@ use App\Http\Requests\Passport\CommSendEmailVerify;
use App\Jobs\SendEmailJob; use App\Jobs\SendEmailJob;
use App\Models\InviteCode; use App\Models\InviteCode;
use App\Models\User; use App\Models\User;
use App\Services\CaptchaService;
use App\Utils\CacheKey; use App\Utils\CacheKey;
use App\Utils\Helper; use App\Utils\Helper;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use ReCaptcha\ReCaptcha;
class CommController extends Controller class CommController extends Controller
{ {
public function sendEmailVerify(CommSendEmailVerify $request) public function sendEmailVerify(CommSendEmailVerify $request)
{ {
if ((int) admin_setting('recaptcha_enable', 0)) { // 验证人机验证码
$recaptcha = new ReCaptcha(admin_setting('recaptcha_key')); $captchaService = app(CaptchaService::class);
$recaptchaResp = $recaptcha->verify($request->input('recaptcha_data')); [$captchaValid, $captchaError] = $captchaService->verify($request);
if (!$recaptchaResp->isSuccess()) { if (!$captchaValid) {
return $this->fail([400, __('Invalid code is incorrect')]); return $this->fail($captchaError);
}
} }
$email = $request->input('email'); $email = $request->input('email');
@@ -10,6 +10,7 @@ use App\Models\Order;
use App\Models\Plan; use App\Models\Plan;
use App\Models\Ticket; use App\Models\Ticket;
use App\Models\User; use App\Models\User;
use App\Services\Auth\LoginService;
use App\Services\AuthService; use App\Services\AuthService;
use App\Services\UserService; use App\Services\UserService;
use App\Utils\CacheKey; use App\Utils\CacheKey;
@@ -19,6 +20,14 @@ use Illuminate\Support\Facades\Cache;
class UserController extends Controller class UserController extends Controller
{ {
protected $loginService;
public function __construct(
LoginService $loginService
) {
$this->loginService = $loginService;
}
public function getActiveSession(Request $request) public function getActiveSession(Request $request)
{ {
$user = User::find($request->user()->id); $user = User::find($request->user()->id);
@@ -205,15 +214,7 @@ class UserController extends Controller
return $this->fail([400, __('The user does not exist')]); return $this->fail([400, __('The user does not exist')]);
} }
$code = Helper::guid(); $url = $this->loginService->generateQuickLoginUrl($user, $request->input('redirect'));
$key = CacheKey::get('TEMP_TOKEN', $code);
Cache::put($key, $user->id, 60);
$redirect = '/#/login?verify=' . $code . '&redirect=' . ($request->input('redirect') ? $request->input('redirect') : 'dashboard');
if (admin_setting('app_url')) {
$url = admin_setting('app_url') . $redirect;
} else {
$url = url($redirect);
}
return $this->success($url); return $this->success($url);
} }
} }
@@ -190,15 +190,23 @@ class ConfigController extends Controller
'email_whitelist_enable' => (bool) admin_setting('email_whitelist_enable', 0), 'email_whitelist_enable' => (bool) admin_setting('email_whitelist_enable', 0),
'email_whitelist_suffix' => admin_setting('email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT), 'email_whitelist_suffix' => admin_setting('email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT),
'email_gmail_limit_enable' => (bool) admin_setting('email_gmail_limit_enable', 0), 'email_gmail_limit_enable' => (bool) admin_setting('email_gmail_limit_enable', 0),
'recaptcha_enable' => (bool) admin_setting('recaptcha_enable', 0), 'captcha_enable' => (bool) admin_setting('captcha_enable', 0),
'captcha_type' => admin_setting('captcha_type', 'recaptcha'),
'recaptcha_key' => admin_setting('recaptcha_key', ''), 'recaptcha_key' => admin_setting('recaptcha_key', ''),
'recaptcha_site_key' => admin_setting('recaptcha_site_key', ''), 'recaptcha_site_key' => admin_setting('recaptcha_site_key', ''),
'recaptcha_v3_secret_key' => admin_setting('recaptcha_v3_secret_key', ''),
'recaptcha_v3_site_key' => admin_setting('recaptcha_v3_site_key', ''),
'recaptcha_v3_score_threshold' => admin_setting('recaptcha_v3_score_threshold', 0.5),
'turnstile_secret_key' => admin_setting('turnstile_secret_key', ''),
'turnstile_site_key' => admin_setting('turnstile_site_key', ''),
'register_limit_by_ip_enable' => (bool) admin_setting('register_limit_by_ip_enable', 0), 'register_limit_by_ip_enable' => (bool) admin_setting('register_limit_by_ip_enable', 0),
'register_limit_count' => admin_setting('register_limit_count', 3), 'register_limit_count' => admin_setting('register_limit_count', 3),
'register_limit_expire' => admin_setting('register_limit_expire', 60), 'register_limit_expire' => admin_setting('register_limit_expire', 60),
'password_limit_enable' => (bool) admin_setting('password_limit_enable', 1), 'password_limit_enable' => (bool) admin_setting('password_limit_enable', 1),
'password_limit_count' => admin_setting('password_limit_count', 5), 'password_limit_count' => admin_setting('password_limit_count', 5),
'password_limit_expire' => admin_setting('password_limit_expire', 60) 'password_limit_expire' => admin_setting('password_limit_expire', 60),
// 保持向后兼容
'recaptcha_enable' => (bool) admin_setting('captcha_enable', 0)
], ],
'subscribe_template' => [ 'subscribe_template' => [
'subscribe_template_singbox' => $this->formatTemplateContent( 'subscribe_template_singbox' => $this->formatTemplateContent(
@@ -240,22 +248,22 @@ class ConfigController extends Controller
{ {
return match ($format) { return match ($format) {
'json' => match (true) { 'json' => match (true) {
is_array($content) => json_encode( is_array($content) => json_encode(
value: $content, value: $content,
flags: JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
),
is_string($content) && str($content)->isJson() => rescue(
callback: fn() => json_encode(
value: json_decode($content, associative: true, flags: JSON_THROW_ON_ERROR),
flags: JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES flags: JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
), ),
rescue: $content,
report: false
),
default => str($content)->toString() is_string($content) && str($content)->isJson() => rescue(
}, callback: fn() => json_encode(
value: json_decode($content, associative: true, flags: JSON_THROW_ON_ERROR),
flags: JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
),
rescue: $content,
report: false
),
default => str($content)->toString()
},
default => str($content)->toString() default => str($content)->toString()
}; };
+12 -1
View File
@@ -82,9 +82,16 @@ class ConfigSave extends FormRequest
'email_whitelist_enable' => 'boolean', 'email_whitelist_enable' => 'boolean',
'email_whitelist_suffix' => 'nullable|array', 'email_whitelist_suffix' => 'nullable|array',
'email_gmail_limit_enable' => 'boolean', 'email_gmail_limit_enable' => 'boolean',
'captcha_enable' => 'boolean',
'captcha_type' => 'in:recaptcha,turnstile,recaptcha-v3',
'recaptcha_enable' => 'boolean', 'recaptcha_enable' => 'boolean',
'recaptcha_key' => '', 'recaptcha_key' => '',
'recaptcha_site_key' => '', 'recaptcha_site_key' => '',
'recaptcha_v3_secret_key' => '',
'recaptcha_v3_site_key' => '',
'recaptcha_v3_score_threshold' => 'numeric|min:0|max:1',
'turnstile_secret_key' => '',
'turnstile_site_key' => '',
'email_verify' => 'bool', 'email_verify' => 'bool',
'safe_mode_enable' => 'boolean', 'safe_mode_enable' => 'boolean',
'register_limit_by_ip_enable' => 'boolean', 'register_limit_by_ip_enable' => 'boolean',
@@ -124,7 +131,11 @@ class ConfigSave extends FormRequest
'telegram_discuss_link.url' => 'Telegram群组地址必须为URL格式,必须携带http(s)://', 'telegram_discuss_link.url' => 'Telegram群组地址必须为URL格式,必须携带http(s)://',
'logo.url' => 'LOGO URL格式不正确,必须携带https(s)://', 'logo.url' => 'LOGO URL格式不正确,必须携带https(s)://',
'secure_path.min' => '后台路径长度最小为8位', 'secure_path.min' => '后台路径长度最小为8位',
'secure_path.regex' => '后台路径只能为字母或数字' 'secure_path.regex' => '后台路径只能为字母或数字',
'captcha_type.in' => '人机验证类型只能选择 recaptcha、turnstile 或 recaptcha-v3',
'recaptcha_v3_score_threshold.numeric' => 'reCAPTCHA v3 分数阈值必须为数字',
'recaptcha_v3_score_threshold.min' => 'reCAPTCHA v3 分数阈值不能小于0',
'recaptcha_v3_score_threshold.max' => 'reCAPTCHA v3 分数阈值不能大于1'
]; ];
} }
} }
+55 -17
View File
@@ -19,12 +19,18 @@ class LoginService
public function login(string $email, string $password): array public function login(string $email, string $password): array
{ {
// 检查密码错误限制 // 检查密码错误限制
if ((int)admin_setting('password_limit_enable', true)) { if ((int) admin_setting('password_limit_enable', true)) {
$passwordErrorCount = (int)Cache::get(CacheKey::get('PASSWORD_ERROR_LIMIT', $email), 0); $passwordErrorCount = (int) Cache::get(CacheKey::get('PASSWORD_ERROR_LIMIT', $email), 0);
if ($passwordErrorCount >= (int)admin_setting('password_limit_count', 5)) { if ($passwordErrorCount >= (int) admin_setting('password_limit_count', 5)) {
return [false, [429, __('There are too many password errors, please try again after :minute minutes.', [ return [
'minute' => admin_setting('password_limit_expire', 60) false,
])]]; [
429,
__('There are too many password errors, please try again after :minute minutes.', [
'minute' => admin_setting('password_limit_expire', 60)
])
]
];
} }
} }
@@ -35,19 +41,21 @@ class LoginService
} }
// 验证密码 // 验证密码
if (!Helper::multiPasswordVerify( if (
$user->password_algo, !Helper::multiPasswordVerify(
$user->password_salt, $user->password_algo,
$password, $user->password_salt,
$user->password) $password,
$user->password
)
) { ) {
// 增加密码错误计数 // 增加密码错误计数
if ((int)admin_setting('password_limit_enable', true)) { if ((int) admin_setting('password_limit_enable', true)) {
$passwordErrorCount = (int)Cache::get(CacheKey::get('PASSWORD_ERROR_LIMIT', $email), 0); $passwordErrorCount = (int) Cache::get(CacheKey::get('PASSWORD_ERROR_LIMIT', $email), 0);
Cache::put( Cache::put(
CacheKey::get('PASSWORD_ERROR_LIMIT', $email), CacheKey::get('PASSWORD_ERROR_LIMIT', $email),
(int)$passwordErrorCount + 1, (int) $passwordErrorCount + 1,
60 * (int)admin_setting('password_limit_expire', 60) 60 * (int) admin_setting('password_limit_expire', 60)
); );
} }
return [false, [400, __('Incorrect email or password')]]; return [false, [400, __('Incorrect email or password')]];
@@ -77,13 +85,13 @@ class LoginService
{ {
// 检查重置请求限制 // 检查重置请求限制
$forgetRequestLimitKey = CacheKey::get('FORGET_REQUEST_LIMIT', $email); $forgetRequestLimitKey = CacheKey::get('FORGET_REQUEST_LIMIT', $email);
$forgetRequestLimit = (int)Cache::get($forgetRequestLimitKey); $forgetRequestLimit = (int) Cache::get($forgetRequestLimitKey);
if ($forgetRequestLimit >= 3) { if ($forgetRequestLimit >= 3) {
return [false, [429, __('Reset failed, Please try again later')]]; return [false, [429, __('Reset failed, Please try again later')]];
} }
// 验证邮箱验证码 // 验证邮箱验证码
if ((string)Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $email)) !== (string)$emailCode) { if ((string) Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $email)) !== (string) $emailCode) {
Cache::put($forgetRequestLimitKey, $forgetRequestLimit ? $forgetRequestLimit + 1 : 1, 300); Cache::put($forgetRequestLimitKey, $forgetRequestLimit ? $forgetRequestLimit + 1 : 1, 300);
return [false, [400, __('Incorrect email verification code')]]; return [false, [400, __('Incorrect email verification code')]];
} }
@@ -108,4 +116,34 @@ class LoginService
return [true, true]; return [true, true];
} }
/**
* 生成临时登录令牌和快速登录URL
*
* @param User $user 用户对象
* @param string $redirect 重定向路径
* @return string|null 快速登录URL
*/
public function generateQuickLoginUrl(User $user, string $redirect = 'dashboard'): ?string
{
if (!$user || !$user->exists) {
return null;
}
$code = Helper::guid();
$key = CacheKey::get('TEMP_TOKEN', $code);
Cache::put($key, $user->id, 60);
$loginRedirect = '/#/login?verify=' . $code . '&redirect=' . $redirect;
if (admin_setting('app_url')) {
$url = admin_setting('app_url') . $loginRedirect;
} else {
$url = url($loginRedirect);
}
return $url;
}
} }
+1 -23
View File
@@ -19,7 +19,7 @@ class MailLinkService
*/ */
public function handleMailLink(string $email, ?string $redirect = null): array public function handleMailLink(string $email, ?string $redirect = null): array
{ {
if (!(int)admin_setting('login_with_mail_link_enable')) { if (!(int) admin_setting('login_with_mail_link_enable')) {
return [false, [404, null]]; return [false, [404, null]];
} }
@@ -72,28 +72,6 @@ class MailLinkService
]); ]);
} }
/**
* 获取快速登录URL
*
* @param User $user 用户对象
* @param string|null $redirect 重定向地址
* @return string 登录URL
*/
public function getQuickLoginUrl(User $user, ?string $redirect = null): string
{
$code = Helper::guid();
$key = CacheKey::get('TEMP_TOKEN', $code);
Cache::put($key, $user->id, 60);
$redirectUrl = '/#/login?verify=' . $code . '&redirect=' . ($redirect ? $redirect : 'dashboard');
if (admin_setting('app_url')) {
return admin_setting('app_url') . $redirectUrl;
} else {
return url($redirectUrl);
}
}
/** /**
* 处理Token登录 * 处理Token登录
* *
+34 -28
View File
@@ -5,12 +5,12 @@ namespace App\Services\Auth;
use App\Models\InviteCode; use App\Models\InviteCode;
use App\Models\Plan; use App\Models\Plan;
use App\Models\User; use App\Models\User;
use App\Services\CaptchaService;
use App\Utils\CacheKey; use App\Utils\CacheKey;
use App\Utils\Dict; use App\Utils\Dict;
use App\Utils\Helper; use App\Utils\Helper;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use ReCaptcha\ReCaptcha;
class RegisterService class RegisterService
{ {
@@ -23,36 +23,42 @@ class RegisterService
public function validateRegister(Request $request): array public function validateRegister(Request $request): array
{ {
// 检查IP注册限制 // 检查IP注册限制
if ((int)admin_setting('register_limit_by_ip_enable', 0)) { if ((int) admin_setting('register_limit_by_ip_enable', 0)) {
$registerCountByIP = Cache::get(CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip())) ?? 0; $registerCountByIP = Cache::get(CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip())) ?? 0;
if ((int)$registerCountByIP >= (int)admin_setting('register_limit_count', 3)) { if ((int) $registerCountByIP >= (int) admin_setting('register_limit_count', 3)) {
return [false, [429, __('Register frequently, please try again after :minute minute', [ return [
'minute' => admin_setting('register_limit_expire', 60) false,
])]]; [
429,
__('Register frequently, please try again after :minute minute', [
'minute' => admin_setting('register_limit_expire', 60)
])
]
];
} }
} }
// 检查验证码 // 检查验证码
if ((int)admin_setting('recaptcha_enable', 0)) { $captchaService = app(CaptchaService::class);
$recaptcha = new ReCaptcha(admin_setting('recaptcha_key')); [$captchaValid, $captchaError] = $captchaService->verify($request);
$recaptchaResp = $recaptcha->verify($request->input('recaptcha_data')); if (!$captchaValid) {
if (!$recaptchaResp->isSuccess()) { return [false, $captchaError];
return [false, [400, __('Invalid code is incorrect')]];
}
} }
// 检查邮箱白名单 // 检查邮箱白名单
if ((int)admin_setting('email_whitelist_enable', 0)) { if ((int) admin_setting('email_whitelist_enable', 0)) {
if (!Helper::emailSuffixVerify( if (
$request->input('email'), !Helper::emailSuffixVerify(
admin_setting('email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT)) $request->input('email'),
admin_setting('email_whitelist_suffix', Dict::EMAIL_WHITELIST_SUFFIX_DEFAULT)
)
) { ) {
return [false, [400, __('Email suffix is not in the Whitelist')]]; return [false, [400, __('Email suffix is not in the Whitelist')]];
} }
} }
// 检查Gmail限制 // 检查Gmail限制
if ((int)admin_setting('email_gmail_limit_enable', 0)) { if ((int) admin_setting('email_gmail_limit_enable', 0)) {
$prefix = explode('@', $request->input('email'))[0]; $prefix = explode('@', $request->input('email'))[0];
if (strpos($prefix, '.') !== false || strpos($prefix, '+') !== false) { if (strpos($prefix, '.') !== false || strpos($prefix, '+') !== false) {
return [false, [400, __('Gmail alias is not supported')]]; return [false, [400, __('Gmail alias is not supported')]];
@@ -60,23 +66,23 @@ class RegisterService
} }
// 检查是否关闭注册 // 检查是否关闭注册
if ((int)admin_setting('stop_register', 0)) { if ((int) admin_setting('stop_register', 0)) {
return [false, [400, __('Registration has closed')]]; return [false, [400, __('Registration has closed')]];
} }
// 检查邀请码要求 // 检查邀请码要求
if ((int)admin_setting('invite_force', 0)) { if ((int) admin_setting('invite_force', 0)) {
if (empty($request->input('invite_code'))) { if (empty($request->input('invite_code'))) {
return [false, [422, __('You must use the invitation code to register')]]; return [false, [422, __('You must use the invitation code to register')]];
} }
} }
// 检查邮箱验证 // 检查邮箱验证
if ((int)admin_setting('email_verify', 0)) { if ((int) admin_setting('email_verify', 0)) {
if (empty($request->input('email_code'))) { if (empty($request->input('email_code'))) {
return [false, [422, __('Email verification code cannot be empty')]]; return [false, [422, __('Email verification code cannot be empty')]];
} }
if ((string)Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))) !== (string)$request->input('email_code')) { if ((string) Cache::get(CacheKey::get('EMAIL_VERIFY_CODE', $request->input('email'))) !== (string) $request->input('email_code')) {
return [false, [400, __('Incorrect email verification code')]]; return [false, [400, __('Incorrect email verification code')]];
} }
} }
@@ -109,7 +115,7 @@ class RegisterService
->first(); ->first();
if (!$inviteCodeModel) { if (!$inviteCodeModel) {
if ((int)admin_setting('invite_force', 0)) { if ((int) admin_setting('invite_force', 0)) {
return [false, [400, __('Invalid invitation code')]]; return [false, [400, __('Invalid invitation code')]];
} }
return [true, null]; return [true, null];
@@ -117,7 +123,7 @@ class RegisterService
$user->invite_user_id = $inviteCodeModel->user_id ? $inviteCodeModel->user_id : null; $user->invite_user_id = $inviteCodeModel->user_id ? $inviteCodeModel->user_id : null;
if (!(int)admin_setting('invite_never_expire', 0)) { if (!(int) admin_setting('invite_never_expire', 0)) {
$inviteCodeModel->status = true; $inviteCodeModel->status = true;
$inviteCodeModel->save(); $inviteCodeModel->save();
} }
@@ -133,7 +139,7 @@ class RegisterService
*/ */
public function handleTryOut(User $user): void public function handleTryOut(User $user): void
{ {
if ((int)admin_setting('try_out_plan_id', 0)) { if ((int) admin_setting('try_out_plan_id', 0)) {
$plan = Plan::find(admin_setting('try_out_plan_id')); $plan = Plan::find(admin_setting('try_out_plan_id'));
if ($plan) { if ($plan) {
$user->transfer_enable = $plan->transfer_enable * 1073741824; $user->transfer_enable = $plan->transfer_enable * 1073741824;
@@ -186,7 +192,7 @@ class RegisterService
} }
// 清除邮箱验证码 // 清除邮箱验证码
if ((int)admin_setting('email_verify', 0)) { if ((int) admin_setting('email_verify', 0)) {
Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $email)); Cache::forget(CacheKey::get('EMAIL_VERIFY_CODE', $email));
} }
@@ -195,12 +201,12 @@ class RegisterService
$user->save(); $user->save();
// 更新IP注册计数 // 更新IP注册计数
if ((int)admin_setting('register_limit_by_ip_enable', 0)) { if ((int) admin_setting('register_limit_by_ip_enable', 0)) {
$registerCountByIP = Cache::get(CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip())) ?? 0; $registerCountByIP = Cache::get(CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip())) ?? 0;
Cache::put( Cache::put(
CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip()), CacheKey::get('REGISTER_IP_RATE_LIMIT', $request->ip()),
(int)$registerCountByIP + 1, (int) $registerCountByIP + 1,
(int)admin_setting('register_limit_expire', 60) * 60 (int) admin_setting('register_limit_expire', 60) * 60
); );
} }
+112
View File
@@ -0,0 +1,112 @@
<?php
namespace App\Services;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use ReCaptcha\ReCaptcha;
class CaptchaService
{
/**
* 验证人机验证码
*
* @param Request $request 请求对象
* @return array [是否通过, 错误消息]
*/
public function verify(Request $request): array
{
if (!(int) admin_setting('captcha_enable', 0)) {
return [true, null];
}
$captchaType = admin_setting('captcha_type', 'recaptcha');
return match ($captchaType) {
'turnstile' => $this->verifyTurnstile($request),
'recaptcha-v3' => $this->verifyRecaptchaV3($request),
'recaptcha' => $this->verifyRecaptcha($request),
default => [false, [400, __('Invalid captcha type')]]
};
}
/**
* 验证 Cloudflare Turnstile
*
* @param Request $request
* @return array
*/
private function verifyTurnstile(Request $request): array
{
$turnstileToken = $request->input('turnstile_token');
if (!$turnstileToken) {
return [false, [400, __('Invalid code is incorrect')]];
}
$response = Http::post('https://challenges.cloudflare.com/turnstile/v0/siteverify', [
'secret' => admin_setting('turnstile_secret_key'),
'response' => $turnstileToken,
'remoteip' => $request->ip()
]);
$result = $response->json();
if (!$result['success']) {
return [false, [400, __('Invalid code is incorrect')]];
}
return [true, null];
}
/**
* 验证 Google reCAPTCHA v3
*
* @param Request $request
* @return array
*/
private function verifyRecaptchaV3(Request $request): array
{
$recaptchaV3Token = $request->input('recaptcha_v3_token');
if (!$recaptchaV3Token) {
return [false, [400, __('Invalid code is incorrect')]];
}
$recaptcha = new ReCaptcha(admin_setting('recaptcha_v3_secret_key'));
$recaptchaResp = $recaptcha->verify($recaptchaV3Token, $request->ip());
if (!$recaptchaResp->isSuccess()) {
return [false, [400, __('Invalid code is incorrect')]];
}
// 检查分数阈值(如果有的话)
$score = $recaptchaResp->getScore();
$threshold = admin_setting('recaptcha_v3_score_threshold', 0.5);
if ($score !== null && $score < $threshold) {
return [false, [400, __('Invalid code is incorrect')]];
}
return [true, null];
}
/**
* 验证 Google reCAPTCHA v2
*
* @param Request $request
* @return array
*/
private function verifyRecaptcha(Request $request): array
{
$recaptchaData = $request->input('recaptcha_data');
if (!$recaptchaData) {
return [false, [400, __('Invalid code is incorrect')]];
}
$recaptcha = new ReCaptcha(admin_setting('recaptcha_key'));
$recaptchaResp = $recaptcha->verify($recaptchaData);
if (!$recaptchaResp->isSuccess()) {
return [false, [400, __('Invalid code is incorrect')]];
}
return [true, null];
}
}
+14 -14
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -16,7 +16,7 @@
title: 'Xboard', title: 'Xboard',
version: '1.0.0', version: '1.0.0',
logo: 'https://xboard.io/i6mages/logo.png', logo: 'https://xboard.io/i6mages/logo.png',
secure_path: '/6a416b7a', secure_path: '/22aba88a',
} }
</script> </script>
<script src="./locales/en-US.js"></script> <script src="./locales/en-US.js"></script>
+51 -11
View File
@@ -416,20 +416,60 @@ window.XBOARD_TRANSLATIONS['en-US'] = {
"description": "Enter the allowed email suffixes, one per line" "description": "Enter the allowed email suffixes, one per line"
} }
}, },
"recaptcha": { "captcha": {
"enable": { "enable": {
"label": "Enable reCAPTCHA", "label": "Enable Captcha",
"description": "When enabled, users will need to pass reCAPTCHA verification when registering." "description": "When enabled, users will need to pass captcha verification when registering."
}, },
"key": { "type": {
"label": "reCAPTCHA Key", "label": "Captcha Type",
"placeholder": "Enter reCAPTCHA key", "description": "Select the captcha service type to use",
"description": "Enter your reCAPTCHA key" "options": {
"recaptcha": "Google reCAPTCHA v2",
"recaptcha-v3": "Google reCAPTCHA v3",
"turnstile": "Cloudflare Turnstile"
}
}, },
"siteKey": { "recaptcha": {
"label": "reCAPTCHA Site Key", "key": {
"placeholder": "Enter reCAPTCHA site key", "label": "reCAPTCHA Key",
"description": "Enter your reCAPTCHA site key" "placeholder": "Enter reCAPTCHA key",
"description": "Enter your reCAPTCHA key"
},
"siteKey": {
"label": "reCAPTCHA Site Key",
"placeholder": "Enter reCAPTCHA site key",
"description": "Enter your reCAPTCHA site key"
}
},
"recaptcha_v3": {
"secretKey": {
"label": "reCAPTCHA v3 Key",
"placeholder": "Enter reCAPTCHA v3 key",
"description": "Enter your reCAPTCHA v3 server key"
},
"siteKey": {
"label": "reCAPTCHA v3 Site Key",
"placeholder": "Enter reCAPTCHA v3 site key",
"description": "Enter your reCAPTCHA v3 site key"
},
"scoreThreshold": {
"label": "Score Threshold",
"placeholder": "0.5",
"description": "Set verification score threshold (0-1), higher scores indicate more likely human behavior"
}
},
"turnstile": {
"secretKey": {
"label": "Turnstile Key",
"placeholder": "Enter Turnstile key",
"description": "Enter your Cloudflare Turnstile key"
},
"siteKey": {
"label": "Turnstile Site Key",
"placeholder": "Enter Turnstile site key",
"description": "Enter your Cloudflare Turnstile site key"
}
} }
}, },
"registerLimit": { "registerLimit": {
+33 -11
View File
@@ -414,20 +414,42 @@ window.XBOARD_TRANSLATIONS['ko-KR'] = {
"description": "허용된 이메일 접미사를 한 줄에 하나씩 입력하세요" "description": "허용된 이메일 접미사를 한 줄에 하나씩 입력하세요"
} }
}, },
"recaptcha": { "captcha": {
"enable": { "enable": {
"label": "reCAPTCHA 활성화", "label": "캡차 활성화",
"description": "활성화하면 사용자는 등록 시 reCAPTCHA 인증을 통과해야 합니다." "description": "활성화하면 사용자는 등록 시 캡차 인증을 통과해야 합니다."
}, },
"key": { "type": {
"label": "reCAPTCHA 키", "label": "캡차 유형",
"placeholder": "reCAPTCHA 키 입력", "description": "사용할 캡차 서비스 유형을 선택하세요",
"description": "reCAPTCHA 키를 입력하세요" "options": {
"recaptcha": "Google reCAPTCHA v2",
"turnstile": "Cloudflare Turnstile"
}
}, },
"siteKey": { "recaptcha": {
"label": "reCAPTCHA 사이트 키", "key": {
"placeholder": "reCAPTCHA 사이트 키 입력", "label": "reCAPTCHA ",
"description": "reCAPTCHA 사이트 키를 입력하세요" "placeholder": "reCAPTCHA 키 입력",
"description": "reCAPTCHA 키를 입력하세요"
},
"siteKey": {
"label": "reCAPTCHA 사이트 키",
"placeholder": "reCAPTCHA 사이트 키 입력",
"description": "reCAPTCHA 사이트 키를 입력하세요"
}
},
"turnstile": {
"secretKey": {
"label": "Turnstile 키",
"placeholder": "Turnstile 키 입력",
"description": "Cloudflare Turnstile 키를 입력하세요"
},
"siteKey": {
"label": "Turnstile 사이트 키",
"placeholder": "Turnstile 사이트 키 입력",
"description": "Cloudflare Turnstile 사이트 키를 입력하세요"
}
} }
}, },
"registerLimit": { "registerLimit": {
+51 -11
View File
@@ -336,20 +336,60 @@ window.XBOARD_TRANSLATIONS['zh-CN'] = {
"description": "输入允许的邮箱后缀,每行一个" "description": "输入允许的邮箱后缀,每行一个"
} }
}, },
"recaptcha": { "captcha": {
"enable": { "enable": {
"label": "启用reCAPTCHA", "label": "启用验证码",
"description": "开启后用户注册时需要通过reCAPTCHA验证。" "description": "开启后用户注册时需要通过验证码验证。"
}, },
"key": { "type": {
"label": "reCAPTCHA密钥", "label": "验证码类型",
"placeholder": "输入reCAPTCHA密钥", "description": "选择要使用的验证码服务类型",
"description": "输入您的reCAPTCHA密钥" "options": {
"recaptcha": "Google reCAPTCHA v2",
"recaptcha-v3": "Google reCAPTCHA v3",
"turnstile": "Cloudflare Turnstile"
}
}, },
"siteKey": { "recaptcha": {
"label": "reCAPTCHA站点密钥", "key": {
"placeholder": "输入reCAPTCHA站点密钥", "label": "reCAPTCHA密钥",
"description": "输入您的reCAPTCHA站点密钥" "placeholder": "输入reCAPTCHA密钥",
"description": "输入您的reCAPTCHA密钥"
},
"siteKey": {
"label": "reCAPTCHA站点密钥",
"placeholder": "输入reCAPTCHA站点密钥",
"description": "输入您的reCAPTCHA站点密钥"
}
},
"recaptcha_v3": {
"secretKey": {
"label": "reCAPTCHA v3密钥",
"placeholder": "输入reCAPTCHA v3密钥",
"description": "输入您的reCAPTCHA v3服务器密钥"
},
"siteKey": {
"label": "reCAPTCHA v3站点密钥",
"placeholder": "输入reCAPTCHA v3站点密钥",
"description": "输入您的reCAPTCHA v3站点密钥"
},
"scoreThreshold": {
"label": "分数阈值",
"placeholder": "0.5",
"description": "设置验证分数阈值(0-1),分数越高表示越可能是真人操作"
}
},
"turnstile": {
"secretKey": {
"label": "Turnstile密钥",
"placeholder": "输入Turnstile密钥",
"description": "输入您的Cloudflare Turnstile密钥"
},
"siteKey": {
"label": "Turnstile站点密钥",
"placeholder": "输入Turnstile站点密钥",
"description": "输入您的Cloudflare Turnstile站点密钥"
}
} }
}, },
"registerLimit": { "registerLimit": {
+656 -656
View File
File diff suppressed because one or more lines are too long
Binary file not shown.
Binary file not shown.