feat: implement super admin role with spatie rbac and categorize sidebar by management

This commit is contained in:
Ray1111-aa
2026-10-15 15:03:24 +07:00
parent 9c00515a73
commit 2e1f05b494
29 changed files with 5334 additions and 144 deletions
+16
View File
@@ -26,6 +26,7 @@ class UserFactory extends Factory
{
return [
'name' => fake()->name(),
'username' => fake()->unique()->userName(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
@@ -42,4 +43,19 @@ class UserFactory extends Factory
'email_verified_at' => null,
]);
}
/**
* Configure the model factory.
*/
public function configure(): static
{
return $this->afterCreating(function (User $user) {
if ($user->role && \Illuminate\Support\Facades\Schema::hasTable('roles')) {
$role = \Spatie\Permission\Models\Role::where('name', $user->role)->first();
if ($role && !$user->hasRole($user->role)) {
$user->assignRole($role);
}
}
});
}
}
@@ -0,0 +1,137 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
$teams = config('permission.teams');
$tableNames = config('permission.table_names');
$columnNames = config('permission.column_names');
$pivotRole = $columnNames['role_pivot_key'] ?? 'role_id';
$pivotPermission = $columnNames['permission_pivot_key'] ?? 'permission_id';
throw_if(empty($tableNames), 'Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.');
throw_if($teams && empty($columnNames['team_foreign_key'] ?? null), 'Error: team_foreign_key on config/permission.php not loaded. Run [php artisan config:clear] and try again.');
/**
* See `docs/prerequisites.md` for suggested lengths on 'name' and 'guard_name' if "1071 Specified key was too long" errors are encountered.
*/
Schema::create($tableNames['permissions'], static function (Blueprint $table) {
$table->id(); // permission id
$table->string('name');
$table->string('guard_name');
$table->timestamps();
$table->unique(['name', 'guard_name']);
});
/**
* See `docs/prerequisites.md` for suggested lengths on 'name' and 'guard_name' if "1071 Specified key was too long" errors are encountered.
*/
Schema::create($tableNames['roles'], static function (Blueprint $table) use ($teams, $columnNames) {
$table->id(); // role id
if ($teams || config('permission.testing')) { // permission.testing is a fix for sqlite testing
$table->unsignedBigInteger($columnNames['team_foreign_key'])->nullable();
$table->index($columnNames['team_foreign_key'], 'roles_team_foreign_key_index');
}
$table->string('name');
$table->string('guard_name');
$table->timestamps();
if ($teams || config('permission.testing')) {
$table->unique([$columnNames['team_foreign_key'], 'name', 'guard_name']);
} else {
$table->unique(['name', 'guard_name']);
}
});
Schema::create($tableNames['model_has_permissions'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotPermission, $teams) {
$table->unsignedBigInteger($pivotPermission);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->cascadeOnDelete();
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_permissions_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
} else {
$table->primary([$pivotPermission, $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
}
});
Schema::create($tableNames['model_has_roles'], static function (Blueprint $table) use ($tableNames, $columnNames, $pivotRole, $teams) {
$table->unsignedBigInteger($pivotRole);
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->cascadeOnDelete();
if ($teams) {
$table->unsignedBigInteger($columnNames['team_foreign_key']);
$table->index($columnNames['team_foreign_key'], 'model_has_roles_team_foreign_key_index');
$table->primary([$columnNames['team_foreign_key'], $pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
} else {
$table->primary([$pivotRole, $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
}
});
Schema::create($tableNames['role_has_permissions'], static function (Blueprint $table) use ($tableNames, $pivotRole, $pivotPermission) {
$table->unsignedBigInteger($pivotPermission);
$table->unsignedBigInteger($pivotRole);
$table->foreign($pivotPermission)
->references('id') // permission id
->on($tableNames['permissions'])
->cascadeOnDelete();
$table->foreign($pivotRole)
->references('id') // role id
->on($tableNames['roles'])
->cascadeOnDelete();
$table->primary([$pivotPermission, $pivotRole], 'role_has_permissions_permission_id_role_id_primary');
});
app('cache')
->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
->forget(config('permission.cache.key'));
}
/**
* Reverse the migrations.
*/
public function down(): void
{
$tableNames = config('permission.table_names');
throw_if(empty($tableNames), 'Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.');
Schema::dropIfExists($tableNames['role_has_permissions']);
Schema::dropIfExists($tableNames['model_has_roles']);
Schema::dropIfExists($tableNames['model_has_permissions']);
Schema::dropIfExists($tableNames['roles']);
Schema::dropIfExists($tableNames['permissions']);
}
};
+3
View File
@@ -267,5 +267,8 @@ class DatabaseSeeder extends Seeder
'stnk_document' => 'STNK-BH-8412-AA',
'kir_document' => 'KIR-2026/11',
]);
// 6. Seed RBAC Roles, Permissions & Super Admin
$this->call(RolePermissionSeeder::class);
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;
class RolePermissionSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
// 1. Reset cache permission Spatie
app()[PermissionRegistrar::class]->forgetCachedPermissions();
// 2. Baca seluruh daftar permission dari konfigurasi rbac_permissions
$modules = config('rbac_permissions.modules', []);
$allPermissions = [];
foreach ($modules as $moduleKey => $moduleData) {
foreach ($moduleData['permissions'] as $permKey => $permMeta) {
$allPermissions[] = $permKey;
Permission::firstOrCreate([
'name' => $permKey,
'guard_name' => 'web',
]);
}
}
// 3. Pemetaan Default Permission per Role
$rolesWithPermissions = [
'super_admin' => $allPermissions,
'hse_admin' => [
'hse.employees.view',
'hse.employees.create',
'hse.employees.edit',
],
'qma_admin' => [
'qma.vehicles.view',
'qma.vehicles.create',
'qma.vehicles.edit',
'qma.vehicles.delete',
'qma.logs.view',
'qma.summary.view',
],
'pg_admin' => [
'pg.guards.view',
'pg.guards.create',
'pg.guards.edit',
'pg.guards.toggle',
'pg.guards.delete',
'pg.logs.view',
],
'gate_officer' => [
'gate.inspect',
'gate.approve',
'gate.reject',
],
];
foreach ($rolesWithPermissions as $roleName => $perms) {
$role = Role::firstOrCreate(['name' => $roleName, 'guard_name' => 'web']);
$role->syncPermissions($perms);
}
// 4. Buat Akun Default Super Admin
$superAdmin = User::firstOrCreate(
['username' => 'superadmin'],
[
'name' => 'Super Administrator',
'email' => '[email protected]',
'password' => Hash::make('password'),
'role' => 'super_admin',
]
);
if (!$superAdmin->hasRole('super_admin')) {
$superAdmin->assignRole('super_admin');
}
// 5. Sinkronisasi Akun Existing ke Spatie Roles
$existingUsers = User::all();
foreach ($existingUsers as $user) {
if ($user->role && in_array($user->role, array_keys($rolesWithPermissions))) {
if (!$user->hasRole($user->role)) {
$user->assignRole($user->role);
}
}
}
}
}