当我在Laravel框架中注册新用户时,我现在正在这样做,
$newPass = bcrypt($response->new_password);
这很好用,我可以登录到该应用程序。但是,我希望用户可以选择在其设置页面中更改其密码。这样做,我使用相同的技术,使用
// Validation
$this->validate($request, [
'email' => 'email',
'password' => 'min:8|confirmed',
'current_password' => 'required',
]);
// Getting the user ID
$userId = Auth::id();
// Dummy hack check, change later.
if(!Auth::attempt(['id' => $userId, 'password' => $request->current_password]))
{
return redirect('settings')->with('alert','current password is wrong.');
}
// Everything is validated and ok to proceed
if($request->email)
{
$data['email'] = $request->email;
}
if($request->password)
{
$data['password'] = bcrypt("helloworld");
}
$user = User::where('id',$userId)->update($data);
dd($data);
并更新用户字段。但是,这样做之后,我无法登录?我在laravel中使用内置身份验证服务进行注册/登录。
我在这里做错了什么?我应该采取另一种方式吗?
我还试图加密我当前的密码,而且我得到的哈希值与存储在数据库中的哈希值完全不同。
这太令人困惑..
更新了控制器代码
+request: ParameterBag {#40 ▼
#parameters: array:5 [▼
"_token" => "JQIIuCjiKQmbK0X5zCM6czYD1vIoh4PGjLO4qrFm"
"email" => "testing@gmail.com"
"password" => "thisisnewpass"
"password_confirmation" => "thisisnewpass"
"current_password" => "helloworld"
]
}
转储输入数据
{{1}}
答案 0 :(得分:0)
此代码更接近Laravel如何处理内部重置用户密码的方式。试一试。
// Getting the User
$user = Auth::user(); // Gets the currently logged in User
$credentials = [
'id' => $user->id,
'password' => $request->input('current_password')
];
// Make sure current password is correct
if (!Auth::validate($credentials)) { // Checks the User's credentials
return redirect('settings')->with('alert','current password is wrong.');
}
// Change the password
if ($request->has('password')) {
$user->password = bcrypt($request->input('password'));
}
// Save any changes
$user->save();
您似乎也在使用相同的表单来更新用户的电子邮件地址,因此请更新代码以满足您的需求。
答案 1 :(得分:0)
将密码存储在新变量中似乎可以解决问题(不知道为什么?)但是,这是使一切正常运行的代码,
// Validation
$this->validate($request, [
'email' => 'email',
'password' => 'min:8|confirmed',
'current_password' => 'required',
]);
// Getting the user ID
$userId = Auth::id();
$newPassword = $request->password;
// Dummy hack check, change later.
if(!Auth::attempt(['id' => $userId, 'password' => $request->current_password]))
{
return redirect('settings')->with('alert','Wrong password.');
}
// Everything is validated and ok to proceed
if($request->email)
{
$data['email'] = $request->email;
}
if($request->password)
{
$data['password'] = bcrypt($newPassword);
}
// Getting, and checking if the current password is corrent.
$user = User::where('id',$userId)->update($data);
echo $newPassword . "<br><br>";
dd($data);
如果有任何我没有看到的解释,请告诉我原因。但是,它现在正在运作。
答案 2 :(得分:0)
对于2017年的Laravel,这就是我们推出的方式:
//create a setter method in your controller
public function setPasswordAttribute( $password ) {
if ( $password !== null ) {
if ( is_null(request()->bcrypt) ) {
$this->attributes['password'] = bcrypt($password);
} else {
$this->attributes['password'] = $password;
}
}
}
检查this链接,他们都在谈论将它放在模型中,但它可以在我自己的控制器中运行。