Laravel 单设备登录

https://laravel-china.org/articles/10605/laravel-single-device-login

前几天在 laracasts 看了laravel5.6的新功能视频 logoutOtherDevices 用于使在其他设备上处于活动状态的用户会话无效并“注销”,而不会使其当前设备上的会话无效。,今天抽空把它应用到了系统里,在这里记录下吧。
在使用此功能前需要先把 app/Http/Kernel.php web 中间件中的 \Illuminate\Session\Middleware\AuthenticateSession::class 注释取消掉。

LoginController 控制器中继承 Illuminate\Foundation\Auth\AuthenticatesUsers 类中的 authenticated 方法。

protected function authenticated(Request $request, $user)
{
    $this->guard()->logoutOtherDevices($request->password);
    return response()->json(['message' => '登录成功']);
}

logoutOtherDevices 接受两个参数,第一个参数是来自表单提交的数据,然后经过加密保存到第二个参数指定的字段里,在经过中间件储存 session

public function logoutOtherDevices($password, $attribute = 'password')
{
    if (! $this->user()) {
        return;
    }

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

 

 

这样在用户登录成功后,即会注销其他设备上的会话而实现单设备登陆。

posted @ 2018-09-06 13:46  码农编程进阶笔记  阅读(684)  评论(0编辑  收藏  举报
返回顶部 有事您Q我