-
app/Services/ForRouteGate.php
Open in GitHubuse App\Exceptions\MissingModel; use App\Models\User; use App\Providers\AppServiceProvider; use Illuminate\Support\Str; class ForRouteGate { public function __invoke(User $user, $permissionName = '', $model = null) { if ($user->isAdmin()) { return true; } if ($permissionName === '' || $permissionName === null) { return false; } if (! Str::contains($permissionName, ['show', 'edit', 'delete'])) { return $user->hasPermission($permissionName); } return $this->forOwner($user, $permissionName, $model); } public function forOwner($user, $permissionName, $model) { if ($model === null) { throw new MissingModel(); } $ownerField = AppServiceProvider::OWNER_FIELD; if ($model->$ownerField === null) { return $user->hasPermission($permissionName); } return $user->isModelOwner($permissionName, $model); } }
-
app/Providers/AuthServiceProvider.php
Open in GitHubuse App\Services\ForRouteGate; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Support\Facades\Gate; class AuthServiceProvider extends ServiceProvider { protected $policies = []; public function boot() { Gate::define('for-route', ForRouteGate::class); $this->registerPolicies(); } }
-
app/Http/Middleware/Authorization.php
Open in GitHubuse Illuminate\Container\Container; use Illuminate\Support\Facades\Gate; use Livewire\ImplicitRouteBinding; class Authorization { public function handle($request, $next) { $component = $request->route()->action['controller']; $model = (new ImplicitRouteBinding(new Container()))->resolveComponentProps( $request->route(), new $component() ); Gate::authorize('for-route', [$request->route()->getName(), $model->first() ?? null]); return $next($request); } }