1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2026-02-05 15:14:04 +00:00

Added request data identification middleware (#207)

* Added request data identification middleware

* Fixed styling

* Changed to Illuminate request instead of helper

* Enabled header and querystring customisation

Co-authored-by: Jesper Jacobsen <joj@webshipper.com>
This commit is contained in:
JapSeyz 2020-03-15 21:37:37 +01:00 committed by GitHub
parent 13422fb090
commit fa861ed6dd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 71 additions and 0 deletions

View file

@ -95,6 +95,10 @@ return [
'storage_to_config_map' => [ // Used by the TenantConfig feature 'storage_to_config_map' => [ // Used by the TenantConfig feature
// 'paypal_api_key' => 'services.paypal.api_key', // 'paypal_api_key' => 'services.paypal.api_key',
], ],
'identification' => [
'header' => 'X-Tenant', // Can be anything, but should really start with "X-",
'query_parameter' => '_tenant'
],
'home_url' => '/app', 'home_url' => '/app',
'create_database' => true, 'create_database' => true,
'queue_database_creation' => false, 'queue_database_creation' => false,

View file

@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Middleware;
use Closure;
use Illuminate\Http\Request;
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedException;
class InitializeTenancyByRequestData
{
/** @var callable */
protected $onFail;
public function __construct(callable $onFail = null)
{
$this->onFail = $onFail ?? function ($e) {
throw $e;
};
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->method() !== 'OPTIONS') {
try {
$this->parseTenant($request);
} catch (TenantCouldNotBeIdentifiedException $e) {
($this->onFail)($e);
}
}
return $next($request);
}
protected function parseTenant(Request $request)
{
if (tenancy()->initialized) {
return;
}
$header = config('tenancy.identification.header');
$query = config('tenancy.identification.query_parameter');
$tenant = null;
if ($request->hasHeader($header)) {
$tenant = $request->header($header);
} elseif ($request->has($query)) {
$tenant = $request->get($query);
} elseif (! in_array($request->getHost(), config('tenancy.exempt_domains', []), true)) {
$tenant = explode('.', $request->getHost())[0];
}
if (! $tenant) {
throw new TenantCouldNotBeIdentifiedException($request->getHost());
}
tenancy()->initialize(tenancy()->find($tenant));
}
}