Skip to content

Commit

Permalink
add session override
Browse files Browse the repository at this point in the history
  • Loading branch information
joshmanders committed Aug 12, 2024
1 parent ed75a1b commit 4f38c88
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/Session/DatabaseSessionHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace NiftyCo\Support\Session;

use Carbon\Carbon;

/**
* @TODO:
* 1. Change column `last_activity` => :timestamp to `last_active_at` => :datetime
* 2. Update all underlining `last_activity` usage to account for new column and format
* 3. Create `Session` model that has a virtual columns of `browser` and `location` that
* return mobiledetect parsing on `browser` and geoip data on `location`
* 4. Update `User` model to add a `sessions` relationship that returns all sessions
*/
class DatabaseSessionHandler extends \Illuminate\Session\DatabaseSessionHandler
{
protected function expired($session): bool
{
if (isset($session->last_active_at)) {
return Carbon::parse($session->last_active_at)->lessThan(now()->subMinutes($this->minutes));
}

return false;
}

protected function getDefaultPayload($data): array
{
$payload = [
'payload' => base64_encode($data),
'last_active_at' => now(),
];

if (!$this->container) {
return $payload;
}

return tap($payload, function (&$payload) {
$this->addUserInformation($payload)
->addRequestInformation($payload);
});
}

protected function performInsert($sessionId, $payload): bool|null
{
return parent::performInsert($sessionId, [
...$payload,
'created_at' => now(),
]);
}

public function gc($lifetime): int
{
return $this->getQuery()
->where('last_active_at', '<=', now()->subMinutes($lifetime))
->delete();
}
}
32 changes: 32 additions & 0 deletions src/Session/ServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace NiftyCo\Support\Session;

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\Session;


class ServiceProvider extends \Illuminate\Support\ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}

/**
* Bootstrap any application services.
*/
public function boot(): void
{
Session::extend('database', function (Application $app) {
$table = $app['config']->get('session.table');
$lifetime = $app['config']->get('session.lifetime');
$connection = $app['db']->connection($app['config']->get('session.connection'));

return new DatabaseSessionHandler($connection, $table, $lifetime, $app);
});
}
}

0 comments on commit 4f38c88

Please sign in to comment.