diff --git a/app/Enums/RoleEnum.php b/app/Enums/RoleEnum.php new file mode 100644 index 0000000..0b694e3 --- /dev/null +++ b/app/Enums/RoleEnum.php @@ -0,0 +1,21 @@ + 'Developer', + self::Student => 'Mahasiswa', + self::Kosma => 'Kosma', + }; + } +} diff --git a/app/Models/User.php b/app/Models/User.php index 4fe23a5..e74bc49 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -14,11 +14,12 @@ use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Saade\FilamentFacehash\Concerns\HasFacehashAvatar; +use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable implements FilamentUser { /** @use HasFactory<\Database\Factories\UserFactory> */ - use HasFacehashAvatar, HasFactory, Notifiable, SoftDeletes; + use HasFacehashAvatar, HasFactory, HasRoles, Notifiable, SoftDeletes; protected $guarded = ['id']; diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php index d83d45f..cd9bc1e 100644 --- a/app/Providers/Filament/AdminPanelProvider.php +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -5,6 +5,7 @@ use AchyutN\FilamentLogViewer\FilamentLogViewer; use App\Filament\Pages\Auth\Login; use App\Filament\Pages\Profile; +use BezhanSalleh\FilamentShield\FilamentShieldPlugin; use DiogoGPinto\AuthUIEnhancer\AuthUIEnhancerPlugin; use Filament\Http\Middleware\Authenticate; use Filament\Http\Middleware\AuthenticateSession; @@ -68,6 +69,7 @@ public function panel(Panel $panel): Panel Authenticate::class, ]) ->plugins([ + FilamentShieldPlugin::make(), AuthUIEnhancerPlugin::make() ->formPanelPosition('left') ->formPanelWidth('40%') @@ -90,7 +92,8 @@ public function panel(Panel $panel): Panel ->navigationIcon('heroicon-o-server-stack') ->navigationLabel('Log') ->navigationUrl('/system/logs') - ->pollingTime(null), + ->pollingTime(null) + ->authorize(fn () => auth()->user()->can('View:LogTable')), MobileBottomNav::make() ->items([ diff --git a/composer.json b/composer.json index 95f5ab2..cac9749 100644 --- a/composer.json +++ b/composer.json @@ -9,6 +9,7 @@ "php": "^8.2", "achyutn/filament-log-viewer": "^2.1", "asmit/filament-upload": "^2.0", + "bezhansalleh/filament-shield": "^4.1", "diogogpinto/filament-auth-ui-enhancer": "^2.0", "filament/filament": "^5.0", "filament/spatie-laravel-media-library-plugin": "^5.0", diff --git a/composer.lock b/composer.lock index 41bfa62..0583545 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "a1dbb9834deb9867961bae477b5e320b", + "content-hash": "54a273217804c6144459670e87c93850", "packages": [ { "name": "achyutn/filament-log-viewer", @@ -205,6 +205,179 @@ }, "time": "2026-01-17T06:36:31+00:00" }, + { + "name": "bezhansalleh/filament-plugin-essentials", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/bezhanSalleh/filament-plugin-essentials.git", + "reference": "3bfdb276a8993ccd5acd9d6b43fd4763cf221d3a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/bezhanSalleh/filament-plugin-essentials/zipball/3bfdb276a8993ccd5acd9d6b43fd4763cf221d3a", + "reference": "3bfdb276a8993ccd5acd9d6b43fd4763cf221d3a", + "shasum": "" + }, + "require": { + "filament/filament": "^4.0|^5.0", + "illuminate/contracts": "^11.28|^12.0", + "php": "^8.2", + "spatie/laravel-package-tools": "^1.9" + }, + "require-dev": { + "larastan/larastan": "^2.9||^3.0", + "laravel/pint": "^1.14", + "nunomaduro/collision": "^8.1.1||^7.10.0", + "orchestra/testbench": "^10.0.0||^9.0.0", + "pestphp/pest": "^3.0", + "pestphp/pest-plugin-arch": "^3.0", + "pestphp/pest-plugin-laravel": "^3.0", + "pestphp/pest-plugin-type-coverage": "^3.5", + "phpstan/extension-installer": "^1.3||^2.0", + "phpstan/phpstan-deprecation-rules": "^1.1||^2.0", + "phpstan/phpstan-phpunit": "^1.3||^2.0", + "rector/rector": "^2.1", + "spatie/laravel-ray": "^1.40" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "BezhanSalleh\\PluginEssentials\\PluginEssentialsServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "BezhanSalleh\\PluginEssentials\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Bezhan Salleh", + "email": "bezhan_salleh@yahoo.com", + "role": "Developer" + } + ], + "description": "A collection of essential traits that streamline Filament plugin development by taking care of the boilerplate, so you can focus on shipping real features faster", + "homepage": "https://github.com/bezhansalleh/filament-plugin-essentials", + "keywords": [ + "Bezhan Salleh", + "filament-plugin-essentials", + "laravel" + ], + "support": { + "issues": "https://github.com/bezhanSalleh/filament-plugin-essentials/issues", + "source": "https://github.com/bezhanSalleh/filament-plugin-essentials/tree/1.1.0" + }, + "funding": [ + { + "url": "https://github.com/bezhanSalleh", + "type": "github" + } + ], + "time": "2026-01-19T19:23:25+00:00" + }, + { + "name": "bezhansalleh/filament-shield", + "version": "4.1.0", + "source": { + "type": "git", + "url": "https://github.com/bezhanSalleh/filament-shield.git", + "reference": "bb5ac95b3c10f801e4c54bb289be8c055968726a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/bezhanSalleh/filament-shield/zipball/bb5ac95b3c10f801e4c54bb289be8c055968726a", + "reference": "bb5ac95b3c10f801e4c54bb289be8c055968726a", + "shasum": "" + }, + "require": { + "bezhansalleh/filament-plugin-essentials": "^1.0", + "filament/filament": "^4.0|^5.0", + "illuminate/contracts": "^11.28|^12.0", + "illuminate/support": "^11.28|^12.0", + "php": "^8.2", + "spatie/laravel-package-tools": "^1.92", + "spatie/laravel-permission": "^6.0" + }, + "require-dev": { + "larastan/larastan": "^3.8", + "laravel/pint": "^1.26", + "nunomaduro/collision": "^8.8", + "orchestra/testbench": "^10.8", + "pestphp/pest": "^3.8|^4.0", + "pestphp/pest-plugin-laravel": "^3.2|^4.0", + "pestphp/pest-plugin-livewire": "^3.0|^4.0", + "pestphp/pest-plugin-type-coverage": "^3.6|^4.0", + "phpstan/extension-installer": "^1.4", + "phpstan/phpstan": "^2.1", + "phpstan/phpstan-deprecation-rules": "^2.0", + "phpstan/phpstan-phpunit": "^2.0", + "phpunit/phpunit": "^11.5", + "rector/jack": "^0.4.0", + "rector/rector": "^2.2", + "spatie/laravel-ray": "^1.43" + }, + "type": "library", + "extra": { + "laravel": { + "aliases": { + "FilamentShield": "BezhanSalleh\\FilamentShield\\Facades\\FilamentShield" + }, + "providers": [ + "BezhanSalleh\\FilamentShield\\FilamentShieldServiceProvider" + ] + } + }, + "autoload": { + "psr-4": { + "BezhanSalleh\\FilamentShield\\": "src", + "BezhanSalleh\\FilamentShield\\Database\\Factories\\": "database/factories" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Bezhan Salleh", + "email": "bezhan_salleh@yahoo.com", + "role": "Developer" + } + ], + "description": "Filament support for `spatie/laravel-permission`.", + "homepage": "https://github.com/bezhansalleh/filament-shield", + "keywords": [ + "acl", + "bezhanSalleh", + "filament", + "filament-shield", + "laravel", + "permission", + "permissions", + "rbac", + "roles", + "security" + ], + "support": { + "issues": "https://github.com/bezhanSalleh/filament-shield/issues", + "source": "https://github.com/bezhanSalleh/filament-shield/tree/4.1.0" + }, + "funding": [ + { + "url": "https://github.com/bezhanSalleh", + "type": "github" + } + ], + "time": "2026-01-19T19:28:46+00:00" + }, { "name": "blade-ui-kit/blade-heroicons", "version": "2.6.0", @@ -6503,6 +6676,89 @@ ], "time": "2026-02-21T12:49:54+00:00" }, + { + "name": "spatie/laravel-permission", + "version": "6.24.1", + "source": { + "type": "git", + "url": "https://github.com/spatie/laravel-permission.git", + "reference": "eefc9d17eba80d023d6bff313f882cb2bcd691a3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/spatie/laravel-permission/zipball/eefc9d17eba80d023d6bff313f882cb2bcd691a3", + "reference": "eefc9d17eba80d023d6bff313f882cb2bcd691a3", + "shasum": "" + }, + "require": { + "illuminate/auth": "^8.12|^9.0|^10.0|^11.0|^12.0", + "illuminate/container": "^8.12|^9.0|^10.0|^11.0|^12.0", + "illuminate/contracts": "^8.12|^9.0|^10.0|^11.0|^12.0", + "illuminate/database": "^8.12|^9.0|^10.0|^11.0|^12.0", + "php": "^8.0" + }, + "require-dev": { + "laravel/passport": "^11.0|^12.0", + "laravel/pint": "^1.0", + "orchestra/testbench": "^6.23|^7.0|^8.0|^9.0|^10.0", + "phpunit/phpunit": "^9.4|^10.1|^11.5" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Spatie\\Permission\\PermissionServiceProvider" + ] + }, + "branch-alias": { + "dev-main": "6.x-dev", + "dev-master": "6.x-dev" + } + }, + "autoload": { + "files": [ + "src/helpers.php" + ], + "psr-4": { + "Spatie\\Permission\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Freek Van der Herten", + "email": "freek@spatie.be", + "homepage": "https://spatie.be", + "role": "Developer" + } + ], + "description": "Permission handling for Laravel 8.0 and up", + "homepage": "https://github.com/spatie/laravel-permission", + "keywords": [ + "acl", + "laravel", + "permission", + "permissions", + "rbac", + "roles", + "security", + "spatie" + ], + "support": { + "issues": "https://github.com/spatie/laravel-permission/issues", + "source": "https://github.com/spatie/laravel-permission/tree/6.24.1" + }, + "funding": [ + { + "url": "https://github.com/spatie", + "type": "github" + } + ], + "time": "2026-02-09T21:10:03+00:00" + }, { "name": "spatie/laravel-settings", "version": "3.7.0", diff --git a/config/filament-shield.php b/config/filament-shield.php new file mode 100644 index 0000000..189c29a --- /dev/null +++ b/config/filament-shield.php @@ -0,0 +1,263 @@ + [ + 'slug' => 'shield/roles', + 'show_model_path' => true, + 'cluster' => null, + 'tabs' => [ + 'pages' => true, + 'widgets' => true, + 'resources' => true, + 'custom_permissions' => false, + ], + ], + + /* + |-------------------------------------------------------------------------- + | Multi-Tenancy + |-------------------------------------------------------------------------- + | + | When your application supports teams, Shield will automatically detect + | and configure the tenant model during setup. This enables tenant-scoped + | roles and permissions throughout your application. + | + */ + + 'tenant_model' => null, + + /* + |-------------------------------------------------------------------------- + | User Model + |-------------------------------------------------------------------------- + | + | This value contains the class name of your user model. This model will + | be used for role assignments and must implement the HasRoles trait + | provided by the Spatie\Permission package. + | + */ + + 'auth_provider_model' => 'App\\Models\\User', + + /* + |-------------------------------------------------------------------------- + | Super Admin + |-------------------------------------------------------------------------- + | + | Here you may define a super admin that has unrestricted access to your + | application. You can choose to implement this via Laravel's gate system + | or as a traditional role with all permissions explicitly assigned. + | + */ + + 'super_admin' => [ + 'enabled' => true, + 'name' => 'super_admin', + 'define_via_gate' => false, + 'intercept_gate' => 'before', + ], + + /* + |-------------------------------------------------------------------------- + | Panel User + |-------------------------------------------------------------------------- + | + | When enabled, Shield will create a basic panel user role that can be + | assigned to users who should have access to your Filament panels but + | don't need any specific permissions beyond basic authentication. + | + */ + + 'panel_user' => [ + 'enabled' => true, + 'name' => 'panel_user', + ], + + /* + |-------------------------------------------------------------------------- + | Permission Builder + |-------------------------------------------------------------------------- + | + | You can customize how permission keys are generated to match your + | preferred naming convention and organizational standards. Shield uses + | these settings when creating permission names from your resources. + | + | Supported formats: snake, kebab, pascal, camel, upper_snake, lower_snake + | + */ + + 'permissions' => [ + 'separator' => ':', + 'case' => 'pascal', + 'generate' => true, + ], + + /* + |-------------------------------------------------------------------------- + | Policies + |-------------------------------------------------------------------------- + | + | Shield can automatically generate Laravel policies for your resources. + | When merge is enabled, the methods below will be combined with any + | resource-specific methods you define in the resources section. + | + */ + + 'policies' => [ + 'path' => app_path('Policies'), + 'merge' => true, + 'generate' => true, + 'methods' => [ + 'viewAny', 'view', 'create', 'update', 'delete', 'restore', + 'forceDelete', 'forceDeleteAny', 'restoreAny', 'replicate', 'reorder', + ], + 'single_parameter_methods' => [ + 'viewAny', + 'create', + 'deleteAny', + 'forceDeleteAny', + 'restoreAny', + 'reorder', + ], + ], + + /* + |-------------------------------------------------------------------------- + | Localization + |-------------------------------------------------------------------------- + | + | Shield supports multiple languages out of the box. When enabled, you + | can provide translated labels for permissions to create a more + | localized experience for your international users. + | + */ + + 'localization' => [ + 'enabled' => false, + 'key' => 'filament-shield::filament-shield.resource_permission_prefixes_labels', + ], + + /* + |-------------------------------------------------------------------------- + | Resources + |-------------------------------------------------------------------------- + | + | Here you can fine-tune permissions for specific Filament resources. + | Use the 'manage' array to override the default policy methods for + | individual resources, giving you granular control over permissions. + | + */ + + 'resources' => [ + 'subject' => 'model', + 'manage' => [ + \BezhanSalleh\FilamentShield\Resources\Roles\RoleResource::class => [ + 'viewAny', + 'view', + 'create', + 'update', + 'delete', + ], + ], + 'exclude' => [ + // + ], + ], + + /* + |-------------------------------------------------------------------------- + | Pages + |-------------------------------------------------------------------------- + | + | Most Filament pages only require view permissions. Pages listed in the + | exclude array will be skipped during permission generation and won't + | appear in your role management interface. + | + */ + + 'pages' => [ + 'subject' => 'class', + 'prefix' => 'view', + 'exclude' => [ + \Filament\Pages\Dashboard::class, + ], + ], + + /* + |-------------------------------------------------------------------------- + | Widgets + |-------------------------------------------------------------------------- + | + | Like pages, widgets typically only need view permissions. Add widgets + | to the exclude array if you don't want them to appear in your role + | management interface. + | + */ + + 'widgets' => [ + 'subject' => 'class', + 'prefix' => 'view', + 'exclude' => [ + \Filament\Widgets\AccountWidget::class, + \Filament\Widgets\FilamentInfoWidget::class, + ], + ], + + /* + |-------------------------------------------------------------------------- + | Custom Permissions + |-------------------------------------------------------------------------- + | + | Sometimes you need permissions that don't map to resources, pages, or + | widgets. Define any custom permissions here and they'll be available + | when editing roles in your application. + | + */ + + 'custom_permissions' => [], + + /* + |-------------------------------------------------------------------------- + | Entity Discovery + |-------------------------------------------------------------------------- + | + | By default, Shield only looks for entities in your default Filament + | panel. Enable these options if you're using multiple panels and want + | Shield to discover entities across all of them. + | + */ + + 'discovery' => [ + 'discover_all_resources' => false, + 'discover_all_widgets' => false, + 'discover_all_pages' => false, + ], + + /* + |-------------------------------------------------------------------------- + | Role Policy + |-------------------------------------------------------------------------- + | + | Shield can automatically register a policy for role management itself. + | This lets you control who can manage roles using Laravel's built-in + | authorization system. Requires a RolePolicy class in your app. + | + */ + + 'register_role_policy' => true, + +]; diff --git a/config/permission.php b/config/permission.php new file mode 100644 index 0000000..f39f6b5 --- /dev/null +++ b/config/permission.php @@ -0,0 +1,202 @@ + [ + + /* + * When using the "HasPermissions" trait from this package, we need to know which + * Eloquent model should be used to retrieve your permissions. Of course, it + * is often just the "Permission" model but you may use whatever you like. + * + * The model you want to use as a Permission model needs to implement the + * `Spatie\Permission\Contracts\Permission` contract. + */ + + 'permission' => Spatie\Permission\Models\Permission::class, + + /* + * When using the "HasRoles" trait from this package, we need to know which + * Eloquent model should be used to retrieve your roles. Of course, it + * is often just the "Role" model but you may use whatever you like. + * + * The model you want to use as a Role model needs to implement the + * `Spatie\Permission\Contracts\Role` contract. + */ + + 'role' => Spatie\Permission\Models\Role::class, + + ], + + 'table_names' => [ + + /* + * When using the "HasRoles" trait from this package, we need to know which + * table should be used to retrieve your roles. We have chosen a basic + * default value but you may easily change it to any table you like. + */ + + 'roles' => 'roles', + + /* + * When using the "HasPermissions" trait from this package, we need to know which + * table should be used to retrieve your permissions. We have chosen a basic + * default value but you may easily change it to any table you like. + */ + + 'permissions' => 'permissions', + + /* + * When using the "HasPermissions" trait from this package, we need to know which + * table should be used to retrieve your models permissions. We have chosen a + * basic default value but you may easily change it to any table you like. + */ + + 'model_has_permissions' => 'model_has_permissions', + + /* + * When using the "HasRoles" trait from this package, we need to know which + * table should be used to retrieve your models roles. We have chosen a + * basic default value but you may easily change it to any table you like. + */ + + 'model_has_roles' => 'model_has_roles', + + /* + * When using the "HasRoles" trait from this package, we need to know which + * table should be used to retrieve your roles permissions. We have chosen a + * basic default value but you may easily change it to any table you like. + */ + + 'role_has_permissions' => 'role_has_permissions', + ], + + 'column_names' => [ + /* + * Change this if you want to name the related pivots other than defaults + */ + 'role_pivot_key' => null, // default 'role_id', + 'permission_pivot_key' => null, // default 'permission_id', + + /* + * Change this if you want to name the related model primary key other than + * `model_id`. + * + * For example, this would be nice if your primary keys are all UUIDs. In + * that case, name this `model_uuid`. + */ + + 'model_morph_key' => 'model_id', + + /* + * Change this if you want to use the teams feature and your related model's + * foreign key is other than `team_id`. + */ + + 'team_foreign_key' => 'team_id', + ], + + /* + * When set to true, the method for checking permissions will be registered on the gate. + * Set this to false if you want to implement custom logic for checking permissions. + */ + + 'register_permission_check_method' => true, + + /* + * When set to true, Laravel\Octane\Events\OperationTerminated event listener will be registered + * this will refresh permissions on every TickTerminated, TaskTerminated and RequestTerminated + * NOTE: This should not be needed in most cases, but an Octane/Vapor combination benefited from it. + */ + 'register_octane_reset_listener' => false, + + /* + * Events will fire when a role or permission is assigned/unassigned: + * \Spatie\Permission\Events\RoleAttached + * \Spatie\Permission\Events\RoleDetached + * \Spatie\Permission\Events\PermissionAttached + * \Spatie\Permission\Events\PermissionDetached + * + * To enable, set to true, and then create listeners to watch these events. + */ + 'events_enabled' => false, + + /* + * Teams Feature. + * When set to true the package implements teams using the 'team_foreign_key'. + * If you want the migrations to register the 'team_foreign_key', you must + * set this to true before doing the migration. + * If you already did the migration then you must make a new migration to also + * add 'team_foreign_key' to 'roles', 'model_has_roles', and 'model_has_permissions' + * (view the latest version of this package's migration file) + */ + + 'teams' => false, + + /* + * The class to use to resolve the permissions team id + */ + 'team_resolver' => \Spatie\Permission\DefaultTeamResolver::class, + + /* + * Passport Client Credentials Grant + * When set to true the package will use Passports Client to check permissions + */ + + 'use_passport_client_credentials' => false, + + /* + * When set to true, the required permission names are added to exception messages. + * This could be considered an information leak in some contexts, so the default + * setting is false here for optimum safety. + */ + + 'display_permission_in_exception' => false, + + /* + * When set to true, the required role names are added to exception messages. + * This could be considered an information leak in some contexts, so the default + * setting is false here for optimum safety. + */ + + 'display_role_in_exception' => false, + + /* + * By default wildcard permission lookups are disabled. + * See documentation to understand supported syntax. + */ + + 'enable_wildcard_permission' => false, + + /* + * The class to use for interpreting wildcard permissions. + * If you need to modify delimiters, override the class and specify its name here. + */ + // 'wildcard_permission' => Spatie\Permission\WildcardPermission::class, + + /* Cache-specific settings */ + + 'cache' => [ + + /* + * By default all permissions are cached for 24 hours to speed up performance. + * When permissions or roles are updated the cache is flushed automatically. + */ + + 'expiration_time' => \DateInterval::createFromDateString('24 hours'), + + /* + * The cache key used to store all permissions. + */ + + 'key' => 'spatie.permission.cache', + + /* + * You may optionally indicate a specific cache driver to use for permission and + * role caching using any of the `store` drivers listed in the cache.php config + * file. Using 'default' here means to use the `default` set in cache.php. + */ + + 'store' => 'default', + ], +]; diff --git a/database/migrations/2026_03_12_083616_create_permission_tables.php b/database/migrations/2026_03_12_083616_create_permission_tables.php new file mode 100644 index 0000000..66ce1f9 --- /dev/null +++ b/database/migrations/2026_03_12_083616_create_permission_tables.php @@ -0,0 +1,134 @@ +engine('InnoDB'); + $table->bigIncrements('id'); // permission id + $table->string('name'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format) + $table->string('guard_name'); // For MyISAM use string('guard_name', 25); + $table->timestamps(); + + $table->unique(['name', 'guard_name']); + }); + + Schema::create($tableNames['roles'], static function (Blueprint $table) use ($teams, $columnNames) { + // $table->engine('InnoDB'); + $table->bigIncrements('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'); // For MyISAM use string('name', 225); // (or 166 for InnoDB with Redundant/Compact row format) + $table->string('guard_name'); // For MyISAM use string('guard_name', 25); + $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']) + ->onDelete('cascade'); + 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']) + ->onDelete('cascade'); + 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']) + ->onDelete('cascade'); + + $table->foreign($pivotRole) + ->references('id') // role id + ->on($tableNames['roles']) + ->onDelete('cascade'); + + $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), Exception::class, '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::drop($tableNames['role_has_permissions']); + Schema::drop($tableNames['model_has_roles']); + Schema::drop($tableNames['model_has_permissions']); + Schema::drop($tableNames['roles']); + Schema::drop($tableNames['permissions']); + } +}; diff --git a/database/seeders/ShieldSeeder.php b/database/seeders/ShieldSeeder.php new file mode 100644 index 0000000..4193683 --- /dev/null +++ b/database/seeders/ShieldSeeder.php @@ -0,0 +1,391 @@ +forgetCachedPermissions(); + + $tenants = '[]'; + $users = '[]'; + $userTenantPivot = '[]'; + $rolesWithPermissions = <<<'JSON' + [ + { + "name": "Developer", + "guard_name": "web", + "permissions" : [ + "ViewAny:Student", + "View:Student", + "Create:Student", + "Update:Student", + "Delete:Student", + "Restore:Student", + "ForceDelete:Student", + "ForceDeleteAny:Student", + "RestoreAny:Student", + "Replicate:Student", + "Reorder:Student", + + "ViewAny:Lecturer", + "View:Lecturer", + "Create:Lecturer", + "Update:Lecturer", + "Delete:Lecturer", + "Restore:Lecturer", + "ForceDelete:Lecturer", + "ForceDeleteAny:Lecturer", + "RestoreAny:Lecturer", + "Replicate:Lecturer", + "Reorder:Lecturer", + + "ViewAny:Course", + "View:Course", + "Create:Course", + "Update:Course", + "Delete:Course", + "Restore:Course", + "ForceDelete:Course", + "ForceDeleteAny:Course", + "RestoreAny:Course", + "Replicate:Course", + "Reorder:Course", + + "ViewAny:CourseSchedule", + "View:CourseSchedule", + "Create:CourseSchedule", + "Update:CourseSchedule", + "Delete:CourseSchedule", + "Restore:CourseSchedule", + "ForceDelete:CourseSchedule", + "ForceDeleteAny:CourseSchedule", + "RestoreAny:CourseSchedule", + "Replicate:CourseSchedule", + "Reorder:CourseSchedule", + + "ViewAny:Assignment", + "View:Assignment", + "Create:Assignment", + "Update:Assignment", + "Delete:Assignment", + "Restore:Assignment", + "ForceDelete:Assignment", + "ForceDeleteAny:Assignment", + "RestoreAny:Assignment", + "Replicate:Assignment", + "Reorder:Assignment", + + "ViewAny:Attendance", + "View:Attendance", + "Create:Attendance", + "Update:Attendance", + "Delete:Attendance", + "Restore:Attendance", + "ForceDelete:Attendance", + "ForceDeleteAny:Attendance", + "RestoreAny:Attendance", + "Replicate:Attendance", + "Reorder:Attendance", + + "ViewAny:Material", + "View:Material", + "Create:Material", + "Update:Material", + "Delete:Material", + "Restore:Material", + "ForceDelete:Material", + "ForceDeleteAny:Material", + "RestoreAny:Material", + "Replicate:Material", + "Reorder:Material", + + "ViewAny:StudyGroup", + "View:StudyGroup", + "Create:StudyGroup", + "Update:StudyGroup", + "Delete:StudyGroup", + "Restore:StudyGroup", + "ForceDelete:StudyGroup", + "ForceDeleteAny:StudyGroup", + "RestoreAny:StudyGroup", + "Replicate:StudyGroup", + "Reorder:StudyGroup", + + "ViewAny:Role", + "View:Role", + "Create:Role", + "Update:Role", + "Delete:Role", + "Restore:Role", + "ForceDelete:Role", + "ForceDeleteAny:Role", + "RestoreAny:Role", + "Replicate:Role", + "Reorder:Role", + + "View:LogTable", + "View:ManageSettings" + ] + }, + { + "name": "Mahasiswa", + "guard_name": "web", + "permissions" : [ + "ViewAny:Student", + "View:Student", + + "ViewAny:Lecturer", + "View:Lecturer", + + "ViewAny:Course", + "View:Course", + + "ViewAny:CourseSchedule", + "View:CourseSchedule", + + "ViewAny:Assignment", + "View:Assignment", + + "ViewAny:Attendance", + "View:Attendance", + + "ViewAny:Material", + "View:Material", + + "ViewAny:StudyGroup", + "View:StudyGroup" + ] + }, + { + "name": "Kosma", + "guard_name": "web", + "permissions" : [ + "ViewAny:Student", + "View:Student", + + "ViewAny:Lecturer", + "View:Lecturer", + + "ViewAny:Course", + "View:Course", + + "ViewAny:CourseSchedule", + "View:CourseSchedule", + + "ViewAny:Assignment", + "View:Assignment", + + "ViewAny:Attendance", + "View:Attendance", + "Create:Attendance", + "Update:Attendance", + "Delete:Attendance", + + "ViewAny:Material", + "View:Material", + + "ViewAny:StudyGroup", + "View:StudyGroup",, + "Create:StudyGroup", + "Update:StudyGroup", + "Delete:StudyGroup" + ] + } + + ] + JSON; + $directPermissions = '[]'; + + // 1. Seed tenants first (if present) + if (! blank($tenants) && $tenants !== '[]') { + static::seedTenants($tenants); + } + + // 2. Seed roles with permissions + static::makeRolesWithPermissions($rolesWithPermissions); + + // 3. Seed direct permissions + static::makeDirectPermissions($directPermissions); + + // 4. Seed users with their roles/permissions (if present) + if (! blank($users) && $users !== '[]') { + static::seedUsers($users); + } + + // 5. Seed user-tenant pivot (if present) + if (! blank($userTenantPivot) && $userTenantPivot !== '[]') { + static::seedUserTenantPivot($userTenantPivot); + } + + $this->command->info('Shield Seeding Completed.'); + } + + protected static function seedTenants(string $tenants): void + { + if (blank($tenantData = json_decode($tenants, true))) { + return; + } + + $tenantModel = ''; + if (blank($tenantModel)) { + return; + } + + foreach ($tenantData as $tenant) { + $tenantModel::firstOrCreate( + ['id' => $tenant['id']], + $tenant + ); + } + } + + protected static function seedUsers(string $users): void + { + if (blank($userData = json_decode($users, true))) { + return; + } + + $userModel = 'App\Models\User'; + $tenancyEnabled = false; + + foreach ($userData as $data) { + // Extract role/permission data before creating user + $roles = $data['roles'] ?? []; + $permissions = $data['permissions'] ?? []; + $tenantRoles = $data['tenant_roles'] ?? []; + $tenantPermissions = $data['tenant_permissions'] ?? []; + unset($data['roles'], $data['permissions'], $data['tenant_roles'], $data['tenant_permissions']); + + $user = $userModel::firstOrCreate( + ['email' => $data['email']], + $data + ); + + // Handle tenancy mode - sync roles/permissions per tenant + if ($tenancyEnabled && (! empty($tenantRoles) || ! empty($tenantPermissions))) { + foreach ($tenantRoles as $tenantId => $roleNames) { + $contextId = $tenantId === '_global' ? null : $tenantId; + setPermissionsTeamId($contextId); + $user->syncRoles($roleNames); + } + + foreach ($tenantPermissions as $tenantId => $permissionNames) { + $contextId = $tenantId === '_global' ? null : $tenantId; + setPermissionsTeamId($contextId); + $user->syncPermissions($permissionNames); + } + } else { + // Non-tenancy mode + if (! empty($roles)) { + $user->syncRoles($roles); + } + + if (! empty($permissions)) { + $user->syncPermissions($permissions); + } + } + } + } + + protected static function seedUserTenantPivot(string $pivot): void + { + if (blank($pivotData = json_decode($pivot, true))) { + return; + } + + $pivotTable = ''; + if (blank($pivotTable)) { + return; + } + + foreach ($pivotData as $row) { + $uniqueKeys = []; + + if (isset($row['user_id'])) { + $uniqueKeys['user_id'] = $row['user_id']; + } + + $tenantForeignKey = 'team_id'; + if (! blank($tenantForeignKey) && isset($row[$tenantForeignKey])) { + $uniqueKeys[$tenantForeignKey] = $row[$tenantForeignKey]; + } + + if (! empty($uniqueKeys)) { + DB::table($pivotTable)->updateOrInsert($uniqueKeys, $row); + } + } + } + + protected static function makeRolesWithPermissions(string $rolesWithPermissions): void + { + if (blank($rolePlusPermissions = json_decode($rolesWithPermissions, true))) { + return; + } + + /** @var \Illuminate\Database\Eloquent\Model $roleModel */ + $roleModel = Utils::getRoleModel(); + /** @var \Illuminate\Database\Eloquent\Model $permissionModel */ + $permissionModel = Utils::getPermissionModel(); + + $tenancyEnabled = false; + $teamForeignKey = 'team_id'; + + foreach ($rolePlusPermissions as $rolePlusPermission) { + $tenantId = $rolePlusPermission[$teamForeignKey] ?? null; + + // Set tenant context for role creation and permission sync + if ($tenancyEnabled) { + setPermissionsTeamId($tenantId); + } + + $roleData = [ + 'name' => $rolePlusPermission['name'], + 'guard_name' => $rolePlusPermission['guard_name'], + ]; + + // Include tenant ID in role data (can be null for global roles) + if ($tenancyEnabled && ! blank($teamForeignKey)) { + $roleData[$teamForeignKey] = $tenantId; + } + + $role = $roleModel::firstOrCreate($roleData); + + if (! blank($rolePlusPermission['permissions'])) { + $permissionModels = collect($rolePlusPermission['permissions']) + ->map(fn ($permission) => $permissionModel::firstOrCreate([ + 'name' => $permission, + 'guard_name' => $rolePlusPermission['guard_name'], + ])) + ->all(); + + $role->syncPermissions($permissionModels); + } + } + } + + public static function makeDirectPermissions(string $directPermissions): void + { + if (blank($permissions = json_decode($directPermissions, true))) { + return; + } + + /** @var \Illuminate\Database\Eloquent\Model $permissionModel */ + $permissionModel = Utils::getPermissionModel(); + + foreach ($permissions as $permission) { + if ($permissionModel::whereName($permission['name'])->doesntExist()) { + $permissionModel::create([ + 'name' => $permission['name'], + 'guard_name' => $permission['guard_name'], + ]); + } + } + } +}