Validate/Authorize 当前密码在 Laravel 5.1

Validate/Authorize Current Password In Laravel 5.1

我正在尝试为登录的 in/authorized 用户添加密码更改功能。这是您的普通 ole 通用设置:

Current Password
New Password
Confirm New Password

显然我可以只对新密码和密码确认使用验证,但我如何根据他们的实际当前密码授权提交的当前密码?

在用户模型中 password 是一个隐藏的 属性,所以我无法将它们匹配起来。

我试着浏览了 Illiminate\AuthGuard 但我没有在任何地方看到它。也许我错过了,或者我做错了?

获取当前密码并与新密码进行比较。

//use Auth, Hash, Input;

if (Hash::check(Input::get('new_password'), Auth::user()->password))
        echo "Matched";
else
        echo "Not matched";

您是否使用了 laravel 内置的身份验证包?如果是,则已为您完成验证。勾选app/Http/Controller/Auth/AuthController.php,可以看到这个验证函数。如果您愿意,可以添加更多!:

protected function validator(array $data)
{
    return Validator::make($data, [
        'first_name' => 'required|max:255',
        'last_name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users',
        'password' => 'required|confirmed|min:6',
    ]);
}

如果在上述验证过程中发生任何错误,它将被发送到 $errors 变量,您的 blade 视图可以在其中捕获它们。因此,在您的重置密码视图 (view/auth/reset.blade.php) 中,您可以捕获如下验证错误:

@if (count($errors) > 0)
                        <div class="alert alert-danger">
                            <strong>Whoops!</strong> There were some problems with your input.<br><br>
                            <ul>
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
@endif

以下是答案以防其他人在看:

$validator = $this->validator($request->all());

$validator->after(function($validator) use ($request) {
    $check = auth()->validate([
        'email'    => $this->user->email,
        'password' => $request->current_password
    ]);

    if (!$check):
        $validator->errors()->add('current_password', 
            'Your current password is incorrect, please try again.');
    endif;
});

if ($validator->fails()):
    return redirect('account/password')
        ->withErrors($validator)
        ->withInput();
endif;

$this->user->password = bcrypt($request->password);
$this->user->save();