手动添加修改密码

Manually adding change password

我正在尝试通过用户的个人资料页面手动向用户提供更改密码功能。经过身份验证的用户可以更改其密码。 我有这个表格:

<form id="changePassword" method="post" action="{{ url('/changePassword', [$user->id]) }}">
                                {{ csrf_field() }}

                                <div class="col-md-6">

                                <label for="password">Old Password</label> 
                                    <input type="password" class="form-control" name="oldPassword" required>
                                </div>

                                <div class="col-md-5"> 
                                <label for="newPassword">New Password</label>  <b style ="color:red">*</b>
                                    <input type="password" id="newPassword" class="form-control" name="newPassword"  required><br>
                                </div>

                                <div class="col-md-5"> 
                                <label for="password-confirm">Confirm Password</label>  <b style ="color:red">*</b>
                                    <input type="password" class="form-control" name="password_confirmation"  required><br>
                                </div>

                                <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Change Password
                                </button>
                                </div>
                                </form>

控制器中的这个函数:

    public function changePassword(Request $request, $id)
    {
        $user=User::where('id',$id)->first();
        if($user && auth()->user('password')==bcrypt($request->oldPassword))
        {
            return 'ok'; 

        }


   return 'No';          
    }

但如果条件永远不会执行。

因为bcrypt()在不同的时间生成不同的散列。因此,bcrypt($request->oldPassword) 将不等于存储在 database.Try 中的散列,两次打印 bcrypt('secret') 并观察差异。

改用Hash::check()

$user=User::where('id',$id)->first();
if(Hash::check($request->oldPassword, $user->password))
 {
    //statement    
}

请尝试以下代码

use Hash;
use Auth;

public function changePassword(Request $request, $id) {

    $user = User::where('id',$id)->first();

    // Old password ( already saved in DB )
    $old_password = $request['old_pass'];

    // New password ( To be updated )
    $new_password = $request['new_pass'];

    // if password in DB matches the password provided
    if ($user && (Hash::check($old_password, $user->password)))  {

      // Hashing new password
      $hash_newpass = Hash::make($new_password);

      // Updating the hashed password
      User::where('id', $id)->update(['password' => $hash_newpass]);
    }

    else {
     // code for failure
    }
}