如何在Laravel 5中验证当前,新的和新的密码确认?

时间:2016-06-01 00:52:56

标签: php laravel laravel-5 laravel-5.2

我在UserController@getProfilePasswordUserController@postProfilePassword

中创建了密码路由,视图和方法

目前,如果我填写new_password字段,它会被哈希并正确提交到数据库,然后我可以使用新密码登录。

但我需要能够验证new_passwordnew_password_confirm,以确保它们相同并验证用户当前的密码。

我该怎么做?

编辑:我在方法中添加了$this->validate,但现在我不断收到错误The password confirmation confirmation does not match.,即使它们匹配,因为我使用的是简单的密码。此外,我认为我需要手动检查当前密码,因为validator不会为我做这件事。

public function getProfilePassword(Request $request) {
    return view('profile/password', ['user' => Auth::user()]);
}

public function postProfilePassword(Request $request) {
    $user = Auth::user();

    $this->validate($request, [
        'old_password'          => 'required',
        'password'              => 'required|min:4',
        'password_confirmation' => 'required|confirmed'
    ]);

    $user->password = Hash::make(Input::get('new_password'));
    $user->save();
}

这是视图

<form action="{{ route('profile/updatepassword') }}" method="post" enctype="multipart/form-data">
    <div class="form-group">
          <label for="name">Current Password</label>
          <input type="password" name="old_password" class="form-control" id="old_password">
    </div>
    <div class="form-group">
          <label for="name">Password</label>
          <input type="password" name="password" class="form-control" id="password">
    </div>
    <div class="form-group">
          <label for="name">New Password</label>
          <input type="password" name="password_confirmation" class="form-control" id="password_confirmation">
    </div>
    <button type="submit" class="btn btn-primary">Change Password</button>
    <input type="hidden" value="{{ Session::token() }}" name="_token">
 </form>

8 个答案:

答案 0 :(得分:43)

Hash::check()功能,可让您检查用户输入的旧密码是否正确。

usage

if (Hash::check("param1", "param2")) {
 //add logic here
}

param1 - user password that has been entered on the form
param2 - old password hash stored in database

如果输入的密码正确,则会返回true,您可以相应地添加逻辑

new_passwordnew_confirm_password相同,您可以在表格请求中添加验证,例如

'new_password' => 'required',
'new_confirm_password' => 'required|same:new_password'

答案 1 :(得分:4)

您可以通过创建自定义验证规则来执行此操作(对于此示例,我使用current_passwordnew_password作为输入名称)。

将其放入AppServiceProvider::boot()

Validator::extend('current_password', function ($attribute, $value, $parameters, $validator) {
    $user = User::find($parameters[0]);

    return $user && Hash::check($value, $user->password);
});

现在您可以在控制器中使用以下内容:

$user = auth()->user(); // or pass an actual user here

$this->validate($request, [
    'current_password' => 'required_with:new_password|current_password,'.$user->id,
]);

答案 2 :(得分:3)

  

如果在整个应用程序中只需要一次自定义规则的功能,则可以使用闭包代替规则对象。 Closure会接收属性的名称,属性的值,以及在验证失败时应调用的$ fail回调

$request->validate([
    'new_password' => 'required|confirmed|min:4',
    'current_password' => ['required', function ($attribute, $value, $fail) use ($user) {
        if (!\Hash::check($value, $user->password)) {
            return $fail(__('The current password is incorrect.'));
        }
    }],
]);

https://laravel.com/docs/5.6/validation#using-closures

答案 3 :(得分:2)

您可以添加confirmed来确认旧密码。 并'required|confirmed'更改为'required|same:password'以比较passwordpassword confirmation

'old_password' => 'required|confirmed', 'password' => 'required|min:4', 'password_confirmation' => 'required|same:password'

祝你好运!

答案 4 :(得分:1)

使用 laravel 5.8 / 6.0 ,这是我的工作(无需很多其他代码)

第1步:验证

    $data = request()->validate([
        'firstname' => ['required', 'string', 'max:255'],
        'lastname' => ['required', 'string', 'max:255'],
        'username' => ['bail', 'nullable', 'string', 'max:255', 'unique:users'],
        'email' => ['bail', 'nullable', 'string', 'email:rfc,strict,dns,spoof,filter', 'max:255', 'unique:users'],
        'new_password' => ['nullable', 'string', 'min:8'],
        'confirm_new_password' => ['nullable', 'required_with:new_password', 'same:new_password'],
        'current_password' => ['required', function ($attribute, $value, $fail) {
            if (!\Hash::check($value, Auth::user()->password)) {
                return $fail(__('The current password is incorrect.'));
            }
        }]
    ]);

步骤2:如果通过了验证

  1. 创建数组,检查每个输入值(但不验证中带有必需标记的输入值),是否存在或为空或执行您想要的操作。

例如:

if(request(input)){
    $data += ['input' => request(input)];
}
  1. 使用创建的数组更新数据库

例如:

Auth::user()->account->update($data);

答案 5 :(得分:1)

根据文档,在Laravel 6中有一个名为password的新规则

  

验证中的字段必须与经过身份验证的用户密码匹配。您可以使用规则的第一个参数指定身份验证保护:
  'password'=>'password:api'

所以验证规则可以很简单:

'current_password' => 'required|password',
'password' => 'required|string|min:8|confirmed',

答案 6 :(得分:0)

一个完整的功能,可以检查所有内容。您只需发送old_passwordnew_passwordconfirm_password

public function changePassword(Request $request) {
            try {
                $valid = validator($request->only('old_password', 'new_password', 'confirm_password'), [
                    'old_password' => 'required|string|min:6',
                    'new_password' => 'required|string|min:6|different:old_password',
                    'confirm_password' => 'required_with:new_password|same:new_password|string|min:6',
                        ], [
                    'confirm_password.required_with' => 'Confirm password is required.'
                ]);

                if ($valid->fails()) {
                    return response()->json([
                                'errors' => $valid->errors(),
                                'message' => 'Faild to update password.',
                                'status' => false
                                    ], 200);
                }
    //            Hash::check("param1", "param2")
    //            param1 - user password that has been entered on the form
    //            param2 - old password hash stored in database
                if (Hash::check($request->get('old_password'), Auth::user()->password)) {
                    $user = User::find(Auth::user()->id);
                    $user->password = (new BcryptHasher)->make($request->get('new_password'));
                    if ($user->save()) {
                        return response()->json([
                                    'data' => [],
                                    'message' => 'Your password has been updated',
                                    'status' => true
                                        ], 200);
                    }
                } else {
                    return response()->json([
                                'errors' => [],
                                'message' => 'Wrong password entered.',
                                'status' => false
                                    ], 200);
                }
            } catch (Exception $e) {
                return response()->json([
                            'errors' => $e->getMessage(),
                            'message' => 'Please try again',
                            'status' => false
                                ], 200);
            }
        }

答案 7 :(得分:0)

Laravel检查旧密码并更新新密码 | this Stackflow question

public function updatePassword(Request $request)
    {
        $this->validate($request, [
            'old_password'     => 'required',
            'new_password'     => 'required|min:6',
            'confirm_password' => 'required|same:new_password',
        ]);

        $data = $request->all();

        if(!\Hash::check($data['old_password'], auth()->user()->password)){

             return back()->with('error','You have entered wrong password');

        }else{

           here you will write password update code

        }
    }