tenancy icon indicating copy to clipboard operation
tenancy copied to clipboard

Add cookie option on Initialize Tenancy by Request identification

Open amjeed-ay opened this issue 3 years ago • 0 comments

Description

Add Tenant Identification by Request Cookie Identification on InitializeTenancyByRequestData middleware payload which can work the same as Request Header Identification.

Why this should be added

When using InitializeTenancyByRequestData In a SPA front-end we need to set a header on every request that will be send to our backend or set query params with tenant id. So in this approach When a user login will receive X-Tenant cookie with value tenant id from Authentication Controller which will be use on the next requests to identify tenant.

I tested it on my project and it works:

How it works

on Authentication controller $response->withCookie(cookie('X-Tenant', $tenant, 120));

in InitializeTenancyByRequestData middleware from stancl\tenancy\src\Middleware\InitializeTenancyByRequestData.php

we add another condition to check if request cookie exist with key X-Tenant then we use the value

 protected function getPayload(Request $request): ?string
    {
        $tenant = null;
        if (static::$header && $request->hasHeader(static::$header)) {
            $tenant = $request->header(static::$header);
        } elseif (static::$queryParameter && $request->has(static::$queryParameter)) {
            $tenant = $request->get(static::$queryParameter);
        } 

         // add below condition ...........
        elseif (static::$header && $request->hasCookie(static::$header)) {   // check if request has cookie with key X-Tenant
            $tenant = $request->cookie(static::$header);    
        }      

        return $tenant;
    }

``

amjeed-ay avatar Jul 13 '22 15:07 amjeed-ay