如何在Laravel中验证bcrypt密码?

时间:2018-01-21 07:12:07

标签: php laravel validation laravel-5

我有一个更改密码表单,其中包含旧密码和新密码的字段 旧密码字段名为old_password

在我的控制器中,我正在验证像这样的密码

$this->validate($request, [
            'old_password' => 'required|min:6|exists:users,password',
            'password' => 'required|min:6:max:30',
]); 

但它不能正常工作,直接将old_password与没有函数bcrypt()的密码进行比较。

那么如何将old_password字段与用户字段中已存储的加密密码进行比较。

  

注意:我想回复验证错误,密码没有   如果不同则匹配

2 个答案:

答案 0 :(得分:2)

这就是我如何制作这样一个功能

HTML表单

<form action="{{ url('admin/admin-admin-password-update/'.$admin->id) }}" method="post">
    {{ csrf_field() }}
    <div class="form-group {{ $errors->has('new_password') ? 'has-error' : '' }}">
        <label for="new_password" class="form-label">New Password (Minimum of 6 characters. No spaces.) <span class="required-alert">*</span></label>
        <input type="password" class="form-control" name="new_password" id="new_password" />

        @if ($errors->has('new_password'))
            <div class="help-block">
                 {{ $errors->first('new_password') }}
            </div>
       @endif

   </div>
   <div class="form-group {{ $errors->has('confirm_password') ? 'has-error' : '' }}">
        <label for="confirm_password" class="form-label">Confirm New Password <span class="required-alert">*</span></label>
        <input type="password" class="form-control" name="confirm_password" id="confirm_password" />

        @if ($errors->has('confirm_password'))
            <div class="help-block">
                 {{ $errors->first('confirm_password') }}
            </div>
       @endif

  </div>
  <div class="form-group clearfix">
     <button type="submit" class="btn btn-primary">Save New Password</button>
  </div>
 </form>

控制器代码

public function updatePassword(Request $request)
{
    $this->admin = Auth::user();
    $this->id   = $this->admin->id;

    $this->validate($request, [
       'current_password'   => 'required',
       'password'           => 'required|min:6',
       'confirm_password'   => 'required|same:password',
    ]);

    if (Hash::check($request->input('current_password'), $this->admin->password)) {
        $this->admin->password = Hash::make($request->input('password'));

        $this->admin->save();

        return redirect()->back()->with('success', 'Your password has been updated.');
    } else {
        return redirect()->back()->with('warning', 'The current password you provided could not be verified');
    }
}

答案 1 :(得分:0)

您需要比较old_password和您想要比较的其他密码的哈希结果。

// when old_password is not encrypted but other_password is:
bcrypt('old_password') === hash_of_other_password

使用$this->validate并且不编写自定义规则的一种方法是使用$request->merge()。这样,如果您的数据库中存储了散列值,则可以使用confirmed规则甚至exists