【问题标题】:Unwanted validation rule being applied on password reset密码重置时应用了不需要的验证规则
【发布时间】:2019-12-06 18:32:15
【问题描述】:

我正在尝试使用 Laravel 身份验证的密码重置功能。运行 ma​​ke:auth 命令后,在我的 ResetPasswordController 中,我重写了 Illuminate\Foundation\Auth\ResetsPasswords 特征的 rules 函数,如下所示:

protected function rules()
{
    return [
        'token' => 'required',
        'email' => 'required|email',
        'password' => 'required|confirmed|min:4',    
    ];
}

所以,我尝试将最小长度值更改为 4。但是当我尝试重置密码时,仍然应用了最少 8 个字符的规则,而不是 4 个。 这是同一文件中laravel的reset功能:

public function reset(Request $request)
{
    $request->validate($this->rules(), $this->validationErrorMessages());

    // Here we will attempt to reset the user's password. If it is successful we
    // will update the password on an actual user model and persist it to the
    // database. Otherwise we will parse the error and return the response.
    $response = $this->broker()->reset(
        $this->credentials($request), function ($user, $password) {
            $this->resetPassword($user, $password);
        }
    );

    // If the password was successfully reset, we will redirect the user back to
    // the application's home authenticated view. If there is an error we can
    // redirect them back to where they came from with their error message.
    return $response == Password::PASSWORD_RESET
                ? $this->sendResetResponse($request, $response)
                : $this->sendResetFailedResponse($request, $response);
}

返回的 $response 是 Illuminate\Support\Facades\Password::INVALID_PASSWORD。我不明白这个规则是从哪里来的。 实际上验证行为是这样的:当我输入少于 4 个字符时,我自己的规则被应用(正确)。但是,输入 4 到少于 8 个字符也是其他规则的错误。

【问题讨论】:

  • 你是在实际的 trait 中还是在控制器中更改了代码?
  • @Rwd 我没有改变特征。我在控制器中添加了新的规则函数来覆盖它。
  • 你使用的是什么版本的 Laravel?
  • @Rwd 5.8 版

标签: laravel validation forgot-password broker validationrules


【解决方案1】:

您收到错误的原因是因为PasswordBroker 需要一个最小长度为 8 个字符的密码,所以即使您的表单验证通过,PasswordBroker 中的验证也没有。

解决此问题的一种方法是覆盖 ResetPasswordController 中的 broker() 方法并将您自己的验证器传递给它:

public function broker()
{
    $broker = Password::broker();

    $broker->validator(function ($credentials) {
        return $credentials['password'] === $credentials['password_confirmation'];
    });

    return $broker;
}

以上内容与PasswordBroker 本身的情况基本相同,只是没有进行字符串长度检查。

不要忘记将 Password 外观导入您的控制器:

use Illuminate\Support\Facades\Password;

这不是必需的,但为了更好地衡量,我建议同时更新您的 resources/lang/en/passwords.php 文件中的 password 错误消息。

【讨论】:

    猜你喜欢
    • 2015-10-10
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 2019-12-11
    • 2020-07-17
    • 2018-02-10
    • 2019-12-01
    相关资源
    最近更新 更多