【发布时间】: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