Completed
Pull Request — master (#116)
by Rustam
01:53
created

AuthMiddleware::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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