feat(permissions): admin role/permission matrix + Gate::before super-admin

Phase 1 (additive, doesn't touch existing checks):
- Gate::before grants everything to holders of 'manage all' (the Admin role),
  robustly (returns true/null, never false; swallows missing-permission).
- New RolePermissionManager Livewire component + view at /admin/permissions:
  editable Roles x Permissions matrix (toggle saves instantly), create/delete
  roles, create/delete permissions. Admin role and 'manage all' are protected.
- Link to the screen from /admin/users header.
Roles are editable from the UI as chosen.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-17 16:39:28 +02:00
parent da0c8bd134
commit 828e70fbe2
5 changed files with 218 additions and 5 deletions
+110
View File
@@ -0,0 +1,110 @@
<?php
namespace App\Livewire;
use Livewire\Component;
use Livewire\Attributes\Layout;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\PermissionRegistrar;
#[Layout('layouts.app')]
class RolePermissionManager extends Component
{
public string $newRole = '';
public string $newPermission = '';
/** Roles that must not be deleted or stripped of core powers. */
private const PROTECTED_ROLES = ['Admin'];
private const CORE_PERMISSION = 'manage all';
public function mount(): void
{
abort_unless(Auth::user()?->can(self::CORE_PERMISSION), 403);
}
private function flushCache(): void
{
app(PermissionRegistrar::class)->forgetCachedPermissions();
}
public function togglePermission(int $roleId, string $permissionName): void
{
$role = Role::findOrFail($roleId);
if ($role->hasPermissionTo($permissionName)) {
// Admin must always keep the core permission
if ($role->name === 'Admin' && $permissionName === self::CORE_PERMISSION) {
$this->dispatch('notify', "El rol Admin no puede perder '" . self::CORE_PERMISSION . "'.");
return;
}
$role->revokePermissionTo($permissionName);
} else {
$role->givePermissionTo($permissionName);
}
$this->flushCache();
$this->dispatch('notify', 'Permisos actualizados');
}
public function addRole(): void
{
$this->validate([
'newRole' => 'required|string|max:50|unique:roles,name',
], [], ['newRole' => 'nombre de rol']);
Role::create(['name' => trim($this->newRole)]);
$this->newRole = '';
$this->flushCache();
$this->dispatch('notify', 'Rol creado');
}
public function deleteRole(int $roleId): void
{
$role = Role::findOrFail($roleId);
if (in_array($role->name, self::PROTECTED_ROLES, true)) {
$this->dispatch('notify', "El rol '{$role->name}' está protegido y no se puede borrar.");
return;
}
$role->delete();
$this->flushCache();
$this->dispatch('notify', 'Rol eliminado');
}
public function addPermission(): void
{
$this->validate([
'newPermission' => 'required|string|max:50|unique:permissions,name',
], [], ['newPermission' => 'nombre de permiso']);
Permission::create(['name' => trim($this->newPermission)]);
$this->newPermission = '';
$this->flushCache();
$this->dispatch('notify', 'Permiso creado');
}
public function deletePermission(int $permissionId): void
{
$permission = Permission::findOrFail($permissionId);
if ($permission->name === self::CORE_PERMISSION) {
$this->dispatch('notify', "El permiso '" . self::CORE_PERMISSION . "' está protegido y no se puede borrar.");
return;
}
$permission->delete();
$this->flushCache();
$this->dispatch('notify', 'Permiso eliminado');
}
public function render()
{
return view('livewire.role-permission-manager', [
'roles' => Role::with('permissions')->orderBy('name')->get(),
'permissions' => Permission::orderBy('name')->get(),
]);
}
}
+11 -1
View File
@@ -3,6 +3,7 @@
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Gate;
class AppServiceProvider extends ServiceProvider
{
@@ -19,6 +20,15 @@ class AppServiceProvider extends ServiceProvider
*/
public function boot(): void
{
//
// Super-admin bypass: anyone with the "manage all" permission
// (the Admin role has it) passes every authorization check.
// Return true to allow, or null to let normal checks run — never false.
Gate::before(function ($user, $ability) {
try {
return $user->hasPermissionTo('manage all') ? true : null;
} catch (\Throwable $e) {
return null;
}
});
}
}
+9 -4
View File
@@ -5,10 +5,15 @@
{{ __('Users') }}
</h2>
<a href="{{ route('admin.users.create') }}" class="btn btn-primary btn-sm gap-1" wire:navigate>
<x-heroicon-o-plus class="w-4 h-4" /> {{ __('New user') }}
</a>
<div class="flex items-center gap-2">
<a href="{{ route('admin.permissions') }}" class="btn btn-outline btn-sm gap-1" wire:navigate>
<x-heroicon-o-shield-check class="w-4 h-4" /> {{ __('Permissions') }}
</a>
<a href="{{ route('admin.users.create') }}" class="btn btn-primary btn-sm gap-1" wire:navigate>
<x-heroicon-o-plus class="w-4 h-4" /> {{ __('New user') }}
</a>
</div>
</div>
</x-slot>
@@ -0,0 +1,87 @@
<div class="py-8 max-w-6xl mx-auto sm:px-6 lg:px-8">
<div class="mb-6">
<h2 class="text-2xl font-bold text-gray-800">{{ __('Permission management') }}</h2>
<p class="text-sm text-gray-500 mt-1">{{ __('Tick which permissions each role has. Changes are saved instantly.') }}</p>
</div>
{{-- Crear rol / permiso --}}
<div class="flex flex-wrap items-start gap-6 mb-6">
<form wire:submit.prevent="addRole" class="flex flex-col gap-1">
<div class="flex gap-2">
<input wire:model="newRole" class="input input-bordered input-sm w-48" placeholder="{{ __('New role') }}" />
<button class="btn btn-sm btn-primary gap-1">
<x-heroicon-o-plus class="w-4 h-4" /> {{ __('Role') }}
</button>
</div>
@error('newRole') <span class="text-error text-xs">{{ $message }}</span> @enderror
</form>
<form wire:submit.prevent="addPermission" class="flex flex-col gap-1">
<div class="flex gap-2">
<input wire:model="newPermission" class="input input-bordered input-sm w-48" placeholder="{{ __('New permission') }}" />
<button class="btn btn-sm btn-outline gap-1">
<x-heroicon-o-plus class="w-4 h-4" /> {{ __('Permission') }}
</button>
</div>
@error('newPermission') <span class="text-error text-xs">{{ $message }}</span> @enderror
</form>
</div>
{{-- Matriz Roles × Permisos --}}
<div class="overflow-x-auto border border-base-300 rounded-lg bg-white">
<table class="table table-sm">
<thead>
<tr>
<th class="bg-base-200">{{ __('Permission') }}</th>
@foreach($roles as $role)
<th class="bg-base-200 text-center align-bottom">
<div class="flex flex-col items-center gap-1">
<span class="font-semibold">{{ $role->name }}</span>
@unless(in_array($role->name, ['Admin'], true))
<button wire:click="deleteRole({{ $role->id }})"
wire:confirm="{{ __('Delete role') }} '{{ $role->name }}'?"
class="btn btn-ghost btn-xs text-error" title="{{ __('Delete role') }}">
<x-heroicon-o-trash class="w-3.5 h-3.5" />
</button>
@endunless
</div>
</th>
@endforeach
</tr>
</thead>
<tbody>
@forelse($permissions as $perm)
<tr wire:key="perm-row-{{ $perm->id }}" class="hover">
<td class="font-medium whitespace-nowrap">
<div class="flex items-center gap-2">
<span>{{ $perm->name }}</span>
@if($perm->name !== 'manage all')
<button wire:click="deletePermission({{ $perm->id }})"
wire:confirm="{{ __('Delete permission') }} '{{ $perm->name }}'?"
class="btn btn-ghost btn-xs text-error opacity-40 hover:opacity-100" title="{{ __('Delete permission') }}">
<x-heroicon-o-trash class="w-3.5 h-3.5" />
</button>
@endif
</div>
</td>
@foreach($roles as $role)
<td class="text-center" wire:key="cell-{{ $perm->id }}-{{ $role->id }}">
<input type="checkbox"
class="checkbox checkbox-sm checkbox-primary"
@checked($role->permissions->contains('id', $perm->id))
wire:click="togglePermission({{ $role->id }}, '{{ $perm->name }}')" />
</td>
@endforeach
</tr>
@empty
<tr><td colspan="{{ $roles->count() + 1 }}" class="text-center text-gray-400 py-6">{{ __('No permissions') }}</td></tr>
@endforelse
</tbody>
</table>
</div>
<p class="text-xs text-gray-400 mt-3">
{{ __('The Admin role and the "manage all" permission are protected and cannot be removed.') }}
</p>
</div>
+1
View File
@@ -136,6 +136,7 @@ Route::get('/reports/dashboard', ReportsDashboard::class)->name('reports.dashboa
Route::get('/users/create', \App\Livewire\UserForm::class)->name('users.create');
Route::get('/users/{user}', \App\Livewire\UserView::class)->name('users.show');
Route::get('/users/{user}/edit', \App\Livewire\UserForm::class)->name('users.edit');
Route::get('/permissions', \App\Livewire\RolePermissionManager::class)->name('permissions');
});
// Gestor de medios