mirror of
https://github.com/archtechx/tenancy.git
synced 2025-12-12 17:24:03 +00:00
[2.3.0] More identification middleware (#323)
* 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> * Apply fixes from StyleCI * Use constructor parameter instead of config * Add tests * Apply fixes from StyleCI Co-authored-by: JapSeyz <JapSeyz@JapSeyz.com> Co-authored-by: Jesper Jacobsen <joj@webshipper.com>
This commit is contained in:
parent
13422fb090
commit
f6115d590a
2 changed files with 132 additions and 0 deletions
70
src/Middleware/InitializeTenancyByRequestData.php
Normal file
70
src/Middleware/InitializeTenancyByRequestData.php
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedException;
|
||||
|
||||
class InitializeTenancyByRequestData
|
||||
{
|
||||
/** @var string|null */
|
||||
protected $header;
|
||||
|
||||
/** @var string|null */
|
||||
protected $queryParameter;
|
||||
|
||||
/** @var callable */
|
||||
protected $onFail;
|
||||
|
||||
public function __construct(?string $header = 'X-Tenant', ?string $queryParameter = 'tenant', callable $onFail = null)
|
||||
{
|
||||
$this->header = $header;
|
||||
$this->queryParameter = $queryParameter;
|
||||
$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->initializeTenancy($request);
|
||||
} catch (TenantCouldNotBeIdentifiedException $e) {
|
||||
($this->onFail)($e);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
protected function initializeTenancy(Request $request)
|
||||
{
|
||||
if (tenancy()->initialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
$tenant = null;
|
||||
if ($this->header && $request->hasHeader($this->header)) {
|
||||
$tenant = $request->header($this->header);
|
||||
} elseif ($this->queryParameter && $request->has($this->queryParameter)) {
|
||||
$tenant = $request->get($this->queryParameter);
|
||||
}
|
||||
|
||||
if (! $tenant) {
|
||||
throw new TenantCouldNotBeIdentifiedException($request->getHost());
|
||||
}
|
||||
|
||||
tenancy()->initialize(tenancy()->find($tenant));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue