mostafamaklad / laravel-permission-mongodb

Associate users with roles and permissions using Laravel and MongoDB
https://maklad.dev
MIT License
112 stars 66 forks source link

Integration with spatie/multi-tenancy #138

Open scotchdesign opened 2 years ago

scotchdesign commented 2 years ago

To integrate with spatie/multi-tenancy you need to reset the permission cache when the current tenant is changed. It would have been easier to add a suffix to the $cacheKey variable, however it's protected so doesn't seem to be able to be modified. Below is my work-around.

app/config/multitenancy.php

'switch_tenant_tasks' => [
        ...
        \App\Tasks\SwitchTenantPermissionCacheTask::class,
       ...
    ],

App\Tasks\SwitchTenantPermissionCacheTask.php

<?php

namespace App\Tasks;

use Spatie\Multitenancy\Models\Tenant;
use Spatie\Multitenancy\Tasks\SwitchTenantTask;

class SwitchTenantPermissionCacheTask implements SwitchTenantTask {

    public function __construct() {

        app(\Maklad\Permission\PermissionRegistrar::class)->forgetCachedPermissions();
        app(\Maklad\Permission\PermissionRegistrar::class)->registerPermissions();
    }

    public function makeCurrent(Tenant $tenant): void {

        app(\Maklad\Permission\PermissionRegistrar::class)->forgetCachedPermissions();
        app(\Maklad\Permission\PermissionRegistrar::class)->registerPermissions();
    }

    public function forgetCurrent(): void {

        app(\Maklad\Permission\PermissionRegistrar::class)->forgetCachedPermissions();
        app(\Maklad\Permission\PermissionRegistrar::class)->registerPermissions();
    }
}