是否可以在 Laravel 中使用用户 ID 强制注销?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37876033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:00:12  来源:igfitidea点击:

Is it possible to force logout using user id in Laravel?

laravel

提问by Kin

I'm wondering if there is any simple way to force logout different users by their id? For example I need to block currently lodged in user so I want to log out him after I set his status to block.

我想知道是否有任何简单的方法可以通过他们的 id 强制注销不同的用户?例如,我需要阻止当前入住的用户,所以我想在将他的状态设置为阻止后注销他。

P.S. I cant use middleware for this to check on each request.

PS 我不能为此使用中间件来检查每个请求。

回答by PeterPan666

I do this inside the Authenticate middleware

我在 Authenticate 中间件中执行此操作

if (!Auth::user()->isActive()) {
    Auth::logout();

    return Redirect::home();
}

The user is already loaded there, no additional database query is needed here.

用户已经在那里加载,这里不需要额外的数据库查询。

I don't think that's a performance issue, you just do a little if statement and you do it only if the user needs to be authenticated.

我不认为这是性能问题,您只需执行一点 if 语句,并且仅在用户需要进行身份验证时才执行此操作。

回答by Sinan Eldem

It's super easy if you are using database session driver:

如果您使用数据库会话驱动程序,这非常容易:

DB::table('sessions')->where('user_id', $userId)->delete();

回答by w1n78

@PerterPan666 thanks, ya i ended up creating a middleware and adding it to the web group.

@PerterPan666 谢谢,是的,我最终创建了一个中间件并将其添加到网络组中。

public function handle($request, Closure $next)
    {
        if (Auth::check())
        {
            if (Auth::User()->is_active != 'Y')
            {
                Auth::logout();
                return redirect()->to('/')->with('warning', 'Your session has expired because your account is deactivated.');
            }
        }
        return $next($request);
    }

回答by Alistair R

For anyone using later Laravel 5.6+, there's a method available for this built in. Doesn't mention where to call logoutOtherDevices, but LoginController@authenticated looks to work well as you can pass through their password, as required by the method

对于使用更高版本 Laravel 5.6+ 的任何人,有一个可用的内置方法。没有提到在哪里调用logoutOtherDevices,但 LoginController@authenticated 看起来工作得很好,因为你可以按照方法的要求传递他们的密码

https://laravel.com/docs/5.8/authentication#invalidating-sessions-on-other-devices

https://laravel.com/docs/5.8/authentication#invalidating-sessions-on-other-devices

public function authenticated(Request $request, $throttles)
{
    \Illuminate\Support\Facades\Auth::logoutOtherDevices($request->get('password'));