|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace DMK\MKSamlAuth\Session; |
|
6
|
|
|
|
|
7
|
|
|
use TYPO3\CMS\Core\SingletonInterface; |
|
8
|
|
|
|
|
9
|
|
|
class PhpSession implements SingletonInterface |
|
10
|
|
|
{ |
|
11
|
|
|
private const DEFAULT_SESSION_OPTIONS = [ |
|
12
|
|
|
'name' => 'saml_auth', |
|
13
|
|
|
'cookie_secure' => true, |
|
14
|
|
|
'cookie_httponly' => true, |
|
15
|
|
|
// 60 seconds should suffice to fill the login form |
|
16
|
|
|
'cookie_lifetime' => 60, |
|
17
|
|
|
// Session fixation protection: |
|
18
|
|
|
'use_strict_mode' => true, |
|
19
|
|
|
]; |
|
20
|
|
|
|
|
21
|
|
|
private const SESSION_KEY = 'DMK_SESSION'; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @var bool |
|
25
|
|
|
*/ |
|
26
|
|
|
private $started = false; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* Starts the new session. |
|
30
|
|
|
*/ |
|
31
|
|
|
public function start(): void |
|
32
|
|
|
{ |
|
33
|
|
|
if ($this->started) { |
|
34
|
|
|
return; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
session_start(self::DEFAULT_SESSION_OPTIONS); |
|
38
|
|
|
|
|
39
|
|
|
if (empty($_SESSION[self::SESSION_KEY])) { |
|
40
|
|
|
// Additional (in case strict mode fails for some reason) session fixation protection |
|
41
|
|
|
session_regenerate_id(true); |
|
42
|
|
|
$_SESSION = []; |
|
43
|
|
|
$_SESSION[self::SESSION_KEY]['started'] = true; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
$this->started = true; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Returns the session id. |
|
51
|
|
|
* |
|
52
|
|
|
* @return string |
|
53
|
|
|
*/ |
|
54
|
|
|
public function getId(): string |
|
55
|
|
|
{ |
|
56
|
|
|
$this->start(); |
|
57
|
|
|
return session_id(); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* Closes the session and write it down. |
|
62
|
|
|
*/ |
|
63
|
|
|
public function close(): void |
|
64
|
|
|
{ |
|
65
|
|
|
$this->started = false; |
|
66
|
|
|
session_write_close(); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* Sets a new value to the session. |
|
71
|
|
|
* |
|
72
|
|
|
* @param string $key |
|
73
|
|
|
* @param mixed $value |
|
74
|
|
|
*/ |
|
75
|
|
|
public function set(string $key, $value): void |
|
76
|
|
|
{ |
|
77
|
|
|
$this->start(); |
|
78
|
|
|
|
|
79
|
|
|
$_SESSION[self::SESSION_KEY][$key] = $value; |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
|
|
/** |
|
83
|
|
|
* Gets a value from the storage, if the key could not be found |
|
84
|
|
|
* it will return null. |
|
85
|
|
|
* |
|
86
|
|
|
* @param string $key |
|
87
|
|
|
* |
|
88
|
|
|
* @return mixed|null |
|
89
|
|
|
*/ |
|
90
|
|
|
public function get(string $key) |
|
91
|
|
|
{ |
|
92
|
|
|
$this->start(); |
|
93
|
|
|
|
|
94
|
|
|
if (empty($_SESSION[self::SESSION_KEY][$key])) { |
|
95
|
|
|
return null; |
|
96
|
|
|
} |
|
97
|
|
|
|
|
98
|
|
|
return $_SESSION[self::SESSION_KEY][$key]; |
|
99
|
|
|
} |
|
100
|
|
|
} |
|
101
|
|
|
|