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

HttpBearerAuth   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 41
ccs 0
cts 21
cp 0
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A challenge() 0 3 1
A __construct() 0 5 1
A authenticate() 0 9 2
A setRealm() 0 3 1
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
final class HttpBearerAuth implements AuthInterface
17
{
18
    use HttpHeaderAuthTrait;
19
    private const HEADER_NAME = 'Authorization';
20
    private const PATTERN = '/^Bearer\s+(.*?)$/';
21
22
    /**
23
     * @var string the HTTP authentication realm
24
     */
25
    private $realm = 'api';
26
    /**
27
     * @var IdentityRepositoryInterface
28
     */
29
    private $identityRepository;
30
31
    public function __construct(IdentityRepositoryInterface $identityRepository)
32
    {
33
        $this->identityRepository = $identityRepository;
34
        $this->header = self::HEADER_NAME;
35
        $this->pattern = self::PATTERN;
36
    }
37
38
    public function authenticate(ServerRequestInterface $request): ?IdentityInterface
39
    {
40
        $authToken = $this->getAuthToken($request);
41
        if ($authToken !== null) {
42
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->withHeader('WWW-Authenticate', "{$this->header} realm=\"{$this->realm}\"");
52
    }
53
54
    public function setRealm(string $realm): void
55
    {
56
        $this->realm = $realm;
57
    }
58
}
59