Passed
Pull Request — 2.0 (#65)
by Robbie
03:35
created
src/Control/CwpBasicAuthMiddleware.php 1 patch
Indentation   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -8,95 +8,95 @@
 block discarded – undo
8 8
 
9 9
 class CwpBasicAuthMiddleware extends BasicAuthMiddleware implements PermissionProvider
10 10
 {
11
-    /**
12
-     * Whitelisted IP addresses will not be given a basic authentication prompt when other basic authentication
13
-     * rules via {@link BasicAuthMiddleware} are enabled.
14
-     *
15
-     * Please note that this will not have any effect if using BasicAuth.entire_site_protected, which will
16
-     * always enabled basic authentication for the entire site.
17
-     *
18
-     * @var array
19
-     */
20
-    protected $whitelistedIps = [];
11
+	/**
12
+	 * Whitelisted IP addresses will not be given a basic authentication prompt when other basic authentication
13
+	 * rules via {@link BasicAuthMiddleware} are enabled.
14
+	 *
15
+	 * Please note that this will not have any effect if using BasicAuth.entire_site_protected, which will
16
+	 * always enabled basic authentication for the entire site.
17
+	 *
18
+	 * @var array
19
+	 */
20
+	protected $whitelistedIps = [];
21 21
 
22
-    /**
23
-     * @return array
24
-     */
25
-    public function getWhitelistedIps()
26
-    {
27
-        return $this->whitelistedIps;
28
-    }
22
+	/**
23
+	 * @return array
24
+	 */
25
+	public function getWhitelistedIps()
26
+	{
27
+		return $this->whitelistedIps;
28
+	}
29 29
 
30
-    /**
31
-     * @param string|string[] $whitelistedIps An array of IP addresses, a comma delimited string, or an array of IPs
32
-     *                                        or comma delimited IP list strings
33
-     * @return $this
34
-     */
35
-    public function setWhitelistedIps($whitelistedIps)
36
-    {
37
-        // Allow string or array input
38
-        $ipLists = is_string($whitelistedIps) ? [$whitelistedIps] : $whitelistedIps;
30
+	/**
31
+	 * @param string|string[] $whitelistedIps An array of IP addresses, a comma delimited string, or an array of IPs
32
+	 *                                        or comma delimited IP list strings
33
+	 * @return $this
34
+	 */
35
+	public function setWhitelistedIps($whitelistedIps)
36
+	{
37
+		// Allow string or array input
38
+		$ipLists = is_string($whitelistedIps) ? [$whitelistedIps] : $whitelistedIps;
39 39
 
40
-        $whitelistedIps = [];
41
-        // Break each string in the array by commas to support nested IP lists
42
-        foreach ($ipLists as $ipList) {
43
-            $ips = array_map('trim', explode(',', $ipList));
44
-            $whitelistedIps = array_merge($whitelistedIps, $ips);
45
-        }
40
+		$whitelistedIps = [];
41
+		// Break each string in the array by commas to support nested IP lists
42
+		foreach ($ipLists as $ipList) {
43
+			$ips = array_map('trim', explode(',', $ipList));
44
+			$whitelistedIps = array_merge($whitelistedIps, $ips);
45
+		}
46 46
 
47
-        // Return unique values with keys reset
48
-        $this->whitelistedIps = array_values(array_unique($whitelistedIps));
49
-        return $this;
50
-    }
47
+		// Return unique values with keys reset
48
+		$this->whitelistedIps = array_values(array_unique($whitelistedIps));
49
+		return $this;
50
+	}
51 51
 
52
-    /**
53
-     * Check for any whitelisted IP addresses. If one matches the current user's IP then return false early,
54
-     * otherwise allow the default {@link BasicAuthMiddleware} to continue its logic.
55
-     *
56
-     * {@inheritDoc}
57
-     */
58
-    protected function checkMatchingURL(HTTPRequest $request)
59
-    {
60
-        if ($this->ipMatchesWhitelist()) {
61
-            return false;
62
-        }
63
-        return parent::checkMatchingURL($request);
64
-    }
52
+	/**
53
+	 * Check for any whitelisted IP addresses. If one matches the current user's IP then return false early,
54
+	 * otherwise allow the default {@link BasicAuthMiddleware} to continue its logic.
55
+	 *
56
+	 * {@inheritDoc}
57
+	 */
58
+	protected function checkMatchingURL(HTTPRequest $request)
59
+	{
60
+		if ($this->ipMatchesWhitelist()) {
61
+			return false;
62
+		}
63
+		return parent::checkMatchingURL($request);
64
+	}
65 65
 
66
-    /**
67
-     * Check whether the current user's IP address is in the IP whitelist
68
-     *
69
-     * @return bool
70
-     */
71
-    protected function ipMatchesWhitelist()
72
-    {
73
-        $whitelist = $this->getWhitelistedIps();
74
-        // Continue if no whitelist is defined
75
-        if (empty($whitelist)) {
76
-            return false;
77
-        }
66
+	/**
67
+	 * Check whether the current user's IP address is in the IP whitelist
68
+	 *
69
+	 * @return bool
70
+	 */
71
+	protected function ipMatchesWhitelist()
72
+	{
73
+		$whitelist = $this->getWhitelistedIps();
74
+		// Continue if no whitelist is defined
75
+		if (empty($whitelist)) {
76
+			return false;
77
+		}
78 78
 
79
-        $userIp = $_SERVER['REMOTE_ADDR'];
80
-        if (in_array($userIp, $whitelist)) {
81
-            return true;
82
-        }
79
+		$userIp = $_SERVER['REMOTE_ADDR'];
80
+		if (in_array($userIp, $whitelist)) {
81
+			return true;
82
+		}
83 83
 
84
-        return false;
85
-    }
84
+		return false;
85
+	}
86 86
 
87
-    /**
88
-     * Provide a permission code for users to be able to access the site in test mode (UAT sites). This will
89
-     * apply to any route other than those required to change your password.
90
-     *
91
-     * @return array
92
-     */
93
-    public function providePermissions()
94
-    {
95
-        return [
96
-            'ACCESS_UAT_SERVER' => _t(
97
-                __CLASS__ . '.UatServerPermission',
98
-                'Allow users to use their accounts to access the UAT server'
99
-            )
100
-        ];
101
-    }
87
+	/**
88
+	 * Provide a permission code for users to be able to access the site in test mode (UAT sites). This will
89
+	 * apply to any route other than those required to change your password.
90
+	 *
91
+	 * @return array
92
+	 */
93
+	public function providePermissions()
94
+	{
95
+		return [
96
+			'ACCESS_UAT_SERVER' => _t(
97
+				__CLASS__ . '.UatServerPermission',
98
+				'Allow users to use their accounts to access the UAT server'
99
+			)
100
+		];
101
+	}
102 102
 }
Please login to merge, or discard this patch.
tests/Control/CwpBasicAuthMiddlewareTest.php 1 patch
Indentation   +110 added lines, -110 removed lines patch added patch discarded remove patch
@@ -13,114 +13,114 @@
 block discarded – undo
13 13
 
14 14
 class CwpBasicAuthMiddlewareTest extends SapphireTest
15 15
 {
16
-    /**
17
-     * @var CwpBasicAuthMiddleware
18
-     */
19
-    protected $middleware;
20
-
21
-    /**
22
-     * @var array
23
-     */
24
-    protected $originalServersVars = [];
25
-
26
-    protected function setUp()
27
-    {
28
-        parent::setUp();
29
-
30
-        $this->middleware = Injector::inst()->get(BasicAuthMiddleware::class);
31
-        $this->originalServersVars = $_SERVER;
32
-
33
-        Config::modify()->set(BasicAuth::class, 'ignore_cli', false);
34
-    }
35
-
36
-    protected function tearDown()
37
-    {
38
-        $_SERVER = $this->originalServersVars;
39
-
40
-        parent::tearDown();
41
-    }
42
-
43
-    public function testSetWhitelistedIpsAcceptsStrings()
44
-    {
45
-        $this->middleware->setWhitelistedIps('127.0.0.1,127.0.0.2');
46
-        $this->assertSame([
47
-            '127.0.0.1',
48
-            '127.0.0.2',
49
-        ], $this->middleware->getWhitelistedIps(), 'Accepts comma delimited strings');
50
-    }
51
-
52
-    public function testSetWhitelistedIpsAcceptsArraysOfStrings()
53
-    {
54
-        $this->middleware->setWhitelistedIps(['127.0.0.1']);
55
-        $this->assertSame(['127.0.0.1'], $this->middleware->getWhitelistedIps(), 'Accepts array values');
56
-    }
57
-
58
-    public function testSetWhitelistedIpsSupportedNestedStringListsInsideArrays()
59
-    {
60
-        $this->middleware->setWhitelistedIps([
61
-            '127.0.0.1,127.0.0.2', // Example of `CWP_IP_BYPASS_BASICAUTH` env var value
62
-            ' 137.0.0.1 , 127.0.0.2', // Example of `CWP_IP_BYPASS_BASICAUTH` env var value with added spaces
63
-            '127.0.0.3',
64
-            '127.0.0.3', // check results are unique
65
-            '127.0.0.4',
66
-        ]);
67
-
68
-        $this->assertSame([
69
-            '127.0.0.1',
70
-            '127.0.0.2',
71
-            '137.0.0.1',
72
-            '127.0.0.3',
73
-            '127.0.0.4',
74
-        ], $this->middleware->getWhitelistedIps(), 'Accepts IP list strings inside arrays');
75
-    }
76
-
77
-    /**
78
-     * @param string $currentIp
79
-     * @param int $expected
80
-     * @dataProvider whitelistingProvider
81
-     */
82
-    public function testIpWhitelisting($currentIp, $expected)
83
-    {
84
-        // Enable basic auth everywhere
85
-        $this->middleware->setURLPatterns(['#.*#' => true]);
86
-
87
-        // Set a whitelisted IP address
88
-        $_SERVER['REMOTE_ADDR'] = $currentIp;
89
-        $this->middleware->setWhitelistedIps(['127.0.0.1']);
90
-
91
-        $response = $this->mockRequest();
92
-
93
-        $this->assertEquals($expected, $response->getStatusCode());
94
-    }
95
-
96
-    /**
97
-     * @return array[]
98
-     */
99
-    public function whitelistingProvider()
100
-    {
101
-        return [
102
-            'IP not in whitelist' => ['123.456.789.012', 401],
103
-            'IP in whitelist' => ['127.0.0.1', 200],
104
-        ];
105
-    }
106
-
107
-    public function testMiddlewareProvidesUatServerPermissions()
108
-    {
109
-        $this->assertArrayHasKey('ACCESS_UAT_SERVER', $this->middleware->providePermissions());
110
-    }
111
-
112
-    /**
113
-     * Perform a mock middleware request. Will return 200 if everything is OK.
114
-     *
115
-     * @param string $url
116
-     * @return HTTPResponse
117
-     */
118
-    protected function mockRequest($url = '/foo')
119
-    {
120
-        $request = new HTTPRequest('GET', $url);
121
-
122
-        return $this->middleware->process($request, function () {
123
-            return new HTTPResponse('OK', 200);
124
-        });
125
-    }
16
+	/**
17
+	 * @var CwpBasicAuthMiddleware
18
+	 */
19
+	protected $middleware;
20
+
21
+	/**
22
+	 * @var array
23
+	 */
24
+	protected $originalServersVars = [];
25
+
26
+	protected function setUp()
27
+	{
28
+		parent::setUp();
29
+
30
+		$this->middleware = Injector::inst()->get(BasicAuthMiddleware::class);
31
+		$this->originalServersVars = $_SERVER;
32
+
33
+		Config::modify()->set(BasicAuth::class, 'ignore_cli', false);
34
+	}
35
+
36
+	protected function tearDown()
37
+	{
38
+		$_SERVER = $this->originalServersVars;
39
+
40
+		parent::tearDown();
41
+	}
42
+
43
+	public function testSetWhitelistedIpsAcceptsStrings()
44
+	{
45
+		$this->middleware->setWhitelistedIps('127.0.0.1,127.0.0.2');
46
+		$this->assertSame([
47
+			'127.0.0.1',
48
+			'127.0.0.2',
49
+		], $this->middleware->getWhitelistedIps(), 'Accepts comma delimited strings');
50
+	}
51
+
52
+	public function testSetWhitelistedIpsAcceptsArraysOfStrings()
53
+	{
54
+		$this->middleware->setWhitelistedIps(['127.0.0.1']);
55
+		$this->assertSame(['127.0.0.1'], $this->middleware->getWhitelistedIps(), 'Accepts array values');
56
+	}
57
+
58
+	public function testSetWhitelistedIpsSupportedNestedStringListsInsideArrays()
59
+	{
60
+		$this->middleware->setWhitelistedIps([
61
+			'127.0.0.1,127.0.0.2', // Example of `CWP_IP_BYPASS_BASICAUTH` env var value
62
+			' 137.0.0.1 , 127.0.0.2', // Example of `CWP_IP_BYPASS_BASICAUTH` env var value with added spaces
63
+			'127.0.0.3',
64
+			'127.0.0.3', // check results are unique
65
+			'127.0.0.4',
66
+		]);
67
+
68
+		$this->assertSame([
69
+			'127.0.0.1',
70
+			'127.0.0.2',
71
+			'137.0.0.1',
72
+			'127.0.0.3',
73
+			'127.0.0.4',
74
+		], $this->middleware->getWhitelistedIps(), 'Accepts IP list strings inside arrays');
75
+	}
76
+
77
+	/**
78
+	 * @param string $currentIp
79
+	 * @param int $expected
80
+	 * @dataProvider whitelistingProvider
81
+	 */
82
+	public function testIpWhitelisting($currentIp, $expected)
83
+	{
84
+		// Enable basic auth everywhere
85
+		$this->middleware->setURLPatterns(['#.*#' => true]);
86
+
87
+		// Set a whitelisted IP address
88
+		$_SERVER['REMOTE_ADDR'] = $currentIp;
89
+		$this->middleware->setWhitelistedIps(['127.0.0.1']);
90
+
91
+		$response = $this->mockRequest();
92
+
93
+		$this->assertEquals($expected, $response->getStatusCode());
94
+	}
95
+
96
+	/**
97
+	 * @return array[]
98
+	 */
99
+	public function whitelistingProvider()
100
+	{
101
+		return [
102
+			'IP not in whitelist' => ['123.456.789.012', 401],
103
+			'IP in whitelist' => ['127.0.0.1', 200],
104
+		];
105
+	}
106
+
107
+	public function testMiddlewareProvidesUatServerPermissions()
108
+	{
109
+		$this->assertArrayHasKey('ACCESS_UAT_SERVER', $this->middleware->providePermissions());
110
+	}
111
+
112
+	/**
113
+	 * Perform a mock middleware request. Will return 200 if everything is OK.
114
+	 *
115
+	 * @param string $url
116
+	 * @return HTTPResponse
117
+	 */
118
+	protected function mockRequest($url = '/foo')
119
+	{
120
+		$request = new HTTPRequest('GET', $url);
121
+
122
+		return $this->middleware->process($request, function () {
123
+			return new HTTPResponse('OK', 200);
124
+		});
125
+	}
126 126
 }
Please login to merge, or discard this patch.