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

HttpHeaderAuth::__construct()   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 1 Features 0
Metric Value
cc 1
eloc 1
c 1
b 1
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\ResponseInterface;
5
use Psr\Http\Message\ServerRequestInterface;
6
use Yiisoft\Yii\Web\User\IdentityInterface;
7
use Yiisoft\Yii\Web\User\IdentityRepositoryInterface;
8
9
/**
10
 * HttpHeaderAuth is an action filter that supports HTTP authentication through HTTP Headers.
11
 *
12
 * The default implementation of HttpHeaderAuth uses the [[Yiisoft\Yii\Web\User\IdentityRepositoryInterface::findIdentityByToken()|findIdentityByToken()]]
13
 * method of the `user` application component and passes the value of the `X-Api-Key` header. This implementation is used
14
 * for authenticating API clients.
15
 */
16
class HttpHeaderAuth implements AuthInterface
17
{
18
    private const HEADER_NAME = 'X-Api-Key';
19
    /**
20
     * @var string the HTTP header name
21
     */
22
    protected $headerName = self::HEADER_NAME;
23
24
    /**
25
     * @var string a pattern to use to extract the HTTP authentication value
26
     */
27
    protected $pattern;
28
29
    /**
30
     * @var IdentityRepositoryInterface
31
     */
32
    protected $identityRepository;
33
34
    public function __construct(IdentityRepositoryInterface $identityRepository)
35
    {
36
        $this->identityRepository = $identityRepository;
37
    }
38
39
    public function authenticate(ServerRequestInterface $request): ?IdentityInterface
40
    {
41
        $authToken = $this->getAuthToken($request);
42
        if ($authToken !== null) {
43
44
            return $this->identityRepository->findIdentityByToken($authToken, get_class($this));
45
        }
46
47
        return null;
48
    }
49
50
    public function challenge(ResponseInterface $response): ResponseInterface
51
    {
52
        return $response;
53
    }
54
55
    public function setHeaderName(string $name): void
56
    {
57
        $this->headerName = $name;
58
    }
59
60
    public function setPattern(string $pattern): void
61
    {
62
        $this->pattern = $pattern;
63
    }
64
65
    protected function getAuthToken(ServerRequestInterface $request): ?string
66
    {
67
        $authHeaders = $request->getHeader($this->headerName);
68
        $authHeader = \reset($authHeaders);
69
        if ($authHeader !== null) {
70
            if ($this->pattern !== null) {
71
                if (preg_match($this->pattern, $authHeader, $matches)) {
72
                    $authHeader = $matches[1];
73
                } else {
74
                    return null;
75
                }
76
            }
77
            return $authHeader;
78
        }
79
        return null;
80
    }
81
}