-
-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathSessionAuthenticator.php
More file actions
85 lines (63 loc) · 2.21 KB
/
Copy pathSessionAuthenticator.php
File metadata and controls
85 lines (63 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php
declare(strict_types=1);
namespace Tempest\Auth\Authentication;
use Tempest\Http\Session\Session;
use Tempest\Http\Session\SessionManager;
final class SessionAuthenticator implements Authenticator
{
public const string AUTHENTICATABLE_KEY = '#authenticatable:id';
public const string AUTHENTICATABLE_CLASS = '#authenticatable:class';
private int|string|null $currentId = null;
private ?string $currentClass = null;
private ?Authenticatable $current = null;
public function __construct(
private readonly SessionManager $sessionManager,
private readonly Session $session,
private readonly AuthenticatableResolver $authenticatableResolver,
) {}
public function authenticate(Authenticatable $authenticatable): void
{
$id = $this->authenticatableResolver->resolveId($authenticatable);
$class = $authenticatable::class;
$this->session->set(
key: self::AUTHENTICATABLE_CLASS,
value: $class,
);
$this->session->set(
key: self::AUTHENTICATABLE_KEY,
value: $id,
);
$this->currentId = $id;
$this->currentClass = $class;
$this->current = $authenticatable;
}
public function deauthenticate(): void
{
$this->session->remove(self::AUTHENTICATABLE_KEY);
$this->session->remove(self::AUTHENTICATABLE_CLASS);
$this->clearCurrent();
$this->sessionManager->save($this->session);
}
public function current(): ?Authenticatable
{
$id = $this->session->get(self::AUTHENTICATABLE_KEY);
$class = $this->session->get(self::AUTHENTICATABLE_CLASS);
if (! $id || ! $class) {
$this->clearCurrent();
return null;
}
if ($this->currentId === $id && $this->currentClass === $class) {
return $this->current;
}
$this->currentId = $id;
$this->currentClass = $class;
$this->current = $this->authenticatableResolver->resolve($id, $class);
return $this->current;
}
public function clearCurrent(): void
{
$this->currentId = null;
$this->currentClass = null;
$this->current = null;
}
}