Hello @m7vm7v Thank you for the reply but the problem Is not Switching tenants the issue is filamentphp that I am using sending an ajax request before setting the cookie which is used to identify tenant.
<?php
namespace App\Filament\Pages\Auth;
use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
use Filament\Facades\Filament;
use Filament\Http\Responses\Auth\LoginResponse;
use Filament\Models\Contracts\FilamentUser;
use Illuminate\Support\Facades\Cookie;
class CustomAuth extends \Filament\Pages\Auth\Login
{
public function authenticate(): ?LoginResponse
{
try {
$this->rateLimit(5);
} catch (TooManyRequestsException $exception) {
$this->getRateLimitedNotification($exception)?->send();
return null;
}
$data = $this->form->getState();
if (! Filament::auth()->attempt($this->getCredentialsFromFormData($data), $data['remember'] ?? false)) {
$this->throwFailureValidationException();
}
$user = Filament::auth()->user();
if (
($user instanceof FilamentUser) &&
(! $user->canAccessPanel(Filament::getCurrentPanel()))
) {
Filament::auth()->logout();
$this->throwFailureValidationException();
}
session()->regenerate();
//this is where we will set the tenant cookie
Cookie::forget('tenant');
Cookie::queue(Cookie::forever('tenant', encrypt($user->tenant_id)));
return app(LoginResponse::class);
}
}
The class above extents filament Auth class and I override the method to dent the cookie once the user is logged in.
<?php
namespace App;
use App\Models\Tenant;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Log;
use Spatie\Multitenancy\Contracts\IsTenant;
use Spatie\Multitenancy\TenantFinder\TenantFinder;
class OlinTenantFinder extends TenantFinder
{
public function findForRequest($request): ? IsTenant
{
if($request->hasCookie('tenant')) {
try{
$tenantId = decrypt($request->cookie('tenant'));
$tenant = Tenant::where('tenant_id', $tenantId)->first();
if(!empty($tenant)) {
$tenant->makeCurrent();
//set the default connection to tenant
config(['database.default' => 'tenant']);
return $tenant;
}
return null;
}
catch(\Exception $e) {
Log::info($e->getMessage());
//kill all the session and cookies
// $request->session()->invalidate();
// $request->session()->regenerateToken();
Cookie::forget('tenant');
return null;
}
}
// return null;
}
}
This class is custom also it extends the spatie tenant fimder as per the docs. Now my issue is the request is supposed to run for authenticated users where the cookie will already be set. but it runs when filamentmakes an ajax request and as per the documentation the middleware is supposed to be on authGuardMidlleware.
use Filament\Panel;
public function panel(Panel $panel): Panel
{
return $panel
// ...
->authMiddleware([
// ...
]);
}