From 869e8c6ff0d535132a45b122726ea8270cde7fde Mon Sep 17 00:00:00 2001 From: Hans Pagel <mail@hanspagel.com> Date: Thu, 12 Sep 2024 17:13:04 +0200 Subject: [PATCH] feat: add a viewScalar gate to add custom authorization --- README.md | 25 +++++++++++++++++++++++++ src/Controllers/ScalarController.php | 5 +++++ src/ScalarServiceProvider.php | 10 ++++++++++ 3 files changed, 40 insertions(+) diff --git a/README.md b/README.md index c7cb992..b2f6259 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,31 @@ return [ ] ``` +## Authorization + +The Scalar API reference may be accessed via the /scalar route. By default, everyone will be able to access this route. However, within your App\Providers\AppServiceProvider.php file, you can overwrite the gate definition. This authorization gate controls access to Scalar in non-local environments. You are free to modify this gate as needed to restrict access to your Horizon installation: + +```php +<?php + +namespace App\Providers; + +use Illuminate\Support\Facades\Gate; +use Illuminate\Support\ServiceProvider; + +class AppServiceProvider extends ServiceProvider +{ + public function boot(): void + { + Gate::define('viewScalar', function ($user) { + return in_array($user->email, [ + // + ]); + }); + } +} +``` + ## Testing ```bash diff --git a/src/Controllers/ScalarController.php b/src/Controllers/ScalarController.php index f47862b..51dd4f7 100644 --- a/src/Controllers/ScalarController.php +++ b/src/Controllers/ScalarController.php @@ -3,11 +3,16 @@ namespace Scalar\Controllers; use Illuminate\Routing\Controller; +use Illuminate\Support\Facades\Gate; class ScalarController extends Controller { public function __invoke() { + if (! Gate::check('viewScalar') && ! app()->environment('local')) { + return abort(403); + } + return view('scalar::reference'); } } diff --git a/src/ScalarServiceProvider.php b/src/ScalarServiceProvider.php index 00c1d69..8bb7e6e 100644 --- a/src/ScalarServiceProvider.php +++ b/src/ScalarServiceProvider.php @@ -2,11 +2,21 @@ namespace Scalar; +use Illuminate\Support\Facades\Gate; use Spatie\LaravelPackageTools\Package; use Spatie\LaravelPackageTools\PackageServiceProvider; class ScalarServiceProvider extends PackageServiceProvider { + public function boot() + { + parent::boot(); + + Gate::define('viewScalar', function ($user = null) { + return true; + }); + } + public function configurePackage(Package $package): void { $package