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

Commit 2e65cd4

Browse files
committed
Configurable response factory
PSR-17 response factory can be provided in configuration
1 parent 2257aac commit 2e65cd4

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

src/JwtAuthentication.php

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,14 +39,14 @@
3939
use InvalidArgumentException;
4040
use Exception;
4141
use Firebase\JWT\JWT;
42+
use Psr\Http\Message\ResponseFactoryInterface;
4243
use Psr\Http\Message\ServerRequestInterface;
4344
use Psr\Http\Message\ResponseInterface;
4445
use Psr\Http\Server\MiddlewareInterface;
4546
use Psr\Http\Server\RequestHandlerInterface;
4647
use Psr\Log\LoggerInterface;
4748
use Psr\Log\LogLevel;
4849
use RuntimeException;
49-
use Tuupola\Middleware\DoublePassTrait;
5050
use Tuupola\Http\Factory\ResponseFactory;
5151
use Tuupola\Middleware\JwtAuthentication\RequestMethodRule;
5252
use Tuupola\Middleware\JwtAuthentication\RequestPathRule;
@@ -85,7 +85,8 @@ final class JwtAuthentication implements MiddlewareInterface
8585
"ignore" => null,
8686
"before" => null,
8787
"after" => null,
88-
"error" => null
88+
"error" => null,
89+
"responseFactory" => null,
8990
];
9091

9192
public function __construct(array $options = [])
@@ -139,7 +140,8 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
139140
$token = $this->fetchToken($request);
140141
$decoded = $this->decodeToken($token);
141142
} catch (RuntimeException | DomainException $exception) {
142-
$response = (new ResponseFactory)->createResponse(401);
143+
$factory = $this->options['responseFactory'] ?? new ResponseFactory;
144+
$response = $factory->createResponse(401);
143145
return $this->processError($response, [
144146
"message" => $exception->getMessage(),
145147
"uri" => (string)$request->getUri()
@@ -158,7 +160,6 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
158160

159161
/* Modify $request before calling next middleware. */
160162
if (is_callable($this->options["before"])) {
161-
$response = (new ResponseFactory)->createResponse(200);
162163
$beforeRequest = $this->options["before"]($request, $params);
163164
if ($beforeRequest instanceof ServerRequestInterface) {
164165
$request = $beforeRequest;
@@ -452,4 +453,12 @@ private function rules(array $rules): void
452453
$this->rules->push($callable);
453454
}
454455
}
456+
457+
/**
458+
* Set the response factory.
459+
*/
460+
private function responseFactory(ResponseFactoryInterface $factory = null): void
461+
{
462+
$this->options["responseFactory"] = $factory;
463+
}
455464
}

0 commit comments

Comments
 (0)