实现登录注册的验证码功能(支持reCAPTCHA,hCaptcha,Turnstile)

由于一些原因,不考虑添加国内的验证码服务提供商
This commit is contained in:
Chenx221 2024-02-27 15:41:25 +08:00
parent ae7e3ae7a9
commit 8fcbd3990e
Signed by: chenx221
GPG Key ID: D7A9EC07024C3021
3 changed files with 160 additions and 17 deletions

View File

@ -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.');
}
}

View File

@ -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]);
} ?>
<div class="user-login">
<h1><?= Html::encode($this->title) ?></h1>
@ -17,18 +24,29 @@ $this->params['breadcrumbs'][] = $this->title;
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin();?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'username')->label('用户名')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'password')->passwordInput()->label('密码') ?>
<?= $form->field($model, 'rememberMe')->checkbox()->label('记住本次登录') ?>
<div class="form-group">
<?php if ($verifyProvider === 'reCAPTCHA'): ?>
<div class="g-recaptcha" data-sitekey="<?= Yii::$app->params['reCAPTCHA']['siteKey'] ?>"></div>
<?php elseif ($verifyProvider === 'hCaptcha'): ?>
<div class="h-captcha" data-sitekey="<?= Yii::$app->params['hCaptcha']['siteKey'] ?>"></div>
<?php elseif ($verifyProvider === 'Turnstile'): ?>
<div class="cf-turnstile" data-sitekey="<?= Yii::$app->params['Turnstile']['siteKey'] ?>" data-language="zh-cn"></div>
<?php endif; ?>
</div>
<div class="form-group">
<?= Html::submitButton('登录', ['class' => 'btn btn-primary']) ?>
</div>
<div class="form-group">
<?= Html::a('还没有账户? 点击注册', ['user/register']) ?>
</div>
<div class="form-group">
<?= Html::a('忘记密码?', ['user/forget']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>

View File

@ -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]);
}
?>
<div class="user-register">
<h1><?= Html::encode($this->title) ?></h1>
@ -23,7 +31,15 @@ $this->params['breadcrumbs'][] = $this->title;
<?= $form->field($model, 'password')->passwordInput()->label('密码') ?>
<?= $form->field($model, 'password2')->passwordInput()->label('重复密码') ?>
<?= $form->field($model, 'email')->label('电子邮箱') ?>
<div class="form-group">
<?php if ($verifyProvider === 'reCAPTCHA'): ?>
<div class="g-recaptcha" data-sitekey="<?= Yii::$app->params['reCAPTCHA']['siteKey'] ?>"></div>
<?php elseif ($verifyProvider === 'hCaptcha'): ?>
<div class="h-captcha" data-sitekey="<?= Yii::$app->params['hCaptcha']['siteKey'] ?>"></div>
<?php elseif ($verifyProvider === 'Turnstile'): ?>
<div class="cf-turnstile" data-sitekey="<?= Yii::$app->params['Turnstile']['siteKey'] ?>" data-language="zh-cn"></div>
<?php endif; ?>
</div>
<div class="form-group">
<?= Html::submitButton('注册', ['class' => 'btn btn-primary']) ?>
</div>