From f383f3bd0037bf445575528e407dd1ee593bc73a Mon Sep 17 00:00:00 2001 From: Yoga Pangestu Date: Fri, 24 Apr 2026 23:43:40 +0700 Subject: [PATCH] feat: integrate spatie/laravel-permission for role-based access control and initialize core system permissions --- app/Models/User.php | 3 +- composer.json | 1 + composer.lock | 91 +++++++- config/permission.php | 206 ++++++++++++++++++ ..._04_24_221340_create_permission_tables.php | 137 ++++++++++++ database/seeders/DatabaseSeeder.php | 1 + database/seeders/RolePermissionSeeder.php | 147 +++++++++++++ database/seeders/UserSeeder.php | 36 ++- 8 files changed, 615 insertions(+), 7 deletions(-) create mode 100644 config/permission.php create mode 100644 database/migrations/2026_04_24_221340_create_permission_tables.php create mode 100644 database/seeders/RolePermissionSeeder.php diff --git a/app/Models/User.php b/app/Models/User.php index 2c39794..1c4debc 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -18,13 +18,14 @@ use Spatie\Activitylog\LogOptions; use Spatie\Activitylog\Models\Activity; use Spatie\Activitylog\Traits\LogsActivity; +use Spatie\Permission\Traits\HasRoles; #[Guarded('id')] #[Hidden(['password'])] #[Appends(['name'])] class User extends Authenticatable { - use HasFactory, LogsActivity, Notifiable, SoftDeletes, TwoFactorAuthenticatable; + use HasFactory, HasRoles, LogsActivity, Notifiable, SoftDeletes, TwoFactorAuthenticatable; protected function casts(): array { diff --git a/composer.json b/composer.json index 1e1fdee..299fb6b 100644 --- a/composer.json +++ b/composer.json @@ -18,6 +18,7 @@ "laravel/wayfinder": "^0.1.14", "spatie/laravel-activitylog": "^4.12", "spatie/laravel-medialibrary": "^11.21", + "spatie/laravel-permission": "^7.3", "spatie/laravel-sluggable": "^3.8" }, "require-dev": { diff --git a/composer.lock b/composer.lock index 3376e78..bab706b 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": "613455d10d2d30948240a64a80c92cdf", + "content-hash": "1e97290615923580b9a565671ca7bfae", "packages": [ { "name": "archtechx/enums", @@ -5229,6 +5229,93 @@ ], "time": "2026-02-21T12:49:54+00:00" }, + { + "name": "spatie/laravel-permission", + "version": "7.3.0", + "source": { + "type": "git", + "url": "https://github.com/spatie/laravel-permission.git", + "reference": "5272955119759cd217e84e8bbac19443c305ebc3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/spatie/laravel-permission/zipball/5272955119759cd217e84e8bbac19443c305ebc3", + "reference": "5272955119759cd217e84e8bbac19443c305ebc3", + "shasum": "" + }, + "require": { + "illuminate/auth": "^12.0|^13.0", + "illuminate/container": "^12.0|^13.0", + "illuminate/contracts": "^12.0|^13.0", + "illuminate/database": "^12.0|^13.0", + "php": "^8.3", + "spatie/laravel-package-tools": "^1.0" + }, + "require-dev": { + "larastan/larastan": "^3.9", + "laravel/passport": "^13.0", + "laravel/pint": "^1.0", + "orchestra/testbench": "^10.0|^11.0", + "pestphp/pest": "^3.0|^4.0", + "pestphp/pest-plugin-laravel": "^3.0|^4.1", + "phpstan/phpstan": "^2.1" + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Spatie\\Permission\\PermissionServiceProvider" + ] + }, + "branch-alias": { + "dev-main": "7.x-dev", + "dev-master": "7.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 12 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/7.3.0" + }, + "funding": [ + { + "url": "https://github.com/spatie", + "type": "github" + } + ], + "time": "2026-04-07T15:19:42+00:00" + }, { "name": "spatie/laravel-sluggable", "version": "3.8.1", @@ -11360,5 +11447,5 @@ "php": "^8.3" }, "platform-dev": {}, - "plugin-api-version": "2.6.0" + "plugin-api-version": "2.9.0" } diff --git a/config/permission.php b/config/permission.php new file mode 100644 index 0000000..392636d --- /dev/null +++ b/config/permission.php @@ -0,0 +1,206 @@ + [ + + /* + * 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' => 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' => 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\RoleAttachedEvent + * \Spatie\Permission\Events\RoleDetachedEvent + * \Spatie\Permission\Events\PermissionAttachedEvent + * \Spatie\Permission\Events\PermissionDetachedEvent + * + * 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' => 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_04_24_221340_create_permission_tables.php b/database/migrations/2026_04_24_221340_create_permission_tables.php new file mode 100644 index 0000000..8986275 --- /dev/null +++ b/database/migrations/2026_04_24_221340_create_permission_tables.php @@ -0,0 +1,137 @@ +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']); + } +}; diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index 0d22859..5d3dcf2 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -14,6 +14,7 @@ public function run(): void { $this->call([ + RolePermissionSeeder::class, UserSeeder::class, CategorySeeder::class, ProductSeeder::class, diff --git a/database/seeders/RolePermissionSeeder.php b/database/seeders/RolePermissionSeeder.php new file mode 100644 index 0000000..962b9ae --- /dev/null +++ b/database/seeders/RolePermissionSeeder.php @@ -0,0 +1,147 @@ + 'View:Dashboard', 'guard_name' => 'web']); + + // Permissions Analysis + Permission::firstOrCreate(['name' => 'View:Analysis', 'guard_name' => 'web']); + + // Permissions User + Permission::firstOrCreate(['name' => 'View:User', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Create:User', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Edit:User', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Delete:User', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'DeleteAny:User', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'ResetPassword:User', 'guard_name' => 'web']); + + // Permissions Category + Permission::firstOrCreate(['name' => 'View:Category', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Create:Category', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Edit:Category', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Delete:Category', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'DeleteAny:Category', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'ToggleStatus:Category', 'guard_name' => 'web']); + + // Permissions Product + Permission::firstOrCreate(['name' => 'View:Product', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Create:Product', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Edit:Product', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Delete:Product', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'DeleteAny:Product', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'ToggleStatus:Product', 'guard_name' => 'web']); + + // Permissions Order + Permission::firstOrCreate(['name' => 'View:Order', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Create:Order', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Edit:Order', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Delete:Order', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'DeleteAny:Order', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Print:Order', 'guard_name' => 'web']); + + // Permissions Expense + Permission::firstOrCreate(['name' => 'View:Expense', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Create:Expense', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Edit:Expense', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Delete:Expense', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'DeleteAny:Expense', 'guard_name' => 'web']); + + // Permissions Purchase + Permission::firstOrCreate(['name' => 'View:Purchase', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Create:Purchase', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Edit:Purchase', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Delete:Purchase', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'DeleteAny:Purchase', 'guard_name' => 'web']); + + // Permissions Payroll + Permission::firstOrCreate(['name' => 'View:Payroll', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Generate:Payroll', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Delete:Payroll', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'DeleteAny:Payroll', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Pay:Payroll', 'guard_name' => 'web']); + + // Permissions PayrollAdjustment + Permission::firstOrCreate(['name' => 'View:PayrollAdjustment', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Create:PayrollAdjustment', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Edit:PayrollAdjustment', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Delete:PayrollAdjustment', 'guard_name' => 'web']); + + // Permissions General Setting + Permission::firstOrCreate(['name' => 'View:Setting', 'guard_name' => 'web']); + Permission::firstOrCreate(['name' => 'Edit:Setting', 'guard_name' => 'web']); + + // Permissions Log + Permission::firstOrCreate(['name' => 'View:Log', 'guard_name' => 'web']); + + // Permissions Activity + Permission::firstOrCreate(['name' => 'View:Activity', 'guard_name' => 'web']); + + // Create Roles + $developer = Role::firstOrCreate(['name' => 'Developer', 'guard_name' => 'web']); + $owner = Role::firstOrCreate(['name' => 'Owner', 'guard_name' => 'web']); + $admin = Role::firstOrCreate(['name' => 'Admin', 'guard_name' => 'web']); + + // Assign permissions to Developer (All Permissions) + $allPermissions = Permission::all(); + $developer->syncPermissions($allPermissions); + + // Assign permissions to Owner (All except View:Log) + $ownerPermissions = Permission::whereNotIn('name', ['View:Log'])->get(); + $owner->syncPermissions($ownerPermissions); + + // Assign permissions to Admin + // Admin gets everything except deleting users and settings + $adminPermissions = Permission::whereNotIn('name', [ + 'View:Analysis', + + 'View:User', + 'Create:User', + 'Edit:User', + 'Delete:User', + 'DeleteAny:User', + 'ResetPassword:User', + + 'Create:Category', + 'Edit:Category', + 'Delete:Category', + 'DeleteAny:Category', + 'ToggleStatus:Category', + + 'Create:Product', + 'Edit:Product', + 'Delete:Product', + 'DeleteAny:Product', + 'ToggleStatus:Product', + + 'Generate:Payroll', + 'Delete:Payroll', + 'DeleteAny:Payroll', + 'Pay:Payroll', + + 'Create:PayrollAdjustment', + 'Edit:PayrollAdjustment', + 'Delete:PayrollAdjustment', + 'DeleteAny:PayrollAdjustment', + + 'View:Setting', + 'Edit:Setting', + + 'View:Log', + + 'View:Activity', + ])->get(); + $admin->syncPermissions($adminPermissions); + } +} diff --git a/database/seeders/UserSeeder.php b/database/seeders/UserSeeder.php index 4ba9308..72b0522 100644 --- a/database/seeders/UserSeeder.php +++ b/database/seeders/UserSeeder.php @@ -13,7 +13,8 @@ class UserSeeder extends Seeder */ public function run(): void { - $user = User::updateOrCreate( + // Developer + $developer = User::updateOrCreate( ['username' => 'pangestu'], [ 'email' => 'info.pangestuyoga@gmail.com', @@ -21,7 +22,7 @@ public function run(): void ] ); - $user->profile()->updateOrCreate( + $developer->profile()->updateOrCreate( ['nik' => '3213051307900001'], [ 'full_name' => 'Yoga Pangestu', @@ -29,10 +30,37 @@ public function run(): void 'address' => 'Jl. Contoh No. 123', 'birth_place' => 'Jakarta', 'birth_date' => '1990-01-01', - 'base_salary' => 1500000, + 'base_salary' => 0, ] ); - User::factory(10)->create(); + $developer->assignRole('Developer'); + + // Owner + $owner = User::updateOrCreate( + ['username' => 'owner'], + [ + 'email' => 'owner@gmail.com', + 'password' => Hash::make('Minimal8@'), + ] + ); + + $owner->profile()->updateOrCreate( + ['nik' => '3213051307900002'], + [ + 'full_name' => 'Owner', + 'phone_number' => '082121212121', + 'address' => 'Jl. Contoh No. 123', + 'birth_place' => 'Jakarta', + 'birth_date' => '1990-01-01', + 'base_salary' => 0, + ] + ); + + $owner->assignRole('Owner'); + + User::factory(10)->create()->each(function ($u) { + $u->assignRole('Admin'); + }); } }