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

AuthMiddleware   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
c 1
b 0
f 0
dl 0
loc 58
ccs 0
cts 37
cp 0
rs 10
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setRequestName() 0 3 1
A isOptional() 0 10 3
A process() 0 18 3
A setOptional() 0 3 1
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
}