|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* Spiral Framework. |
|
5
|
|
|
* |
|
6
|
|
|
* @license MIT |
|
7
|
|
|
* @author Anton Titov (Wolfy-J) |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
declare(strict_types=1); |
|
11
|
|
|
|
|
12
|
|
|
namespace Spiral\Cookies\Config; |
|
13
|
|
|
|
|
14
|
|
|
use Psr\Http\Message\UriInterface; |
|
15
|
|
|
use Spiral\Core\InjectableConfig; |
|
16
|
|
|
|
|
17
|
|
|
final class CookiesConfig extends InjectableConfig |
|
18
|
|
|
{ |
|
19
|
|
|
public const CONFIG = 'cookies'; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Cookie protection methods. |
|
23
|
|
|
*/ |
|
24
|
|
|
public const COOKIE_UNPROTECTED = 0; |
|
25
|
|
|
public const COOKIE_ENCRYPT = 1; |
|
26
|
|
|
public const COOKIE_HMAC = 2; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* Algorithm used to sign cookies. |
|
30
|
|
|
*/ |
|
31
|
|
|
public const HMAC_ALGORITHM = 'sha256'; |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* Generated MAC length, has to be stripped from cookie. |
|
35
|
|
|
*/ |
|
36
|
|
|
public const MAC_LENGTH = 64; |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @var array |
|
40
|
|
|
*/ |
|
41
|
|
|
protected $config = [ |
|
42
|
|
|
'domain' => '.%s', |
|
43
|
|
|
'method' => self::COOKIE_ENCRYPT, |
|
44
|
|
|
'excluded' => ['PHPSESSID', 'csrf-token'] |
|
45
|
|
|
]; |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Return domain associated with the cookie. |
|
49
|
|
|
* |
|
50
|
|
|
* @param UriInterface $uri |
|
51
|
|
|
* @return string|null |
|
52
|
|
|
*/ |
|
53
|
|
|
public function resolveDomain(UriInterface $uri): ?string |
|
54
|
|
|
{ |
|
55
|
|
|
$host = $uri->getHost(); |
|
56
|
|
|
if (empty($host)) { |
|
57
|
|
|
return null; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
$pattern = $this->config['domain']; |
|
61
|
|
|
if (preg_match("/^(\d{1,3}){4}:\d+$/", $host, $matches)) { |
|
62
|
|
|
// remove port |
|
63
|
|
|
$host = $matches[1]; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
if ($host === 'localhost' || filter_var($host, FILTER_VALIDATE_IP)) { |
|
67
|
|
|
//We can't use sub-domains when website required by IP |
|
68
|
|
|
$pattern = ltrim($pattern, '.'); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
if (strpos($pattern, '%s') === false) { |
|
72
|
|
|
//Forced domain |
|
73
|
|
|
return $pattern; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
return sprintf($pattern, $host); |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
/** |
|
80
|
|
|
* Cookie protection method. |
|
81
|
|
|
* |
|
82
|
|
|
* @return int |
|
83
|
|
|
*/ |
|
84
|
|
|
public function getProtectionMethod(): int |
|
85
|
|
|
{ |
|
86
|
|
|
return $this->config['method']; |
|
87
|
|
|
} |
|
88
|
|
|
|
|
89
|
|
|
/** |
|
90
|
|
|
* Cookies excluded from protection. |
|
91
|
|
|
* |
|
92
|
|
|
* @return array |
|
93
|
|
|
*/ |
|
94
|
|
|
public function getExcludedCookies(): array |
|
95
|
|
|
{ |
|
96
|
|
|
return $this->config['excluded']; |
|
97
|
|
|
} |
|
98
|
|
|
} |
|
99
|
|
|
|