From cdae22ab085067ce2dc50b5b27c1e3455c4bef1a Mon Sep 17 00:00:00 2001 From: LT Date: Sun, 29 Oct 2023 12:29:32 +0300 Subject: [PATCH] init --- .editorconfig | 9 ++ .gitignore | 8 ++ LICENCE.md | 9 ++ README.md | 60 +++++++++ composer.json | 56 ++++++++ ...reate_moonshine_user_permissions_table.php | 25 ++++ .../views/components/permissions.blade.php | 9 ++ src/Components/Permissions.php | 126 ++++++++++++++++++ src/Http/Controllers/PermissionController.php | 38 ++++++ src/Http/Requests/PermissionFormRequest.php | 33 +++++ src/Models/MoonshineUser.php | 13 ++ src/Models/MoonshineUserPermission.php | 32 +++++ src/PermissionsServiceProvider.php | 43 ++++++ src/Traits/HasMoonShinePermissions.php | 26 ++++ src/Traits/WithPermissions.php | 45 +++++++ 15 files changed, 532 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 LICENCE.md create mode 100644 README.md create mode 100644 composer.json create mode 100644 database/migrations/2023_01_20_173629_create_moonshine_user_permissions_table.php create mode 100644 resources/views/components/permissions.blade.php create mode 100644 src/Components/Permissions.php create mode 100644 src/Http/Controllers/PermissionController.php create mode 100644 src/Http/Requests/PermissionFormRequest.php create mode 100644 src/Models/MoonshineUser.php create mode 100644 src/Models/MoonshineUserPermission.php create mode 100644 src/PermissionsServiceProvider.php create mode 100644 src/Traits/HasMoonShinePermissions.php create mode 100644 src/Traits/WithPermissions.php diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..fcdf61e --- /dev/null +++ b/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cb96071 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.idea +vendor +composer.lock +node_modules +.phpunit.result.cache +.php-cs-fixer.cache +app +reports diff --git a/LICENCE.md b/LICENCE.md new file mode 100644 index 0000000..8ab2763 --- /dev/null +++ b/LICENCE.md @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Danil Shutsky + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4974297 --- /dev/null +++ b/README.md @@ -0,0 +1,60 @@ +## MoonShine Permission + +### Requirements + +- MoonShine v2.0+ + +### Installation + +```shell +composer require moonshine/permissions +``` + +```shell +php artisan migrate +``` + +### Get started + +1. Change MoonShineUser model in app/moonshine.php + +```php +use MoonShine\Permissions\Models\MoonshineUser; + +return [ + // ... + 'auth' => [ + // ... + 'providers' => [ + 'moonshine' => [ + 'driver' => 'eloquent', + 'model' => MoonshineUser::class, + ], + ], + ], + // ... +]; +``` + +Or add trait HasChangeLog to user model + +```php +use MoonShine\Permissions\Traits\HasMoonShinePermissions; + +class MoonShineUser extends Model +{ + use HasMoonShinePermissions; +} +``` + +2. Add trait to resource + +```php +use MoonShine\Permissions\Traits\WithPermissions; + +class PostResource extends ModelResource +{ + use WithPermissions; +} +``` + diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..4d2b492 --- /dev/null +++ b/composer.json @@ -0,0 +1,56 @@ +{ + "name": "moonshine/permissions", + "description": "User permissions for MoonShine", + "keywords": ["permissions", "moonshine"], + "type": "library", + "homepage": "https://moonshine-laravel.com", + "license": "MIT", + "support": { + "issues": "https://github.com/moonshine-software/permissions/issues", + "source": "https://github.com/moonshine-software/permissions" + }, + "authors": [ + { + "name": "Danil Shutsky", + "email": "thecutcode@gmail.com", + "homepage": "https://moonshine-laravel.com" + } + ], + "require": { + "php": "^8.1|^8.2", + "ext-curl": "*", + "ext-json": "*" + }, + "require-dev": { + "phpunit/phpunit": "^9.5.8", + "mockery/mockery": "^1.4.4", + "phpstan/phpstan": "^1.4.7", + "orchestra/testbench": "^4.0|^5.0|^6.0|^7.0|^8.0", + "brianium/paratest": "^6.8" + }, + "autoload": { + "psr-4": { + "MoonShine\\Permissions\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "MoonShine\\Permissions\\Tests\\": "tests/", + "MoonShine\\Permissions\\Database\\Factories\\": "database/factories/" + } + }, + "conflict": { + "moonshine/moonshine": "<2.0" + }, + "scripts": { + "test": "vendor/bin/phpunit", + "format": "vendor/bin/php-cs-fixer fix --allow-risky=yes" + }, + "extra": { + "laravel": { + "providers": [ + "MoonShine\\Permissions\\PermissionsServiceProvider" + ] + } + } +} diff --git a/database/migrations/2023_01_20_173629_create_moonshine_user_permissions_table.php b/database/migrations/2023_01_20_173629_create_moonshine_user_permissions_table.php new file mode 100644 index 0000000..31bd689 --- /dev/null +++ b/database/migrations/2023_01_20_173629_create_moonshine_user_permissions_table.php @@ -0,0 +1,25 @@ +id(); + + $table->foreignId('moonshine_user_id'); + + $table->json('permissions'); + + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('moonshine_user_permissions'); + } +}; diff --git a/resources/views/components/permissions.blade.php b/resources/views/components/permissions.blade.php new file mode 100644 index 0000000..451d7b2 --- /dev/null +++ b/resources/views/components/permissions.blade.php @@ -0,0 +1,9 @@ +@if($item->exists) + + + + {{ $label }} + + + {{ $form->render() }} +@endif diff --git a/src/Components/Permissions.php b/src/Components/Permissions.php new file mode 100644 index 0000000..f99106d --- /dev/null +++ b/src/Components/Permissions.php @@ -0,0 +1,126 @@ +setResource($resource); + $this->setLabel($label); + } + + public function getItem(): Model + { + return $this->getResource()->getItemOrInstance(); + } + + public function getForm(): FormBuilder + { + $url = $this->getResource() + ->route('permissions', $this->getItem()->getKey()); + + $elements = []; + $values = []; + $all = true; + + foreach (moonshine()->getResources() as $resource) { + $checkboxes = []; + $class = 'ps_' . class_basename($resource::class); + $allSections = true; + + foreach ($resource->gateAbilities() as $ability) { + $values['permissions'][$resource::class][$ability] = $this->getItem()->isHavePermission( + $resource::class, + $ability + ); + + if (! $values['permissions'][$resource::class][$ability]) { + $allSections = false; + $all = false; + } + + $checkboxes[] = Switcher::make( + $ability, + "permissions." . $resource::class . ".$ability" + ) + ->customAttributes(['class' => 'permission_switcher ' . $class]) + ->setName("permissions[" . $resource::class . "][$ability]"); + } + + $elements[] = Column::make([ + Switcher::make($resource->title())->customAttributes([ + 'class' => 'permission_switcher_section', + '@change' => "document + .querySelectorAll('.$class') + .forEach((el) => {el.checked = parseInt(event.target.value); el.dispatchEvent(new Event('change'))})", + ])->setValue($allSections)->hint('Toggle off/on all'), + + ...$checkboxes, + Divider::make(), + ])->columnSpan(6); + } + + return FormBuilder::make($url) + ->fields([ + Switcher::make('All')->customAttributes([ + '@change' => <<<'JS' + document + .querySelectorAll('.permission_switcher, .permission_switcher_section') + .forEach((el) => {el.checked = parseInt(event.target.value); el.dispatchEvent(new Event('change'))}) + JS + , + ])->setValue($all), + Divider::make(), + Grid::make( + $elements + ), + ]) + ->fill($values) + ->submit(__('moonshine::ui.save')); + } + + protected function viewData(): array + { + return [ + 'label' => $this->label(), + 'form' => $this->getItem()?->exists + ? $this->getForm() + : '', + 'item' => $this->getItem(), + 'resource' => $this->getResource(), + ]; + } +} diff --git a/src/Http/Controllers/PermissionController.php b/src/Http/Controllers/PermissionController.php new file mode 100644 index 0000000..dde7f5d --- /dev/null +++ b/src/Http/Controllers/PermissionController.php @@ -0,0 +1,38 @@ +getResource() + ->getItem(); + + if (! $request->has('permissions')) { + $item->moonshineUserPermission()->delete(); + } else { + MoonshineUserPermission::query()->updateOrCreate( + ['moonshine_user_id' => $item->getKey()], + request() + ->merge(['moonshine_user_id' => $item->getKey()]) + ->only(['moonshine_user_id', 'permissions']) + ); + } + + $this->toast( + __('moonshine::ui.saved'), + 'success' + ); + + return back(); + } +} diff --git a/src/Http/Requests/PermissionFormRequest.php b/src/Http/Requests/PermissionFormRequest.php new file mode 100644 index 0000000..909e9a1 --- /dev/null +++ b/src/Http/Requests/PermissionFormRequest.php @@ -0,0 +1,33 @@ +getResource()->getActiveActions(), + true + )) { + return false; + } + + return $this->getResource()->can('update'); + } + + /** + * @return array{permissions: string[]} + */ + public function rules(): array + { + return [ + 'permissions' => ['array'], + ]; + } +} diff --git a/src/Models/MoonshineUser.php b/src/Models/MoonshineUser.php new file mode 100644 index 0000000..6eb9e65 --- /dev/null +++ b/src/Models/MoonshineUser.php @@ -0,0 +1,13 @@ + 'collection', + ]; + + public function moonshineUser(): BelongsTo + { + $model = MoonShineAuth::model(); + + return $this->belongsTo( + $model::class, + 'moonshine_user_id', + $model->getKeyName(), + ); + } +} diff --git a/src/PermissionsServiceProvider.php b/src/PermissionsServiceProvider.php new file mode 100644 index 0000000..1153a81 --- /dev/null +++ b/src/PermissionsServiceProvider.php @@ -0,0 +1,43 @@ +loadMigrationsFrom(__DIR__ . '/../database/migrations'); + $this->loadViewsFrom(__DIR__ . '/../resources/views', 'moonshine-permissions'); + + MoonShine::defineAuthorization( + static function (ResourceContract $resource, Model $user, string $ability): bool { + $hasUserPermissions = in_array( + HasMoonShinePermissions::class, + class_uses_recursive($user), + true + ); + + if (! $hasUserPermissions) { + return true; + } + + if (! $user->moonshineUserPermission) { + return true; + } + + return $user->isHavePermission( + $resource::class, + $ability + ); + } + ); + } +} diff --git a/src/Traits/HasMoonShinePermissions.php b/src/Traits/HasMoonShinePermissions.php new file mode 100644 index 0000000..2617f95 --- /dev/null +++ b/src/Traits/HasMoonShinePermissions.php @@ -0,0 +1,26 @@ +moonshineUserPermission?->permissions[$resourceClass][$ability]); + } + + public function moonshineUserPermission(): HasOne + { + return $this->hasOne( + MoonshineUserPermission::class, + 'moonshine_user_id', + MoonShineAuth::model()?->getKeyName() ?? 'id' + ); + } +} diff --git a/src/Traits/WithPermissions.php b/src/Traits/WithPermissions.php new file mode 100644 index 0000000..6ac6ed7 --- /dev/null +++ b/src/Traits/WithPermissions.php @@ -0,0 +1,45 @@ +getPages() + ->findByType(PageType::FORM) + ?->pushToLayer( + Layer::BOTTOM, + Permissions::make( + 'Permissions', + $this + )->canSee( + fn() => auth()->user()->moonshine_user_role_id === MoonshineUserRole::DEFAULT_ROLE_ID + ) + ); + } + + protected function resolveRoutes(): void + { + parent::resolveRoutes(); + + Route::post( + 'permissions/{resourceItem}', + PermissionController::class + )->name('permissions'); + } +}