laravel5.5 一定时间用户无操作自动退出登录

场景

  • 公司项目经常会要求,在一定时间内无操作 则自动退出登陆
  • 环境
    • laravel5.5

参考资料

分析

  • 这个需要分析每一次请求,所以定义一次全局的middleware

解决

  • session记录上次访问的时间, 比较和当前访问的时间戳是否达到了要求, 如果超过了限制 退出登陆状态 && 跳转到登陆页面
  • 我是用了laravel echo服务 所以增加了一个属性,去屏蔽pusher路由
代码
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class SessionTimeout
{
    /*
     * 用户上次活动的时间
     * */
    private $key_session_last_active = 'last_active_time';

    /*
     * 保持时间
     * */
    private $time_decay = 7200;

    private $list_except_path = [
        'broadcasting/auth'
    ];

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 没有登陆则继续下面的请求 &&  pusher service path 排除
        $path = $request->path();
        if (!auth()->check() || in_array($path, $this->list_except_path)) {
            return $next($request);
        }

        // 如果上次缓存有存值
        if (session()->has($this->key_session_last_active)) {
            // 如果超过session的衰变期 && 还在登录状态
            $time_decay = time() - session($this->key_session_last_active);
            if ($time_decay > $this->time_decay) {
                $email = auth()->user()->email;
                auth()->logout();
                session()->forget($this->key_session_last_active);
                return redirect('login')->withInput(compact('email'));
            }
        }

        // logout操作
        if ($this->determineLogoutAction()){
            session()->has($this->key_session_last_active) && session()->forget($this->key_session_last_active);
        } else {
            session()->put($this->key_session_last_active, time());
        }

        return $next($request);
    }

    /**
     * 是否是logout action
     * @return bool
     */
    private function determineLogoutAction(): bool
    {
        $route_name = request()->route()->getName();
        return $route_name === 'logout';
    }
}

猜你喜欢

转载自blog.csdn.net/cominglately/article/details/86665261
今日推荐