yii - 如何添加仅针对特定条件yii2所需的验证码
问题描述
我正在尝试仅在登录尝试失败次数超过 3 次时才需要验证码字段。到目前为止,我已经写了下面的代码。
在 LoginForm 模型中,我添加了以下规则
public function rules()
{
return [
[['username', 'password'], 'required'],
['password', 'validatePassword'],
['verifyCode', 'captcha', 'when' => function($model) {
return $this->checkattempts();
}],
];
}
public function validatePassword($attribute, $params)
{
if (!$this->hasErrors()) {
$user = $this->getUser();
if (!$user || !$user->validatePassword($this->password)) {
$this->addLoginAttempt($user->id);
$this->addError($attribute, 'Incorrect username or password.');
}
}
}
public function checkattempts()
{
$user = $this->getUser();
$ip = $this->get_client_ip();
$data = (new Query())->select('*')
->from('login_attempts')
->where(['ip' => $ip])->andWhere(['user_ref_id' => $user->id])
->one();
if($data["attempts"] >=3){
return false;
}else{
return true;
}
}
public function addLoginAttempt($uid) {
$ip = $this->get_client_ip();
$data = (new Query())->select('*')
->from('login_attempts')
->where(['ip' => $ip])->andWhere(['user_ref_id' => $uid])
->one();
if($data)
{
$attempts = $data["attempts"]+1;
@Yii::$app->db->createCommand("UPDATE login_attempts SET attempts=".$attempts." where ip = '$ip' AND user_ref_id=$uid")->execute();
}
else {
Yii::$app->db->createCommand("INSERT into login_attempts (attempts, user_ref_id, ip) VALUES(1,'$uid', '$ip')")->execute();
}
}
在这里,我首先验证密码。如果密码不正确,那么我将计数增加 1。这部分工作正常。计数成功递增。
在此之后,我试图在使用该功能验证验证码时获取失败尝试的计数checkattempts()
,但它不起作用。
谁能告诉我我在哪里犯了错误。
提前致谢。
解决方案
推荐阅读
- jquery - 使用 jquery 在 node.js 服务器中解析 json 会出现 404 错误
- python - Python & Pyqt5:文件存在后创建按钮
- asp.net - 在模板字段中使用本地资源
- c++ - 如何在 qt for windows 中使用 QAxObject 创建 docx 和 doc 文件?
- powerbi - PowerBi 测量的不可理解的结果
- python - url 在表单操作中不匹配(python django)
- python - 时间序列预测:分析
- html - CSS 不等 div 框
- vuetify.js - 添加 vuetify 时,纱线中的 -D 选项是什么
- google-cloud-platform - 如何在 Google BigQuery 中设置用户的查询配额