From 8fcbd3990e9832bb9442f8f7a8c1e17847b96e5c Mon Sep 17 00:00:00 2001 From: Chenx221 Date: Tue, 27 Feb 2024 15:41:25 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E7=99=BB=E5=BD=95=E6=B3=A8?= =?UTF-8?q?=E5=86=8C=E7=9A=84=E9=AA=8C=E8=AF=81=E7=A0=81=E5=8A=9F=E8=83=BD?= =?UTF-8?q?(=E6=94=AF=E6=8C=81reCAPTCHA,hCaptcha,Turnstile)=20=E7=94=B1?= =?UTF-8?q?=E4=BA=8E=E4=B8=80=E4=BA=9B=E5=8E=9F=E5=9B=A0=EF=BC=8C=E4=B8=8D?= =?UTF-8?q?=E8=80=83=E8=99=91=E6=B7=BB=E5=8A=A0=E5=9B=BD=E5=86=85=E7=9A=84?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E7=A0=81=E6=9C=8D=E5=8A=A1=E6=8F=90=E4=BE=9B?= =?UTF-8?q?=E5=95=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controllers/UserController.php | 135 +++++++++++++++++++++++++++++---- views/user/login.php | 24 +++++- views/user/register.php | 18 ++++- 3 files changed, 160 insertions(+), 17 deletions(-) diff --git a/controllers/UserController.php b/controllers/UserController.php index e38cc63..7c07f0a 100644 --- a/controllers/UserController.php +++ b/controllers/UserController.php @@ -4,8 +4,11 @@ namespace app\controllers; use app\models\User; use app\models\UserSearch; +use ReCaptcha\ReCaptcha; use Yii; use yii\base\Exception; +use yii\base\InvalidConfigException; +use yii\httpclient\Client; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; @@ -141,7 +144,7 @@ class UserController extends Controller * * @return string|Response */ - public function actionLogin() + public function actionLogin(): Response|string { if (!Yii::$app->user->isGuest) { return $this->goHome(); @@ -150,10 +153,29 @@ class UserController extends Controller $model = new User(['scenario' => 'login']); if ($model->load(Yii::$app->request->post()) && $model->validate()) { - if ($model->login()) { - return $this->goBack(); + // 根据 verifyProvider 的值选择使用哪种验证码服务 + $verifyProvider = Yii::$app->params['verifyProvider']; + $captchaResponse = null; + $isCaptchaValid = false; + if ($verifyProvider === 'reCAPTCHA') { + $captchaResponse = Yii::$app->request->post('g-recaptcha-response', null); + $isCaptchaValid = $this->validateRecaptcha($captchaResponse); + } elseif ($verifyProvider === 'hCaptcha') { + $captchaResponse = Yii::$app->request->post('h-captcha-response', null); + $isCaptchaValid = $this->validateHcaptcha($captchaResponse); + } elseif ($verifyProvider === 'Turnstile') { + $captchaResponse = Yii::$app->request->post('cf-turnstile-response', null); + $isCaptchaValid = $this->validateTurnstile($captchaResponse); + } + + if ($captchaResponse !== null && $isCaptchaValid) { + if ($model->login()) { + return $this->goBack(); + } else { + Yii::$app->session->setFlash('error', 'Invalid username or password.'); + } } else { - Yii::$app->session->setFlash('error', 'Invalid username or password.'); + Yii::$app->session->setFlash('error', 'Invalid captcha.'); } } return $this->render('login', [ @@ -161,6 +183,74 @@ class UserController extends Controller ]); } + /** + * 验证 reCAPTCHA 的响应 + * 无法保证这项服务在中国大陆的可用性 + * @param $recaptchaResponse + * @return bool + */ + private function validateRecaptcha($recaptchaResponse): bool + { + $recaptcha = new ReCaptcha(Yii::$app->params['reCAPTCHA']['secret']); + $resp = $recaptcha->verify($recaptchaResponse, $_SERVER['REMOTE_ADDR']); + + return $resp->isSuccess(); + } + + /** + * 验证 hCaptcha 的响应 + * @param $hcaptchaResponse + * @return bool + * @throws InvalidConfigException + * @throws \yii\httpclient\Exception + */ + private function validateHcaptcha($hcaptchaResponse): bool + { + $hcaptchaSecret = Yii::$app->params['hCaptcha']['secret']; + $verifyUrl = 'https://api.hcaptcha.com/siteverify'; + + $client = new Client(); + $response = $client->createRequest() + ->setMethod('POST') + ->setUrl($verifyUrl) + ->setData(['secret' => $hcaptchaSecret, 'response' => $hcaptchaResponse]) + ->send(); + + if ($response->isOk) { + $responseData = $response->getData(); + return isset($responseData['success']) && $responseData['success'] === true; + } + + return false; + } + + /** + * 验证 Turnstile 的响应 + * @param $turnstileResponse + * @return bool + * @throws InvalidConfigException + * @throws \yii\httpclient\Exception + */ + private function validateTurnstile($turnstileResponse): bool + { + $turnstileSecret = Yii::$app->params['Turnstile']['secret']; + $verifyUrl = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'; + + $client = new Client(); + $response = $client->createRequest() + ->setMethod('POST') + ->setUrl($verifyUrl) + ->setData(['secret' => $turnstileSecret, 'response' => $turnstileResponse]) + ->send(); + + if ($response->isOk) { + $responseData = $response->getData(); + return isset($responseData['success']) && $responseData['success'] === true; + } + + return false; + } + /** * Logs out the current user. * @return Response @@ -178,19 +268,38 @@ class UserController extends Controller * @return string|Response * @throws Exception */ - public function actionRegister() + public function actionRegister(): Response|string { $model = new User(['scenario' => 'register']); if ($model->load(Yii::$app->request->post()) && $model->validate()) { - $raw_password = $model->password; - $model->password = Yii::$app->security->generatePasswordHash($raw_password); - $model->auth_key = Yii::$app->security->generateRandomString(); - if ($model->save(false)) { // save without validation - Yii::$app->session->setFlash('success', 'Registration successful. You can now log in.'); - return $this->redirect(['login']); + // 根据 verifyProvider 的值选择使用哪种验证码服务 + $verifyProvider = Yii::$app->params['verifyProvider']; + $captchaResponse = null; + $isCaptchaValid = false; + if ($verifyProvider === 'reCAPTCHA') { + $captchaResponse = Yii::$app->request->post('g-recaptcha-response', null); + $isCaptchaValid = $this->validateRecaptcha($captchaResponse); + } elseif ($verifyProvider === 'hCaptcha') { + $captchaResponse = Yii::$app->request->post('h-captcha-response', null); + $isCaptchaValid = $this->validateHcaptcha($captchaResponse); + } elseif ($verifyProvider === 'Turnstile') { + $captchaResponse = Yii::$app->request->post('cf-turnstile-response', null); + $isCaptchaValid = $this->validateTurnstile($captchaResponse); + } + + if ($captchaResponse !== null && $isCaptchaValid) { + $raw_password = $model->password; + $model->password = Yii::$app->security->generatePasswordHash($raw_password); + $model->auth_key = Yii::$app->security->generateRandomString(); + if ($model->save(false)) { // save without validation + Yii::$app->session->setFlash('success', 'Registration successful. You can now log in.'); + return $this->redirect(['login']); + } else { + $model->password = $raw_password; + Yii::$app->session->setFlash('error', 'Failed to register user.'); + } } else { - $model->password = $raw_password; - Yii::$app->session->setFlash('error', 'Failed to register user.'); + Yii::$app->session->setFlash('error', 'Invalid captcha.'); } } diff --git a/views/user/login.php b/views/user/login.php index 2721ac2..79d25e8 100644 --- a/views/user/login.php +++ b/views/user/login.php @@ -9,7 +9,14 @@ use yii\bootstrap5\ActiveForm; $this->title = '用户登录'; $this->params['breadcrumbs'][] = $this->title; -?> +$verifyProvider = Yii::$app->params['verifyProvider']; +if ($verifyProvider === 'reCAPTCHA') { + $this->registerJsFile('https://www.recaptcha.net/recaptcha/api.js?hl=zh-CN', ['async' => true, 'defer' => true]); +} elseif ($verifyProvider === 'hCaptcha') { + $this->registerJsFile('https://js.hcaptcha.com/1/api.js?hl=zh-CN', ['async' => true, 'defer' => true]); +} elseif ($verifyProvider === 'Turnstile') { + $this->registerJsFile('https://challenges.cloudflare.com/turnstile/v0/api.js', ['async' => true, 'defer' => true]); +} ?>

title) ?>

@@ -17,18 +24,29 @@ $this->params['breadcrumbs'][] = $this->title;
- + field($model, 'username')->label('用户名')->textInput(['autofocus' => true]) ?> field($model, 'password')->passwordInput()->label('密码') ?> field($model, 'rememberMe')->checkbox()->label('记住本次登录') ?> - +
+ +
+ +
+ +
+ +
'btn btn-primary']) ?>
+
+ +
diff --git a/views/user/register.php b/views/user/register.php index 008f0cf..5a56f2f 100644 --- a/views/user/register.php +++ b/views/user/register.php @@ -9,6 +9,14 @@ use yii\bootstrap5\ActiveForm; $this->title = '用户注册'; $this->params['breadcrumbs'][] = $this->title; +$verifyProvider = Yii::$app->params['verifyProvider']; +if ($verifyProvider === 'reCAPTCHA') { + $this->registerJsFile('https://www.recaptcha.net/recaptcha/api.js?hl=zh-CN', ['async' => true, 'defer' => true]); +} elseif ($verifyProvider === 'hCaptcha') { + $this->registerJsFile('https://js.hcaptcha.com/1/api.js?hl=zh-CN', ['async' => true, 'defer' => true]); +} elseif ($verifyProvider === 'Turnstile') { + $this->registerJsFile('https://challenges.cloudflare.com/turnstile/v0/api.js', ['async' => true, 'defer' => true]); +} ?>

title) ?>

@@ -23,7 +31,15 @@ $this->params['breadcrumbs'][] = $this->title; field($model, 'password')->passwordInput()->label('密码') ?> field($model, 'password2')->passwordInput()->label('重复密码') ?> field($model, 'email')->label('电子邮箱') ?> - +
+ +
+ +
+ +
+ +
'btn btn-primary']) ?>