Passed
Pull Request — master (#116)
by Rustam
01:56
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 `$_SERVER['PHP_AUTH_USER']` and `$_SERVER['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
    public $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
    public $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
    private function getAuthCredentials(ServerRequestInterface $request): array
82
    {
83
        $username = $_SERVER['PHP_AUTH_USER'] ?? null;
84
        $password = $_SERVER['PHP_AUTH_PW'] ?? null;
85
        if ($username !== null || $password !== null) {
86
            return [$username, $password];
87
        }
88
89
        /*
90
         * Apache with php-cgi does not pass HTTP Basic authentication to PHP by default.
91
         * To make it work, add the following line to to your .htaccess file:
92
         *
93
         * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
94
         */
95
        $headers = $request->getHeader('Authorization');
96
        $authToken = !empty($headers) ? \reset($headers) : $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
97
        if ($authToken !== null && strncasecmp($authToken, 'basic', 5) === 0) {
98
            $parts = array_map(static function ($value) {
99
                return strlen($value) === 0 ? null : $value;
100
            }, explode(':', base64_decode(mb_substr($authToken, 6)), 2));
101
102
            if (\count($parts) < 2) {
103
                return [$parts[0], null];
104
            }
105
106
            return $parts;
107
        }
108
109
        return [null, null];
110
    }
111
}
112