Skip to content

Commit

Permalink
Merge pull request #232 from bezhanSalleh/fix/cleanup
Browse files Browse the repository at this point in the history
cleanup wip
  • Loading branch information
bezhanSalleh authored Sep 16, 2023
2 parents 9bab99b + 981fa41 commit 42a1b43
Show file tree
Hide file tree
Showing 10 changed files with 32 additions and 85 deletions.
19 changes: 9 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,6 @@ The easiest and most intuitive way to add access management to your Filament Adm
- :fire: **Widgets**
- :fire: **Custom Permissions**

> **Warning**
> The 3.x is still in beta but compatible for filament 3.x

> **Note**
> For **Filament 2.x** use **[2.x](https://github.com/bezhanSalleh/filament-shield/tree/2.x)** branch
Expand All @@ -44,7 +42,7 @@ The easiest and most intuitive way to add access management to your Filament Adm
1. Install the package via composer:

```bash
composer require bezhansalleh/filament-shield "^3.0@beta"
composer require bezhansalleh/filament-shield
```

2. Add the `Spatie\Permission\Traits\HasRoles` trait to your User model(s):
Expand All @@ -55,7 +53,7 @@ use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
use HasRoles; //or HasFilamentShield
use HasRoles;

// ...
}
Expand All @@ -64,7 +62,7 @@ class User extends Authenticatable
```bash
php artisan vendor:publish --tag=filament-shield-config
```
4. Register the plugin for the Filament Panel
4. Register the plugin for the Filament Panels you want
```php
public function panel(Panel $panel): Panel
{
Expand All @@ -81,7 +79,7 @@ php artisan shield:install
Follow the prompts and enjoy!

## Filament Panels
If you want to enable `Shield` for more than one panel then you need to register the plugin for each panel.
If you want to enable `Shield` for more than one panel then you need to register the plugin for each panel as mentioned above.

#### Resources
Generally there are two scenarios that shield handles permissions for your `Filament` resources.
Expand Down Expand Up @@ -315,7 +313,7 @@ class IncomeWidget extends LineChartWidget

#### Role Policy

You can skip this if have set the `'register_role_policy' => true` in the config.
You can skip this if have set the `enabled => true` in the config.
To ensure `RoleResource` access via `RolePolicy` you would need to add the following to your `AuthServiceProvider`:

```php
Expand All @@ -327,21 +325,21 @@ protected $policies = [
...
```

#### Third-Party Plugins
#### Custom folder structure for Models or Third-Party Plugins

Shield also generates policies and permissions for third-party plugins and to enforce the generated policies you will need to register them in your application's `AuthServiceProvider`:
Shield also generates policies and permissions for third-party plugins and `Models` with custom folder structure and to enforce the generated policies you will need to register them in your application's `AuthServiceProvider`:
```
...
class AuthServiceProvider extends ServiceProvider
{
...
protected $policies = [
...,
'App\Models\Blog\Author' => 'App\Policies\Blog\AuthorPolicy',
'Ramnzys\FilamentEmailLog\Models\Email' => 'App\Policies\EmailPolicy'
];
```
Same applies for models inside folders.

#### Translations

Expand Down Expand Up @@ -370,6 +368,7 @@ Generate Permissions and/or Policies for Filament entities. Accepts the followin
- `--widget[=WIDGET]` One or many widgets separated by comma (,)
- `--exclude` Exclude the given entities during generation
- `--ignore-config-exclude` Ignore config `exclude` option during generation
- `--ignore-existing-policies` Do not overwrite the existing policies.

#### `shield:super-admin`
Create a user with super_admin role.
Expand Down
5 changes: 0 additions & 5 deletions config/filament-shield.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,6 @@
'intercept_gate' => 'before', // after
],

'filament_user' => [
'enabled' => true,
'name' => 'filament_user',
],

'permission_prefixes' => [
'resource' => [
'view',
Expand Down
3 changes: 1 addition & 2 deletions src/Commands/MakeShieldDoctorCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,7 @@ public function handle(): int
protected static function authProviderConfigured()
{
if (class_exists(Utils::getAuthProviderFQCN())) {
return in_array("BezhanSalleh\FilamentShield\Traits\HasFilamentShield", class_uses(Utils::getAuthProviderFQCN()))
|| in_array("Spatie\Permission\Traits\HasRoles", class_uses(Utils::getAuthProviderFQCN()))
return Utils::isAuthProviderConfigured()
? '<fg=green;options=bold>CONFIGURED</>'
: '<fg=red;options=bold>NOT CONFIGURED</>';
}
Expand Down
2 changes: 2 additions & 0 deletions src/Commands/MakeShieldGenerateCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ protected function generateForResources(array $resources): Collection
->each(function ($entity) {
if ($this->generatorOption === 'policies_and_permissions') {
$policyPath = $this->generatePolicyPath($entity);
/** @phpstan-ignore-next-line */
if (! $this->option('ignore-existing-policies') || ($this->option('ignore-existing-policies') && ! $this->fileExists($policyPath))) {
$this->copyStubToApp(static::getPolicyStub($entity['model']), $policyPath, $this->generatePolicyStubVariables($entity));
}
Expand All @@ -201,6 +202,7 @@ protected function generateForResources(array $resources): Collection

if ($this->generatorOption === 'policies') {
$policyPath = $this->generatePolicyPath($entity);
/** @phpstan-ignore-next-line */
if (! $this->option('ignore-existing-policies') || ($this->option('ignore-existing-policies') && ! $this->fileExists($policyPath))) {
$this->copyStubToApp(static::getPolicyStub($entity['model']), $policyPath, $this->generatePolicyStubVariables($entity));
}
Expand Down
10 changes: 1 addition & 9 deletions src/Commands/MakeShieldSuperAdminCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class MakeShieldSuperAdminCommand extends Command
public $signature = 'shield:super-admin
{--user= : ID of user to be made super admin.}
{--panel= : Panel ID to get the configuration from.}
';
';

public $description = 'Creates Filament Super Admin';

Expand All @@ -38,10 +38,6 @@ public function handle(): int
FilamentShield::createRole();
}

if (Utils::isFilamentUserRoleEnabled() && Utils::getRoleModel()::whereName(Utils::getFilamentUserRoleName())->doesntExist()) {
FilamentShield::createRole(isSuperAdmin: false);
}

if ($this->option('user')) {
$this->superAdmin = $userProvider->getModel()::findOrFail($this->option('user'));
} elseif ($userProvider->getModel()::count() === 1) {
Expand Down Expand Up @@ -71,10 +67,6 @@ public function handle(): int
}
$this->superAdmin->assignRole(Utils::getSuperAdminName());

if (Utils::isFilamentUserRoleEnabled()) {
$this->superAdmin->assignRole(Utils::getFilamentUserRoleName());
}

$loginUrl = Filament::getCurrentPanel()?->getLoginUrl();

$this->info("Success! {$this->superAdmin->email} may now log in at {$loginUrl}.");
Expand Down
15 changes: 6 additions & 9 deletions src/FilamentShield.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,11 @@ protected static function giveSuperAdminPermission(string | array | Collection $
}
}

public static function createRole(bool $isSuperAdmin = true)
public static function createRole()
{
return Utils::getRoleModel()::firstOrCreate(
['name' => $isSuperAdmin ? Utils::getSuperAdminName() : Utils::getFilamentUserRoleName()],
['guard_name' => $isSuperAdmin ? Utils::getFilamentAuthGuard() : Utils::getFilamentAuthGuard()]
['name' => Utils::getSuperAdminName()],
['guard_name' => Utils::getFilamentAuthGuard()]
);
}

Expand Down Expand Up @@ -316,13 +316,10 @@ protected static function transformClassString(string $string, bool $isPageClass
$widgets = array_unique($widgets);
}

$prefix = Str::of($isPageClass ? Utils::getPagePermissionPrefix() : Utils::getWidgetPermissionPrefix())->append('_');

return (string) collect($isPageClass ? $pages : $widgets)
->first(fn ($item) => Str::endsWith(
$item,
Str::of($string)
->after('_')
->studly()
));
->first(fn ($item) => class_basename($item) == Str::of($string)->after($prefix)->studly());
}

protected static function hasHeadingForShield(object | string $class): bool
Expand Down
16 changes: 5 additions & 11 deletions src/Resources/RoleResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,7 @@ public static function form(Form $form): Form
->tabs([
Forms\Components\Tabs\Tab::make(__('filament-shield::filament-shield.resources'))
->visible(fn (): bool => (bool) Utils::isResourceEntityEnabled())
// ->live()
->badge(static::getResourceTabBadge())
->badge(static::getResourceTabBadgeCount())
->schema([
Forms\Components\Grid::make()
->schema(static::getResourceEntitiesSchema())
Expand All @@ -86,6 +85,7 @@ public static function form(Form $form): Form
]),
Forms\Components\Tabs\Tab::make(__('filament-shield::filament-shield.pages'))
->visible(fn (): bool => (bool) Utils::isPageEntityEnabled() && (count(FilamentShield::getPages()) > 0 ? true : false))
->badge(count(static::getPageOptions()))
->schema([
Forms\Components\CheckboxList::make('pages_tab')
->label('')
Expand Down Expand Up @@ -126,7 +126,7 @@ public static function form(Form $form): Form
]),
Forms\Components\Tabs\Tab::make(__('filament-shield::filament-shield.widgets'))
->visible(fn (): bool => (bool) Utils::isWidgetEntityEnabled() && (count(FilamentShield::getWidgets()) > 0 ? true : false))
->live()
->badge(count(static::getWidgetOptions()))
->schema([
Forms\Components\CheckboxList::make('widgets_tab')
->label('')
Expand Down Expand Up @@ -166,10 +166,9 @@ public static function form(Form $form): Form
])
->columnSpanFull(),
]),

Forms\Components\Tabs\Tab::make(__('filament-shield::filament-shield.custom'))
->visible(fn (): bool => (bool) Utils::isCustomPermissionEntityEnabled() && (count(static::getCustomEntities()) > 0 ? true : false))
->live()
->badge(count(static::getCustomPermissionOptions()))
->schema([
Forms\Components\CheckboxList::make('custom_permissions')
->label('')
Expand Down Expand Up @@ -323,10 +322,6 @@ public static function canGloballySearch(): bool
return Utils::isResourceGloballySearchable() && count(static::getGloballySearchableAttributes()) && static::canViewAny();
}

/**--------------------------------*
| Resource Related Logic Start |
*----------------------------------*/

public static function getResourceEntitiesSchema(): ?array
{
if (blank(static::$permissionsCollection)) {
Expand All @@ -342,7 +337,6 @@ public static function getResourceEntitiesSchema(): ?array
->schema([
Forms\Components\CheckboxList::make($entity['resource'])
->label('')
// ->hint(Utils::showModelPath($entity['fqcn']))
->options(fn (): array => static::getResourcePermissionOptions($entity))
->live()
->afterStateHydrated(function (Component $component, $livewire, string $operation, ?Model $record, Forms\Set $set) use ($entity) {
Expand Down Expand Up @@ -384,7 +378,7 @@ public static function getResourceEntitiesSchema(): ?array
?->toArray() ?? [];
}

public static function getResourceTabBadge(): ?int
public static function getResourceTabBadgeCount(): ?int
{
return collect(FilamentShield::getResources())
->map(fn ($resource) => count(static::getResourcePermissionOptions($resource)))
Expand Down
13 changes: 1 addition & 12 deletions src/Support/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,7 @@ public static function getAuthProviderFQCN()

public static function isAuthProviderConfigured(): bool
{
return in_array("BezhanSalleh\FilamentShield\Traits\HasFilamentShield", class_uses(static::getAuthProviderFQCN()))
|| in_array("Spatie\Permission\Traits\HasRoles", class_uses(static::getAuthProviderFQCN()));
return in_array("Spatie\Permission\Traits\HasRoles", class_uses(static::getAuthProviderFQCN()));
}

public static function isSuperAdminEnabled(): bool
Expand All @@ -84,16 +83,6 @@ public static function getSuperAdminGateInterceptionStatus(): string
return (string) config('filament-shield.super_admin.intercept_gate');
}

public static function isFilamentUserRoleEnabled(): bool
{
return (bool) config('filament-shield.filament_user.enabled', true);
}

public static function getFilamentUserRoleName(): string
{
return (string) config('filament-shield.filament_user.name');
}

public static function getGeneralResourcePermissionPrefixes(): array
{
return config('filament-shield.permission_prefixes.resource');
Expand Down
25 changes: 0 additions & 25 deletions src/Traits/HasFilamentShield.php

This file was deleted.

9 changes: 7 additions & 2 deletions src/Traits/HasPageShield.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use BezhanSalleh\FilamentShield\Support\Utils;
use Filament\Facades\Filament;
use Filament\Notifications\Notification;
use Illuminate\Support\Str;

trait HasPageShield
Expand All @@ -13,7 +14,11 @@ public function booted(): void
$this->beforeBooted();

if (! static::canView()) {
$this->notify('warning', __('filament-shield::filament-shield.forbidden'));

Notification::make()
->title(__('filament-shield::filament-shield.forbidden'))
->warning()
->send();

$this->beforeShieldRedirects();

Expand Down Expand Up @@ -43,7 +48,7 @@ protected function beforeShieldRedirects(): void

protected function getShieldRedirectPath(): string
{
return config('filament.path');
return Filament::getUrl();
}

public static function canView(): bool
Expand Down

0 comments on commit 42a1b43

Please sign in to comment.