diff --git a/migrations/2023_09_28_create_oauth_scopes_table.php b/migrations/2023_09_28_create_oauth_scopes_table.php index 6ab8913..aabda7a 100644 --- a/migrations/2023_09_28_create_oauth_scopes_table.php +++ b/migrations/2023_09_28_create_oauth_scopes_table.php @@ -11,6 +11,8 @@ return [ $schema->create('oauth_scopes', function (Blueprint $table) { $table->increments('id'); $table->string('scope', 80); + $table->string('resource_path', 500); + $table->string('method', 20); $table->boolean('is_default')->nullable(); }); }, diff --git a/src/Middlewares/ResourceScopeMiddleware.php b/src/Middlewares/ResourceScopeMiddleware.php new file mode 100644 index 0000000..d42de10 --- /dev/null +++ b/src/Middlewares/ResourceScopeMiddleware.php @@ -0,0 +1,63 @@ +getUri()->getPath(); + $token = Arr::get($request->getQueryParams(), 'access_token', ''); + if ($token !== '' && $scope = Scope::get_path_scope($path)) { + if (strtolower($request->getMethod()) === strtolower($scope->method)) { + try { + $oauth = new OAuth(); + $server = $oauth->server(); + $request = $oauth->request(); + if (!$server->verifyResourceRequest($request::createFromGlobals(), null, $scope->scope)) { + $server->getResponse()->send('json'); + die; + } + /*$error = new ResponseBag('422', [ + [ + 'status' => '422', + 'code' => 'validation_error', + 'source' => [ + 'pointer' => $path, + ], + 'detail' => 'Yikes! The access token don\'t has the scope.', + ], + ]); + $document = new Document(); + $document->setErrors($error->getErrors()); + + return new JsonApiResponse($document, $error->getStatus());*/ + } catch (ValidationException $exception) { + + $handler = resolve(IlluminateValidationExceptionHandler::class); + + $error = $handler->handle($exception); + + return (new JsonApiFormatter())->format($error, $request); + } + } + } + + return $handler->handle($request); + } +} diff --git a/src/Models/Scope.php b/src/Models/Scope.php index e5d108e..ae67779 100644 --- a/src/Models/Scope.php +++ b/src/Models/Scope.php @@ -7,4 +7,10 @@ use Flarum\Database\AbstractModel; class Scope extends AbstractModel { protected $table = 'oauth_scopes'; + + static public function get_path_scope($path = '') + { + return self::where('resource_path', 'like', $path . '%')->first(); + // return $this->where('resource_path', $path)->first(); + } }