我正在尝试通过其个人资料页面手动向用户提供更改密码功能。经过身份验证的用户可以更改其密码 我有这样的表格:
<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';
}
但是如果从未执行过条件。
答案 0 :(得分:3)
因为bcrypt()
会在不同时间生成不同的哈希值。因此,bcrypt($request->oldPassword)
将不等于存储在数据库中的哈希。尝试两次打印bcrypt('secret')
并观察差异。
改为使用Hash::check()
。
$user=User::where('id',$id)->first();
if(Hash::check($request->oldPassword, $user->password))
{
//statement
}
答案 1 :(得分: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
}
}