Completed
Push — master ( ba7c5d...c3b626 )
by Julián
02:08
created

BasicAuth::isExcluded()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 9.2
cc 4
eloc 6
nc 3
nop 1
1
<?php
2
/**
3
 * Effortless maintenance management (http://juliangut.com/janitor)
4
 *
5
 * @link https://github.com/juliangut/janitor for the canonical source repository
6
 *
7
 * @license https://github.com/juliangut/janitor/blob/master/LICENSE
8
 */
9
10
namespace Janitor\Excluder;
11
12
use Janitor\Excluder as ExcluderInterface;
13
use Psr\Http\Message\ServerRequestInterface;
14
15
/**
16
 * Maintenance excluder by Basic Authorization
17
 */
18
class BasicAuth implements ExcluderInterface
19
{
20
    /**
21
     * List of user/password to be excluded.
22
     *
23
     * @var array
24
     */
25
    protected $users = [];
26
27
    /**
28
     * @param array $users
29
     */
30
    public function __construct(array $users = [])
31
    {
32
        foreach ($users as $username => $password) {
33
            $this->addUser($username, $password);
34
        }
35
    }
36
37
    /**
38
     * Add user.
39
     *
40
     * @param string      $username
41
     * @param string|null $password
42
     */
43
    public function addUser($username, $password = null)
44
    {
45
        $this->users[trim($username)] = $password;
46
47
        return $this;
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function isExcluded(ServerRequestInterface $request)
54
    {
55
        $authData = $this->getAuth($request);
56
57
        foreach ($this->users as $username => $password) {
58
            if ($authData['username'] === $username && $authData['password'] === $password) {
59
                return true;
60
            }
61
        }
62
63
        return false;
64
    }
65
66
    /**
67
     * Retrieve request authentication information.
68
     *
69
     * @param \Psr\Http\Message\ServerRequestInterface $request
70
     *
71
     * @return array
72
     */
73
    protected function getAuth(ServerRequestInterface $request)
74
    {
75
        $authData = [
76
            'username' => null,
77
            'password' => null,
78
        ];
79
80
        $authHeader = $request->getHeaderLine('Authorization');
81
        if (preg_match('/^Basic /', $authHeader)) {
82
            $auth = explode(':', base64_decode(substr($authHeader, 6)), 2);
83
84
            $authData['username'] = $auth[0];
85
            $authData['password'] = isset($auth[1]) ? $auth[1] : null;
86
        }
87
88
        return $authData;
89
    }
90
}
91