使用“logoutOtherDevices”时,Laravel 新密码不会保存到数据库中

Posted

技术标签:

【中文标题】使用“logoutOtherDevices”时,Laravel 新密码不会保存到数据库中【英文标题】:Laravel new password not persisting to database when using `logoutOtherDevices` 【发布时间】:2020-08-04 22:59:47 【问题描述】:

我正在尝试在 Laravel 7 中创建一个密码更新表单,即当前登录用户可以用来更改密码的表单。

我正在使用默认的 laravel 身份验证包,只是在它的基础上构建。

我的更新功能似乎没有将新用户密码保存到数据库中。我已确认我的新/旧密码不同。提交表单后,我仍然可以使用旧密码登录,但新密码不起作用。没有错误(我开启了开发模式)。数据库正在获取新的时间戳,并且哈希值正在发生变化。

/**
 * Update current user's password
 * @param Request $request
 * @return JsonResponse
 */
public function updatePassword(Request $request)

    $validator = Validator::make($request->only(['current_password', 'password', 'password_confirmation']), [
        'current_password' => ['required'],
        'password' => ['required', 'string', 'min:10', 'confirmed']
    ]);
    $user = User::findOrFail(Auth::user()->id);
    $validator->after(function ($validator) use ($request, $user) 
        if (!Hash::check($request->current_password, $user->password)) 
            $validator->errors()->add('current_password', 'The current value does not match our records.');
        
    )->validate();
    //echo 'current password: '. $request->current_password . '<br>';
    //echo 'new password: ' . $request->password . '<br>';
    $currentPassword = $request->current_password;
    $user->password = Hash::make($request->password);
    $user->setRememberToken(Str::random(60));
    $user->save();
    Auth::logoutOtherDevices($currentPassword);
    return response()->json(['success' => true, 'msg' => 'Password updated!']);

【问题讨论】:

你可以在 $currnetPassword = $request->current_password; 之后调试 ($request->password)结果为空? 结果如预期。新密码。 【参考方案1】:

注释掉logoutOutOtherDevices,新密码将保留在数据库中。除了需要当前密码外,Laravel 几乎没有提供有关如何使用该功能的信息。由于操作顺序是先更新再注销其他设备,所以需要添加新密码而不是之前的密码。

Auth::logoutOtherDevices($request->password); // i.e. the current (new) password

这是由于logoutOtherDevices()中的这行代码:

    $result = tap($this->user()->forceFill([
        $attribute => Hash::make($password),
    ]))->save();

【讨论】:

以上是关于使用“logoutOtherDevices”时,Laravel 新密码不会保存到数据库中的主要内容,如果未能解决你的问题,请参考以下文章

Java:指定long时L和l(小写L)有区别吗?

使用 (void *) 作为通用数据容器时的 L 值问题

Windows 锁定时截取桌面截图 (Win+L)

为什么gcc在使用-l时动态链接?

Axure RP使用攻略--入门级

在android L上加载OpenCV时如何删除日志记录