1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2026-02-05 15:54:03 +00:00
tenancy/src/Middleware/ScopeSessions.php
lukinovec dc90e60a2f
[4.x] Make ScopeSessions usable on universal routes (#1342)
* Skip ScopeSessions MW if the current context is central and the route is universal

* Add regressiont test

* Simplify code

---------

Co-authored-by: Samuel Štancl <samuel@archte.ch>
2025-04-04 03:15:37 +02:00

41 lines
1.2 KiB
PHP

<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Middleware;
use Closure;
use Illuminate\Http\Request;
use Stancl\Tenancy\Exceptions\TenancyNotInitializedException;
class ScopeSessions
{
public static string $tenantIdKey = '_tenant_id';
/** @var Closure(Request): mixed */
public static Closure|null $onFail = null;
/** @return \Illuminate\Http\Response|mixed */
public function handle(Request $request, Closure $next): mixed
{
if (! tenancy()->initialized) {
if (tenancy()->routeIsUniversal(tenancy()->getRoute($request))) {
return $next($request);
}
throw new TenancyNotInitializedException('Tenancy needs to be initialized before the session scoping middleware is executed');
}
if (! $request->session()->has(static::$tenantIdKey)) {
$request->session()->put(static::$tenantIdKey, tenant()->getTenantKey());
} else {
if ($request->session()->get(static::$tenantIdKey) !== tenant()->getTenantKey()) {
return static::$onFail !== null
? (static::$onFail)($request)
: abort(403);
}
}
return $next($request);
}
}