Passed
Pull Request — master (#116)
by Rustam
01:56
created

AuthMiddleware::setRequestName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
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
        if ($this->isOptional($request)) {
29
            return $handler->handle($request);
30
        }
31
        $identity = $this->authenticator->authenticate($request);
32
33
        if ($identity === null) {
34
            $response = $this->responseFactory->createResponse(401);
35
            $response = $this->authenticator->challenge($response);
36
            $response->getBody()->write('Your request was made with invalid credentials.');
37
38
            return $response;
39
        }
40
41
        $request->withAttribute($this->requestName, $identity);
42
43
        return $handler->handle($request);
44
    }
45
46
    public function setRequestName(string $name): void
47
    {
48
        $this->requestName = $name;
49
    }
50
51
    public function setOptional(array $optional): void
52
    {
53
        $this->optional = $optional;
54
    }
55
56
    /**
57
     * Checks, whether authentication is optional for the given action.
58
     */
59
    private function isOptional(ServerRequestInterface $request): bool
60
    {
61
        $path = $request->getUri()->getPath();
62
        foreach ($this->optional as $pattern) {
63
            if (StringHelper::matchWildcard($pattern, $path)) {
64
                return true;
65
            }
66
        }
67
68
        return false;
69
    }
70
}