2017-03-24 30 views
0

我试图通过用户手动通过其配置文件页面向用户提供更改密码功能。经过身份验证的用户可以更改其密码。 我有这样的形式:手动添加更改密码

<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';   
    } 

但如果从来没有执行条件。

回答

1

请尝试以下代码

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

因为bcrypt()在不同的时间产生不同的散列。因此,bcrypt($request->oldPassword)将不会等于存储在数据库中的散列。尝试两次不同的时间打印bcrypt('secret')并观察差异。

改为使用Hash::check()

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