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

HttpBasicAuth::__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
 * HttpBasicAuth is an action filter that supports the HTTP Basic authentication method.
11
 *
12
 * > Tip: In case authentication does not work like expected, make sure your web server passes
13
 * username and password to `$request->getServerParams()['PHP_AUTH_USER']` and `$request->getServerParams()['PHP_AUTH_PW']` variables.
14
 * If you are using Apache with PHP-CGI, you might need to add this line to your `.htaccess` file:
15
 * ```
16
 * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
17
 * ```
18
 */
19
final class HttpBasicAuth implements AuthInterface
20
{
21
    /**
22
     * @var string the HTTP authentication realm
23
     */
24
    private $realm = 'api';
25
    /**
26
     * @var callable a PHP callable that will authenticate the user with the HTTP basic auth information.
27
     * The callable receives a username and a password as its parameters. It should return an identity object
28
     * that matches the username and password. Null should be returned if there is no such identity.
29
     * The callable will be called only if current user is not authenticated.
30
     *
31
     * The following code is a typical implementation of this callable:
32
     *
33
     * ```php
34
     * function ($username, $password) {
35
     *     return \app\models\User::findOne([
36
     *         'username' => $username,
37
     *         'password' => $password,
38
     *     ]);
39
     * }
40
     * ```
41
     *
42
     * If this property is not set, the username information will be considered as an access token
43
     * while the password information will be ignored. The [[Yiisoft\Yii\Web\User\IdentityRepositoryInterface::findIdentityByToken()]]
44
     * method will be called to authenticate and login the user.
45
     */
46
    private $auth;
47
    /**
48
     * @var IdentityRepositoryInterface
49
     */
50
    private $identityRepository;
51
52
    public function __construct(IdentityRepositoryInterface $identityRepository)
53
    {
54
        $this->identityRepository = $identityRepository;
55
    }
56
57
    public function authenticate(ServerRequestInterface $request): ?IdentityInterface
58
    {
59
        [$username, $password] = $this->getAuthCredentials($request);
60
61
        if ($this->auth) {
62
            if ($username !== null || $password !== null) {
63
                $identity = \call_user_func($this->auth, $username, $password);
64
65
                return $identity;
66
            }
67
        } elseif ($username !== null) {
68
            $identity = $this->identityRepository->findIdentityByToken($username, get_class($this));
69
70
            return $identity;
71
        }
72
73
        return null;
74
    }
75
76
    public function challenge(ResponseInterface $response): ResponseInterface
77
    {
78
        return $response->withHeader('WWW-Authenticate', "Basic realm=\"{$this->realm}\"");
79
    }
80
81
    public function setAuth(callable $auth): void
82
    {
83
        $this->auth = $auth;
84
    }
85
86
    public function setRealm(string $realm): void
87
    {
88
        $this->realm = $realm;
89
    }
90
91
    private function getAuthCredentials(ServerRequestInterface $request): array
92
    {
93
        $username = $request->getServerParams()['PHP_AUTH_USER'] ?? null;
94
        $password = $request->getServerParams()['PHP_AUTH_PW'] ?? null;
95
        if ($username !== null || $password !== null) {
96
            return [$username, $password];
97
        }
98
99
        /*
100
         * Apache with php-cgi does not pass HTTP Basic authentication to PHP by default.
101
         * To make it work, add the following line to to your .htaccess file:
102
         *
103
         * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
104
         */
105
        $headers = $request->getHeader('Authorization');
106
        $authToken = !empty($headers)
107
            ? \reset($headers)
108
            : $request->getServerParams()['REDIRECT_HTTP_AUTHORIZATION'] ?? null;
109
        if ($authToken !== null && strncasecmp($authToken, 'basic', 5) === 0) {
110
            $parts = array_map(static function ($value) {
111
                return strlen($value) === 0 ? null : $value;
112
            }, explode(':', base64_decode(mb_substr($authToken, 6)), 2));
113
114
            if (\count($parts) < 2) {
115
                return [$parts[0], null];
116
            }
117
118
            return $parts;
119
        }
120
121
        return [null, null];
122
    }
123
}
124