Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Commit

Permalink
Configurable response factory
Browse files Browse the repository at this point in the history
PSR-17 response factory can be provided in configuration
  • Loading branch information
dakujem committed Oct 29, 2019
1 parent 2257aac commit 2e65cd4
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/JwtAuthentication.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@
use InvalidArgumentException;
use Exception;
use Firebase\JWT\JWT;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use RuntimeException;
use Tuupola\Middleware\DoublePassTrait;
use Tuupola\Http\Factory\ResponseFactory;
use Tuupola\Middleware\JwtAuthentication\RequestMethodRule;
use Tuupola\Middleware\JwtAuthentication\RequestPathRule;
Expand Down Expand Up @@ -85,7 +85,8 @@ final class JwtAuthentication implements MiddlewareInterface
"ignore" => null,
"before" => null,
"after" => null,
"error" => null
"error" => null,
"responseFactory" => null,
];

public function __construct(array $options = [])
Expand Down Expand Up @@ -139,7 +140,8 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
$token = $this->fetchToken($request);
$decoded = $this->decodeToken($token);
} catch (RuntimeException | DomainException $exception) {
$response = (new ResponseFactory)->createResponse(401);
$factory = $this->options['responseFactory'] ?? new ResponseFactory;
$response = $factory->createResponse(401);
return $this->processError($response, [
"message" => $exception->getMessage(),
"uri" => (string)$request->getUri()
Expand All @@ -158,7 +160,6 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface

/* Modify $request before calling next middleware. */
if (is_callable($this->options["before"])) {
$response = (new ResponseFactory)->createResponse(200);
$beforeRequest = $this->options["before"]($request, $params);
if ($beforeRequest instanceof ServerRequestInterface) {
$request = $beforeRequest;
Expand Down Expand Up @@ -452,4 +453,12 @@ private function rules(array $rules): void
$this->rules->push($callable);
}
}

/**
* Set the response factory.
*/
private function responseFactory(ResponseFactoryInterface $factory = null): void
{
$this->options["responseFactory"] = $factory;
}
}

0 comments on commit 2e65cd4

Please sign in to comment.