feat: hide settings button in table header for unauthorized users
This commit is contained in:
@@ -21,7 +21,8 @@ class ListShortUrls extends ManageRecords
|
||||
->icon('heroicon-o-adjustments-horizontal')
|
||||
->color('gray')
|
||||
->size('sm')
|
||||
->url(static::getResource()::getUrl('settings')),
|
||||
->url(static::getResource()::getUrl('settings'))
|
||||
->visible(fn () => ShortUrlSettingsPage::canAccess()),
|
||||
|
||||
CreateAction::make()
|
||||
->icon('heroicon-o-plus')
|
||||
|
||||
@@ -33,6 +33,28 @@ class ShortUrlSettingsPage extends Page implements HasForms
|
||||
|
||||
protected string $view = 'filament-short-url::settings';
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
try {
|
||||
$plugin = \Bjanczak\FilamentShortUrl\FilamentShortUrlPlugin::get();
|
||||
|
||||
if ($callback = $plugin->getAuthorizeSettingsUsing()) {
|
||||
return (bool) app()->call($callback);
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
// Ignore if plugin is not registered yet in some contexts
|
||||
}
|
||||
|
||||
// Fallback: Check if there's a Model Policy with `manageSettings` method
|
||||
if (\Illuminate\Support\Facades\Gate::getPolicyFor(\Bjanczak\FilamentShortUrl\Models\ShortUrl::class) &&
|
||||
method_exists(\Illuminate\Support\Facades\Gate::getPolicyFor(\Bjanczak\FilamentShortUrl\Models\ShortUrl::class), 'manageSettings')) {
|
||||
return \Illuminate\Support\Facades\Gate::allows('manageSettings', \Bjanczak\FilamentShortUrl\Models\ShortUrl::class);
|
||||
}
|
||||
|
||||
// Default fallback: Check if the user is authorized to view the resource in general
|
||||
return static::getResource()::canViewAny();
|
||||
}
|
||||
|
||||
public ?array $data = [];
|
||||
|
||||
public function mount(): void
|
||||
|
||||
@@ -18,6 +18,8 @@ class FilamentShortUrlPlugin implements Plugin
|
||||
|
||||
protected ?string $routePrefix = null;
|
||||
|
||||
protected ?\Closure $authorizeSettingsUsing = null;
|
||||
|
||||
// ─── Factory ─────────────────────────────────────────────────────────────
|
||||
|
||||
public static function make(): static
|
||||
@@ -119,4 +121,21 @@ class FilamentShortUrlPlugin implements Plugin
|
||||
{
|
||||
return $this->navigationIcon;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a custom callback to authorize access to the Short URL settings page.
|
||||
*
|
||||
* @example FilamentShortUrlPlugin::make()->authorizeSettingsUsing(fn () => auth()->user()->hasRole('admin'))
|
||||
*/
|
||||
public function authorizeSettingsUsing(\Closure $callback): static
|
||||
{
|
||||
$this->authorizeSettingsUsing = $callback;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getAuthorizeSettingsUsing(): ?\Closure
|
||||
{
|
||||
return $this->authorizeSettingsUsing;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user