diff --git a/app/Filament/Resources/Master/Users/Actions/ChangePasswordAction.php b/app/Filament/Resources/Master/Users/Actions/ChangePasswordAction.php new file mode 100644 index 0000000..f006901 --- /dev/null +++ b/app/Filament/Resources/Master/Users/Actions/ChangePasswordAction.php @@ -0,0 +1,42 @@ +label('Ganti Kata Sandi') + ->icon(Heroicon::Key) + ->color('warning') + ->modalWidth(Width::Medium) + ->schema([ + TextInput::make('password') + ->label('Kata Sandi Baru') + ->password() + ->required() + ->minLength(8) + ->default(config('auth.password_default')), + ]) + ->action(function (User $record, array $data): void { + $record->update([ + 'password' => Hash::make($data['password']), + ]); + + CheerfulNotification::success( + 'Kata sandi berhasil diubah! 🔑', + "Kata sandi untuk pengguna {$record->name} telah diperbarui." + )->send(); + }); + } +} diff --git a/app/Filament/Resources/Master/Users/Pages/ManageUsers.php b/app/Filament/Resources/Master/Users/Pages/ManageUsers.php new file mode 100644 index 0000000..2b96bdb --- /dev/null +++ b/app/Filament/Resources/Master/Users/Pages/ManageUsers.php @@ -0,0 +1,38 @@ +label('Tambah') + ->modalHeading('Tambah Pengguna') + ->modalSubmitActionLabel('Simpan') + ->modalCancelActionLabel('Batal') + ->extraModalFooterActions(fn (CreateAction $action): array => [ + $action->makeModalSubmitAction('createAnother', arguments: ['another' => true]) + ->label('Simpan dan Tambah Lagi'), + ]) + ->modalWidth(Width::Large) + ->after(function (CreateAction $action): void { + $user = $action->getRecord(); + + $user->update([ + 'email_verified_at' => now(), + ]); + }), + ]; + } +} diff --git a/app/Filament/Resources/Master/Users/UserResource.php b/app/Filament/Resources/Master/Users/UserResource.php new file mode 100644 index 0000000..c35119d --- /dev/null +++ b/app/Filament/Resources/Master/Users/UserResource.php @@ -0,0 +1,170 @@ +components([ + TextInput::make('name') + ->label('Nama') + ->placeholder('John Doe') + ->autocomplete(false) + ->autofocus() + ->required() + ->maxLength(100), + + TextInput::make('email') + ->label('Alamat Surel') + ->placeholder('johndoe@example.com') + ->autocomplete(false) + ->required() + ->maxLength(254) + ->email() + ->unique(ignoreRecord: true), + + TextInput::make('username') + ->label('Nama Pengguna') + ->placeholder('johndoe') + ->autocomplete(false) + ->required() + ->minLength(5) + ->maxLength(20) + ->regex('/^[a-zA-Z0-9_.-]+$/') + ->unique(ignoreRecord: true), + + Select::make('roles') + ->label('Peran') + ->required() + ->relationship('roles', 'name', function (Builder $query): Builder { + return $query->whereNot('name', RoleEnum::DEVELOPER); + }) + ->multiple() + ->preload() + ->searchable(), + + Hidden::make('password') + ->default(fn (): string => config('auth.password_default')) + ->visibleOn('create'), + ]) + ->columns(1); + } + + public static function table(Table $table): Table + { + return $table + ->columns([ + TextColumn::make('name') + ->label('Nama') + ->searchable() + ->sortable(), + + TextColumn::make('email') + ->label('Alamat Surel') + ->searchable() + ->sortable(), + + TextColumn::make('username') + ->label('Nama Pengguna') + ->searchable() + ->sortable(), + + TextColumn::make('roles.name') + ->label('Peran') + ->searchable() + ->sortable() + ->badge() + ->getStateUsing(fn (User $record): array => $record->roles->pluck('name', 'id')->toArray()), + + ...TimestampColumns::make(), + ]) + ->filters([ + TrashedFilter::make() + ->native(false) + ->visible(fn () => auth()->user()?->hasRole(RoleEnum::DEVELOPER->value)), + ]) + ->recordActions([ + EditAction::make() + ->modalWidth(Width::Large), + + DeleteAction::make(), + + ForceDeleteAction::make(), + + RestoreAction::make(), + + ChangePasswordAction::make('changePassword'), + ]) + ->toolbarActions([ + BulkActionGroup::make([ + ...DefaultBulkActions::make('Pengguna'), + ]), + ]) + ->emptyStateIcon(Heroicon::UserGroup) + ->emptyStateDescription('Setelah Anda membubat data pertama, maka akan muncul disini.') + ->defaultSort('created_at', 'desc') + ->deferFilters(false); + } + + public static function getPages(): array + { + return [ + 'index' => ManageUsers::route('/'), + ]; + } + + public static function getRecordRouteBindingEloquentQuery(): Builder + { + return parent::getRecordRouteBindingEloquentQuery() + ->withoutGlobalScopes([ + SoftDeletingScope::class, + ]); + } + + public static function getEloquentQuery(): Builder + { + return static::getModel()::query()->withoutDeveloper(); + } +} diff --git a/app/Models/User.php b/app/Models/User.php index f858a3a..7c0b940 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -2,14 +2,18 @@ namespace App\Models; +use App\Enums\RoleEnum; +use Illuminate\Database\Eloquent\Attributes\Scope; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; +use Spatie\Permission\Traits\HasRoles; class User extends Authenticatable { - use HasFactory, Notifiable, SoftDeletes; + use HasFactory, HasRoles, Notifiable, SoftDeletes; protected $guarded = ['id']; @@ -23,4 +27,12 @@ protected function casts(): array 'password' => 'hashed', ]; } + + #[Scope] + protected function withoutDeveloper(Builder $query): void + { + $query->whereDoesntHave('roles', function ($q) { + $q->where('name', RoleEnum::DEVELOPER); + }); + } } diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php index 591c6ab..41be4f5 100644 --- a/app/Providers/Filament/AdminPanelProvider.php +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -3,6 +3,7 @@ namespace App\Providers\Filament; use App\Filament\Pages\Auth\Login; +use BezhanSalleh\FilamentShield\FilamentShieldPlugin; use DiogoGPinto\AuthUIEnhancer\AuthUIEnhancerPlugin; use Filament\Http\Middleware\Authenticate; use Filament\Http\Middleware\AuthenticateSession; @@ -59,6 +60,10 @@ public function panel(Panel $panel): Panel Authenticate::class, ]) ->plugins([ + FilamentShieldPlugin::make() + ->navigationSort(999) + ->globallySearchable(false), + AuthUIEnhancerPlugin::make() ->formPanelPosition('left'), ]); diff --git a/composer.json b/composer.json index 3076557..c569cff 100644 --- a/composer.json +++ b/composer.json @@ -7,6 +7,7 @@ "license": "MIT", "require": { "php": "^8.2", + "bezhansalleh/filament-shield": "^4.1", "diogogpinto/filament-auth-ui-enhancer": "^2.0", "filament/filament": "^4.0", "laravel/framework": "^12.0", diff --git a/composer.lock b/composer.lock index 6bf97ba..237f55d 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": "28d56c0579aa0bff54a3eda86204b137", + "content-hash": "d3efc2f623e80c6e682768ab50e46f11", "packages": [ { "name": "anourvalar/eloquent-serialize", @@ -72,6 +72,179 @@ }, "time": "2025-12-04T13:38:21+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", @@ -5342,6 +5515,89 @@ ], "time": "2025-07-17T15:46:43+00:00" }, + { + "name": "spatie/laravel-permission", + "version": "6.24.0", + "source": { + "type": "git", + "url": "https://github.com/spatie/laravel-permission.git", + "reference": "76adb1fc8d07c16a0721c35c4cc330b7a12598d7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/spatie/laravel-permission/zipball/76adb1fc8d07c16a0721c35c4cc330b7a12598d7", + "reference": "76adb1fc8d07c16a0721c35c4cc330b7a12598d7", + "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.0" + }, + "funding": [ + { + "url": "https://github.com/spatie", + "type": "github" + } + ], + "time": "2025-12-13T21:45:21+00:00" + }, { "name": "spatie/shiki-php", "version": "2.3.2", 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_02_09_015257_create_permission_tables.php b/database/migrations/2026_02_09_015257_create_permission_tables.php new file mode 100644 index 0000000..66ce1f9 --- /dev/null +++ b/database/migrations/2026_02_09_015257_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/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index b9c7377..6b43e93 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -15,6 +15,7 @@ class DatabaseSeeder extends Seeder public function run(): void { $this->call([ + ShieldSeeder::class, UserSeeder::class, ]); } diff --git a/database/seeders/ShieldSeeder.php b/database/seeders/ShieldSeeder.php new file mode 100644 index 0000000..82724f9 --- /dev/null +++ b/database/seeders/ShieldSeeder.php @@ -0,0 +1,226 @@ +forgetCachedPermissions(); + + $tenants = '[]'; + $users = '[]'; + $userTenantPivot = '[]'; + $rolesWithPermissions = <<<'JSON' + [ + { + "name": "Developer", + "guard_name": "web", + "permissions" : [] + }, + { + "name": "Pemilik", + "guard_name": "web", + "permissions" : [] + }, + { + "name": "Administrator", + "guard_name": "web", + "permissions" : [] + } + ] + 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'], + ]); + } + } + } +} diff --git a/database/seeders/UserSeeder.php b/database/seeders/UserSeeder.php index f252a25..f96fc93 100644 --- a/database/seeders/UserSeeder.php +++ b/database/seeders/UserSeeder.php @@ -2,6 +2,7 @@ namespace Database\Seeders; +use App\Enums\RoleEnum; use App\Models\User; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\Hash; @@ -20,6 +21,7 @@ public function run(): void 'username' => 'pangestu', 'password' => Hash::make(config('auth.password_default')), ]); + $developer->assignRole(RoleEnum::DEVELOPER); // owner $owner = User::create([ @@ -28,6 +30,7 @@ public function run(): void 'username' => 'owner', 'password' => Hash::make(config('auth.password_default')), ]); + $owner->assignRole(RoleEnum::OWNER); // admin $administrator = User::create([ @@ -36,5 +39,6 @@ public function run(): void 'username' => 'admin', 'password' => Hash::make(config('auth.password_default')), ]); + $administrator->assignRole(RoleEnum::ADMINISTRATOR); } }