Completed
Pull Request — master (#7057)
by Damian
08:49
created

AllowedHostsMiddleware   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 38
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getAllowedHosts() 0 4 1
A setAllowedHosts() 0 4 1
A process() 0 13 4
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
    /**
30
     * @inheritdoc
31
     */
32
    public function process(HTTPRequest $request, callable $delegate)
33
    {
34
        if ($this->allowedHosts && !Director::is_cli()) {
35
            $allowedHosts = preg_split('/ *, */', $this->allowedHosts);
36
37
            // check allowed hosts
38
            if (!in_array($request->getHeader('Host'), $allowedHosts)) {
39
                return new HTTPResponse('Invalid Host', 400);
40
            }
41
        }
42
43
        return $delegate($request);
44
    }
45
}
46