首页 > 解决方案 > 如何添加仅针对特定条件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(),但它不起作用。

谁能告诉我我在哪里犯了错误。

提前致谢。

标签: yiiyii2yii2-advanced-appyii2-basic-appyii2-validation

解决方案


在您的模型中:

if (!$model->checkattempts())
//show the captcha

然后,在您的模型规则中,您将需要以下内容:

['captcha', 'captcha'],

在您的情况下,您可以做的是根据用户尝试使用不同的场景,并且在一种场景(超过 X 次尝试)中需要验证码。

更多关于验证码场景的文档。


推荐阅读