|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Jasny\Auth\Session; |
|
6
|
|
|
|
|
7
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Use OOP abstracted sessions to store auth session info. |
|
11
|
|
|
*/ |
|
12
|
|
|
class SessionObject implements SessionInterface |
|
13
|
|
|
{ |
|
14
|
|
|
protected string $key; |
|
15
|
|
|
|
|
16
|
|
|
/** @var \ArrayAccess<string,mixed>|null */ |
|
17
|
|
|
protected \ArrayAccess $session; |
|
|
|
|
|
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Service constructor. |
|
21
|
|
|
* |
|
22
|
|
|
* @param \ArrayAccess<string,mixed>|null $session |
|
23
|
|
|
* @param string $key |
|
24
|
|
|
*/ |
|
25
|
8 |
|
public function __construct(\ArrayAccess $session, string $key = 'auth') |
|
|
|
|
|
|
26
|
|
|
{ |
|
27
|
8 |
|
$this->session = $session; |
|
28
|
8 |
|
$this->key = $key; |
|
29
|
8 |
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Use the `session` attribute if it's an object that implements ArrayAccess. |
|
33
|
|
|
* |
|
34
|
|
|
* @return self |
|
35
|
|
|
*/ |
|
36
|
4 |
|
public function forRequest(ServerRequestInterface $request): self |
|
37
|
|
|
{ |
|
38
|
4 |
|
$session = $request->getAttribute('session'); |
|
39
|
|
|
|
|
40
|
4 |
|
if (!$session instanceof \ArrayAccess) { |
|
41
|
1 |
|
return $this; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
3 |
|
$copy = clone $this; |
|
45
|
3 |
|
$copy->session = $session; |
|
46
|
|
|
|
|
47
|
3 |
|
return $copy; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* Get auth information from session. |
|
53
|
|
|
* |
|
54
|
|
|
* @return array{uid:mixed,context:mixed,checksum:string|null} |
|
55
|
|
|
*/ |
|
56
|
4 |
|
public function getInfo(): array |
|
57
|
|
|
{ |
|
58
|
4 |
|
$data = $this->session[$this->key] ?? []; |
|
59
|
|
|
|
|
60
|
|
|
return [ |
|
61
|
4 |
|
'uid' => $data['uid'] ?? null, |
|
62
|
4 |
|
'context' => $data['context'] ?? null, |
|
63
|
4 |
|
'checksum' => $data['checksum'] ?? null, |
|
64
|
|
|
]; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
/** |
|
68
|
|
|
* Persist auth information to session. |
|
69
|
|
|
* |
|
70
|
|
|
* @param string|int $uid |
|
71
|
|
|
* @param mixed $context |
|
72
|
|
|
* @param string|null $checksum |
|
73
|
|
|
*/ |
|
74
|
2 |
|
public function persist($uid, $context, ?string $checksum): void |
|
75
|
|
|
{ |
|
76
|
2 |
|
$this->session[$this->key] = compact('uid', 'context', 'checksum'); |
|
77
|
2 |
|
} |
|
78
|
|
|
|
|
79
|
|
|
/** |
|
80
|
|
|
* Remove auth information from session. |
|
81
|
|
|
*/ |
|
82
|
2 |
|
public function clear(): void |
|
83
|
|
|
{ |
|
84
|
2 |
|
if (isset($this->session[$this->key])) { |
|
85
|
1 |
|
unset($this->session[$this->key]); |
|
86
|
|
|
} |
|
87
|
2 |
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|