Completed
Push — director-middleware ( 059969...3cff84 )
by Sam
08:52
created

AllowedHostsMiddleware::getAllowedHosts()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\Control;
4
5
/**
6
 * Secures requests by only allowing a whitelist of Host values
7
 */
8
class AllowedHostsMiddleware implements HTTPMiddleware
9
{
10
11
    private $allowedHosts = null;
12
13
    /**
14
     * @return string A comma-separted list of allowed Host header values
15
     */
16
    public function getAllowedHosts()
17
    {
18
        return $this->allowedHosts;
19
    }
20
21
    /**
22
     * @param $allowedHosts string A comma-separted list of allowed Host header values
23
     */
24
    public function setAllowedHosts($allowedHosts)
25
    {
26
        $this->allowedHosts = $allowedHosts;
27
    }
28
29
    public function process(HTTPRequest $request, callable $delegate)
30
    {
31
        if ($this->allowedHosts && !Director::is_cli()) {
32
            $allowedHosts = preg_split('/ *, */', $this->allowedHosts);
33
34
            // check allowed hosts
35
            if (!in_array($request->getHeader('Host'), $allowedHosts)) {
36
                return new HTTPResponse('Invalid Host', 400);
37
            }
38
        }
39
40
        return $delegate($request);
41
    }
42
}
43