【问题标题】:How to add captcha required only for a particular condition yii2如何添加仅针对特定条件yii2所需的验证码
【发布时间】:2018-05-22 14:13:30
【问题描述】:

我正在尝试仅当登录尝试失败次数超过 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() 验证验证码时获取失败尝试的计数,但它不起作用。

谁能告诉我哪里出错了。

提前致谢。

【问题讨论】:

  • when 条件下使用$model->checkattempts(); 代替$this->checkattempts(); 有什么改变吗?
  • 检查你的checkattempts(),你return false$data["attempts"] >=3,这意味着验证码没有应用。

标签: yii yii2 yii2-advanced-app yii2-basic-app yii2-validation


【解决方案1】:

在您的模型中:

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

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

['captcha', 'captcha'],

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

更多documentation about the captcha 和关于scenarios

【讨论】:

  • 这就是我添加的内容,我已将验证码添加到 verifyCode 字段,并且仅当登录尝试超过 3 次时才尝试强制设置,这是我从数据库中获取的。在这里,我使用了检查尝试来获取计数。但要求不起作用。每次提交表单时,即使尝试次数超过 3
  • @rjirji 看看场景链接。您应该创建一个需要验证码的场景,以及不需要验证码的场景。然后,当您创建模型时,根据您的 checkattempts() 方法使用需要验证码的场景。
  • 我喜欢使用场景来处理问题的想法,+1
  • 你能帮我举个例子吗
猜你喜欢
  • 2016-03-22
  • 1970-01-01
  • 2019-08-26
  • 1970-01-01
  • 2020-06-15
  • 1970-01-01
  • 2019-05-23
  • 2020-03-29
  • 1970-01-01
相关资源
最近更新 更多