|
1
|
|
|
<?php |
|
2
|
|
|
namespace Yiisoft\Yii\Web\Auth; |
|
3
|
|
|
|
|
4
|
|
|
use Psr\Http\Message\ResponseFactoryInterface; |
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
7
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
8
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
9
|
|
|
use Yiisoft\Strings\StringHelper; |
|
10
|
|
|
|
|
11
|
|
|
final class AuthMiddleware implements MiddlewareInterface |
|
12
|
|
|
{ |
|
13
|
|
|
private const REQUEST_NAME = 'auth_user'; |
|
14
|
|
|
|
|
15
|
|
|
private $requestName = self::REQUEST_NAME; |
|
16
|
|
|
private $responseFactory; |
|
17
|
|
|
private $authenticator; |
|
18
|
|
|
private $optional = []; |
|
19
|
|
|
|
|
20
|
|
|
public function __construct(ResponseFactoryInterface $responseFactory, AuthInterface $authenticator) |
|
21
|
|
|
{ |
|
22
|
|
|
$this->responseFactory = $responseFactory; |
|
23
|
|
|
$this->authenticator = $authenticator; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
27
|
|
|
{ |
|
28
|
|
|
$identity = $this->authenticator->authenticate($request); |
|
29
|
|
|
$request->withAttribute($this->requestName, $identity); |
|
30
|
|
|
|
|
31
|
|
|
if ($identity === null && !$this->isOptional($request)) { |
|
32
|
|
|
$response = $this->responseFactory->createResponse(401); |
|
33
|
|
|
$response = $this->authenticator->challenge($response); |
|
34
|
|
|
$response->getBody()->write('Your request was made with invalid credentials.'); |
|
35
|
|
|
|
|
36
|
|
|
return $response; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
return $handler->handle($request); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
public function setRequestName(string $name): void |
|
43
|
|
|
{ |
|
44
|
|
|
$this->requestName = $name; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function setOptional(array $optional): void |
|
48
|
|
|
{ |
|
49
|
|
|
$this->optional = $optional; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Checks, whether authentication is optional for the given action. |
|
54
|
|
|
*/ |
|
55
|
|
|
private function isOptional(ServerRequestInterface $request): bool |
|
56
|
|
|
{ |
|
57
|
|
|
$path = $request->getUri()->getPath(); |
|
58
|
|
|
foreach ($this->optional as $pattern) { |
|
59
|
|
|
if (StringHelper::matchWildcard($pattern, $path)) { |
|
60
|
|
|
return true; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
return false; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|