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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37557820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:17:20  来源:igfitidea点击:

How to validate current, new, and new password confirmation in Laravel 5?

phplaravellaravel-5laravel-5.2

提问by Halnex

I have created the password route, view and method in UserController@getProfilePasswordand UserController@postProfilePassword

我创建的密码路线,观点和方法UserController@getProfilePassword,并UserController@postProfilePassword

At the moment, if I fill out the new_passwordfield, it gets hashed and submitted to the database correctly, then I can login with the new password.

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

But I need to be able to validate the new_passwordand new_password_confirmto make sure they're the same and validate the user's current password as well.

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

How can I do that?

我怎样才能做到这一点?

EDIT: I added $this->validateto the method, but now I keep getting the error The password confirmation confirmation does not match.even though they do match as I am using a simple password. Also I think I need to check against the current password manually as validatorwon't do it for me.

编辑:我添加$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();
}

And this is the view

这是视图

<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>

回答by Sid

There's a Hash::check()function which allows you to check whether the old password entered by user is correct or not.

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

usage

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

it will return true if old password has been entered correctly and you can add your logic accordingly

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

for new_passwordand new_confirm_passwordto be same, you can add your validation in form request like

对于new_passwordnew_confirm_password是一样的,你可以在样形式请求添加验证

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

回答by Steve

If you only need the functionality of a custom rule once throughout your application, you may use a Closure instead of a rule object. The Closure receives the attribute's name, the attribute's value, and a $fail callback that should be called if validation fails

如果您在整个应用程序中只需要一次自定义规则的功能,您可以使用闭包而不是规则对象。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

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

回答by kjdion84

You can do this by creating a custom validation rule (for this example I'm using current_passwordand new_passwordas the input names).

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

Put this in AppServiceProvider::boot():

把这个放在AppServiceProvider::boot()

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

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

Now you can use the following in your controller:

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

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

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

回答by Arash Moosapour

In Laravel 6 there is a new rule called password,according to docs

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

The field under validation must match the authenticated user's password. You may specify an authentication guard using the rule's first parameter:
'password' => 'password:api'

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

so the validation rules can be as simple as :

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

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

回答by MR_AMDEV

Using laravel 5.8/6.0, here is what i do(without much additional code)

使用laravel 5.8/6.0,这就是我所做的(没有太多额外的代码)

Step 1: Validate

第 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.'));
            }
        }]
    ]);

Step 2: If validation is passed

第 2 步:如果验证通过

  1. Create array , checking each input value (but not the ones with the required tag in validation)for presence or null OR do something that you want.
  1. 创建 array ,检查每个输入值(但不是验证中带有所需标记的值)是否存在或为空,或者执行您想要的操作。

For example:

例如:

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

For example:

例如:

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

回答by Developer

Laravel Check Old Password and Updating a New Password| More

Laravel 检查旧密码并更新新密码| 更多的

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

        }
    }

回答by PHP Worm...

A complete function which will check everything. You just need to send old_password, new_passwordand confirm_password.

一个完整的功能,将检查一切。您只需要发送old_password,new_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);
            }
        }

回答by Sanji

You can add confirmedas it's to confirm old password. And 'required|confirmed'you change to 'required|same:password'to compare passwordand password confirmation

您可以confirmed按原样添加以确认旧密码。然后'required|confirmed''required|same:password'改为比较passwordpassword confirmation

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

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

Good luck!

祝你好运!