我正在尝试测试当前密码是否与数据库中的密码相同。
我的简化控制器:
class ChangePasswordController extends Controller
{
public function update(Request $request, User $user)
{
$this->validate($request, [
'current_password' => ['required', new CurrentPassword()],
'password' => 'required|string|min:6|confirmed'
]);
$user->update([
'password' => bcrypt($request->password)
]);
}
}
在我的自定义CurrentPassword规则中,我正在像这样检查哈希:
class CurrentPassword implements Rule
{
public function passes($attribute, $value)
{
$check = Hash::check($value, auth()->user()->password);
dump($check);
return $check;
}
public function message()
{
return 'Current password is incorrect.';
}
}
我对自定义规则的测试是:
/** @test */
public function an_authenticated_user_may_change_own_password()
{
$this->withoutExceptionHandling();
$user = factory(User::class)->create([
'password' => '1234'
]);
$this->actingAs($user)->patch("/profile/{$user->id}/password", [
'current_password' => '1234',
'password' => 'mynewpassword',
'password_confirmation' => 'mynewpassword'
]);
$this->assertTrue(Hash::check('mynewpassword', $user->fresh()->password));
}
不幸的是,我遇到一个错误:
1) 测试\功能\更新密码测试:: an_authenticated_user_may_change_own_password Illuminate \ Validation \ ValidationException:给定的数据无效。
我不明白为什么这令人发指。当我运行此测试时,我的dump($check);
返回false。我的$ value是'1234',并且auth()-> user()-> password也返回'1234'。也许有人对我在做什么错有个看法。
此测试正在变绿:
/** @test */
public function current_password_must_be_valid()
{
$user = factory(User::class)->create([
'password' => '1234'
]);
$this->actingAs($user)->patch("/profile/{$user->id}/password", [
'current_password' => '12345',
'password' => 'mynewpassword',
'password_confirmation' => 'mynewpassword'
])->assertSessionHasErrors('current_password');
}
答案 0 :(得分:1)
您还应该在工厂中对密码进行哈希处理,否则Eloquent会将其以明文形式存储(这就是auth()->user()->password
返回'1234'的原因)
public function current_password_must_be_valid()
{
$user = factory(User::class)->create([
'password' => Hash::make('1234'); // remember to import the Hash facade
]);
...
}