【问题标题】:Is it possible to force logout using user id in Laravel?是否可以在 Laravel 中使用用户 ID 强制注销?
【发布时间】:2016-06-17 07:51:37
【问题描述】:

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

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

【问题讨论】:

  • 为什么不能使用中间件?
  • @PeterPan666 因为项目非常大,检查每个被阻止用户的请求会消耗一些性能。我已经在登录时检查阻止状态。

标签: laravel


【解决方案1】:

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

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

    return Redirect::home();
}

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

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

【讨论】:

  • 你如何在 laravel 5.4 中做到这一点。 auth 中间件现在位于Illuminate\Auth\Middleware\Authenticate。我要在/app/Http/Middleware/Authenticate.php 中创建和复制它并添加我的条件语句吗?
  • 你可以做一个 LogoutDisableUser 中间件并在 auth 中间件之前调用它,甚至创建一个名为“auth”的组,然后调用 logout inactive 然后里面的 auth 中间件;)
【解决方案2】:

如果您使用的是数据库会话驱动程序,那就超级简单了:

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

【讨论】:

    【解决方案3】:

    @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);
        }
    

    【讨论】:

      【解决方案4】:

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

      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'));
      
      

      【讨论】:

        猜你喜欢
        • 2017-05-17
        • 2019-04-30
        • 2017-11-18
        • 1970-01-01
        • 1970-01-01
        • 2016-11-04
        • 1970-01-01
        • 2020-03-18
        • 2014-11-12
        相关资源
        最近更新 更多