Passed
Pull Request — master (#116)
by Rustam
02:07
created

HttpBasicAuth::authenticate()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 5
eloc 9
c 2
b 1
f 0
nc 4
nop 1
dl 0
loc 17
ccs 0
cts 13
cp 0
crap 30
rs 9.6111
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
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 [[\yii\web\User::loginByAccessToken()]]
44
     * method will be called to authenticate and login the user.
45
     */
46
    public $auth;
47
    private $identityRepository;
48
49
    public function __construct(IdentityRepositoryInterface $identityRepository)
50
    {
51
        $this->identityRepository = $identityRepository;
52
    }
53
54
    public function authenticate(ServerRequestInterface $request): ?IdentityInterface
55
    {
56
        [$username, $password] = $this->getAuthCredentials($request);
57
58
        if ($this->auth) {
59
            if ($username !== null || $password !== null) {
60
                $identity = call_user_func($this->auth, $username, $password);
61
62
                return $identity;
63
            }
64
        } elseif ($username !== null) {
65
            $identity = $this->identityRepository->findIdentityByToken($username, get_class($this));
66
67
            return $identity;
68
        }
69
70
        return null;
71
    }
72
73
    public function challenge(ResponseInterface $response): ResponseInterface
74
    {
75
        return $response->withHeader('WWW-Authenticate', "Basic realm=\"{$this->realm}\"");
76
    }
77
78
    private function getAuthCredentials(ServerRequestInterface $request)
79
    {
80
        $username = $_SERVER['PHP_AUTH_USER'] ?? null;
81
        $password = $_SERVER['PHP_AUTH_PW'] ?? null;
82
        if ($username !== null || $password !== null) {
83
            return [$username, $password];
84
        }
85
86
        /*
87
         * Apache with php-cgi does not pass HTTP Basic authentication to PHP by default.
88
         * To make it work, add the following line to to your .htaccess file:
89
         *
90
         * RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
91
         */
92
        $headers = $request->getHeader('Authorization');
93
        $authToken = !empty($headers) ? \reset($headers) : $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
94
        if ($authToken !== null && strncasecmp($authToken, 'basic', 5) === 0) {
95
            $parts = array_map(static function ($value) {
96
                return strlen($value) === 0 ? null : $value;
97
            }, explode(':', base64_decode(mb_substr($authToken, 6)), 2));
98
99
            if (\count($parts) < 2) {
100
                return [$parts[0], null];
101
            }
102
103
            return $parts;
104
        }
105
106
        return [null, null];
107
    }
108
}
109