From 68c5453cdb24ba8b56457cde8cc083ef4efdb04b Mon Sep 17 00:00:00 2001 From: Jeffrey Li Date: Mon, 6 Jul 2020 20:45:21 -0400 Subject: [PATCH] Support session database --- README.md | 4 ++++ .../DatabaseSessionChecker.php | 18 ++++++++++++++++++ src/TimeoutCalculator/TimeoutCalculator.php | 5 +++-- 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 src/TimeoutCalculator/DatabaseSessionChecker.php diff --git a/README.md b/README.md index f207846..cd1fd56 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,10 @@ When the session is about to expire, show a dialog so the user can choose not to ![](screenshot.png) +## How it works + +This code doesn't actually log the user out. It still relies on Laravel's mechanism for expiring sessions. All it does is periodically check how much time before the session will expire and alert the user when it is almost time. + ## Installation Laravel package and NPM dependencies diff --git a/src/TimeoutCalculator/DatabaseSessionChecker.php b/src/TimeoutCalculator/DatabaseSessionChecker.php new file mode 100644 index 0000000..d7edd72 --- /dev/null +++ b/src/TimeoutCalculator/DatabaseSessionChecker.php @@ -0,0 +1,18 @@ +where('id', $this->sessionId)->first(); + if (!$session) { + throw new TimeoutCalculatorException('Session not found'); + } + + return $session->last_activity; + } +} diff --git a/src/TimeoutCalculator/TimeoutCalculator.php b/src/TimeoutCalculator/TimeoutCalculator.php index a546bae..1c3376e 100644 --- a/src/TimeoutCalculator/TimeoutCalculator.php +++ b/src/TimeoutCalculator/TimeoutCalculator.php @@ -25,8 +25,9 @@ public static function getSecondsLeft(Request $request) $sessionId = Crypt::decryptString($request->cookie('laravel_session')); switch (config('session.driver')) { - case 'file': $checker = new FileSessionChecker($sessionId); break; - default: throw new TimeoutCalculatorException('Session driver not supported'); + case 'database': $checker = new DatabaseSessionChecker($sessionId); break; + case 'file': $checker = new FileSessionChecker($sessionId); break; + default: throw new TimeoutCalculatorException('Session driver not supported'); } $secondsSince = time() - $checker->getLastModified();