Skip to content

Instantly share code, notes, and snippets.

@JosephNC
Forked from torshid/.env
Created May 15, 2023 20:43
Show Gist options
  • Save JosephNC/e5364c1cf70014aeb4f6146c834e160d to your computer and use it in GitHub Desktop.
Save JosephNC/e5364c1cf70014aeb4f6146c834e160d to your computer and use it in GitHub Desktop.
https://larawind.com/shared-laravel-sessions-across-domains Shared Laravel sessions across domains
PORTAL_DOMAIN=localhost
SESSION_DRIVER=shared
<?php
return [
// ...
'portal_domain' => env('PORTAL_DOMAIN', 'localhost'),
// ...
'providers' => [
// ...
App\Providers\SessionServiceProvider::class,
],
// ...
];
<?php
namespace App\Extensions;
use Illuminate\Session\DatabaseSessionHandler as BaseDatabaseSessionHandler;
class DatabaseSessionHandler extends BaseDatabaseSessionHandler
{
protected function performInsert($sessionId, $payload)
{
// if we're not in the portal domain and we're trying to create a session, we redirect to the portal
// that way, we are preventing all domains except the portal from creating sessions
if (request()->getHost() != config('app.portal_domain')) {
// assuming the portal's route is in the same app
return redirect()->route('session', ['origin' => request()->fullUrl()])->send();
}
parent::performInsert($sessionId, $payload);
}
}
<?php
protected $middlewareGroups = [
'web' => [
// ...
// \Illuminate\Session\Middleware\StartSession::class,
\App\Http\Middleware\StartSession::class,
// ...
replaceQueryParameter('session', '');
function replaceQueryParameter(parameter, value) {
var queryParams = new URLSearchParams(window.location.search);
if (value == '')
queryParams.delete(parameter);
else
queryParams.set(parameter, value);
history.replaceState(null, null, queryParams.toString() == '' ? window.location.href.split('?')[0] : '?' + queryParams.toString());
}
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\ServiceProvider;
class SessionServiceProvider extends ServiceProvider
{
public function boot()
{
Session::extend('shared', function ($app) {
$table = $app['config']['session.table'];
$lifetime = $app['config']['session.lifetime'];
$connection = $app['db']->connection($app['config']['session.connection']);
return new \App\Extensions\DatabaseSessionHandler($connection, $table, $lifetime, $app);
});
}
}
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Illuminate\Session\Middleware\StartSession as BaseStartSession;
class StartSession extends BaseStartSession
{
public function getSession(Request $request)
{
if ($request->getHost() == config('app.portal_domain')) {
return tap($this->manager->driver(), function (\Illuminate\Contracts\Session\Session $session) use ($request) {
$session->setId($request->cookies->get($session->getName()));
});
}
return tap($this->manager->driver(), function (\Illuminate\Contracts\Session\Session $session) use ($request) {
if ($request->query('session')) {
$session->setId(\Crypt::decryptString($request->query('session')));
} else {
$session->setId($request->cookies->get($session->getName()));
}
});
}
}
<?php
// ...
Route::domain(config('app.portal_domain'))
->group(function () {
Route::get('/session', function (Request $request) {
return redirect()->intended(merge_parameters_to_url($request->get('origin'), ['session' => \Crypt::encryptString(\Session::getId())]));
})->name('session');
});
Route::domain('tenant')
->group(function () {
Route::get('/', function (Request $request) {
return 'I am the tenant. You have a valid session if you\'re reading this.';
})->name('tenant.index');
});
// ...
// may put this function somewhere else
function merge_parameters_to_url($url, array $parameters = [])
{
foreach ($parameters as $key => $value) {
$value = urlencode($value);
$url = preg_replace('/(.*)(?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
$url = substr($url, 0, -1);
if (strpos($url, '?') === false) {
$url = $url . '?' . $key . '=' . $value;
} else {
$url = $url . '&' . $key . '=' . $value;
}
}
return $url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment