73 lines
2.3 KiB
PHP
73 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use App\Enums\Users\RoleEnum;
|
|
use App\Models\Tenant;
|
|
use Closure;
|
|
use Illuminate\Http\Request;
|
|
use Symfony\Component\HttpFoundation\Response;
|
|
|
|
class RestrictTenantAccess
|
|
{
|
|
/** @var list<string> $routesWithoutTenant List of routes without tenant in the url. */
|
|
private $routesWithoutTenant = [
|
|
'bo.dashboard',
|
|
'bo.users.*',
|
|
'bo.tenants.*'
|
|
];
|
|
|
|
/**
|
|
* Handle an incoming request.
|
|
*
|
|
* @param \Illuminate\Http\Request $request
|
|
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
|
* @return \Symfony\Component\HttpFoundation\Response
|
|
* @phpcs:disable Squiz.Commenting.FunctionComment.IncorrectTypeHint
|
|
*/
|
|
public function handle(Request $request, Closure $next): Response
|
|
{
|
|
$user = \auth('backend')->user();
|
|
|
|
if ($user && Tenant::count()) {
|
|
$this->throwNotFoundIfTenantDoesntExist($request);
|
|
if ($request->routeIs($this->routesWithoutTenant)) {
|
|
$tenant = ($user->tenants->count()) ? $user->tenants->first() : Tenant::first()->getKey();
|
|
tenancy()->initialize($request->tenant ?? $tenant);
|
|
return $next($request);
|
|
}
|
|
|
|
if (
|
|
!\in_array($request->tenant, $user->tenants->pluck('id')->toArray()) &&
|
|
!(RoleEnum::conceptor->equals($user->role))
|
|
) {
|
|
abort(403);
|
|
}
|
|
|
|
if (RoleEnum::conceptor->equals($user->role)) {
|
|
tenancy()->initialize($request->tenant ?? Tenant::query()->first()->id);
|
|
return $next($request);
|
|
}
|
|
} //end if
|
|
return $next($request);
|
|
}
|
|
|
|
/**
|
|
* Throw NotFoundException if the tenant doesn't exist,
|
|
* instead of Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByPathException.
|
|
*
|
|
* @param \Illuminate\Http\Request $request
|
|
*
|
|
* @return void
|
|
*/
|
|
private function throwNotFoundIfTenantDoesntExist(Request $request)
|
|
{
|
|
if (
|
|
!$request->routeIs($this->routesWithoutTenant) &&
|
|
$request->tenant &&
|
|
!Tenant::query()->find($request->tenant)
|
|
) {
|
|
abort(404);
|
|
}
|
|
}
|
|
}
|