Completed
Push — master ( 99c4e8...3c79d6 )
by Alexander
02:19
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 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\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 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
            return $this->identityRepository->findIdentityByToken($authToken, get_class($this));
44
        }
45
46
        return null;
47
    }
48
49
    public function challenge(ResponseInterface $response): ResponseInterface
50
    {
51
        return $response;
52
    }
53
54
    public function setHeaderName(string $name): void
55
    {
56
        $this->headerName = $name;
57
    }
58
59
    public function setPattern(string $pattern): void
60
    {
61
        $this->pattern = $pattern;
62
    }
63
64
    protected function getAuthToken(ServerRequestInterface $request): ?string
65
    {
66
        $authHeaders = $request->getHeader($this->headerName);
67
        $authHeader = \reset($authHeaders);
68
        if ($authHeader !== null) {
69
            if ($this->pattern !== null) {
70
                if (preg_match($this->pattern, $authHeader, $matches)) {
71
                    $authHeader = $matches[1];
72
                } else {
73
                    return null;
74
                }
75
            }
76
            return $authHeader;
77
        }
78
        return null;
79
    }
80
}
81