Passed
Push — master ( 436c58...98654e )
by Anton
06:21 queued 03:52
created

TokenStorage::create()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 6
c 1
b 0
f 1
dl 0
loc 9
rs 10
cc 2
nc 3
nop 2
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\Auth\Session;
13
14
use Spiral\Auth\Exception\TokenStorageException;
15
use Spiral\Auth\TokenInterface;
16
use Spiral\Auth\TokenStorageInterface;
17
use Spiral\Session\SessionScope;
18
19
/**
20
 * Store tokens in active session segment (received via scope).
21
 */
22
final class TokenStorage implements TokenStorageInterface
23
{
24
    // session section to store session information
25
    private const SESSION_SECTION = 'auth';
26
27
    /** @var SessionScope */
28
    private $session;
29
30
    /**
31
     * @param SessionScope $session
32
     */
33
    public function __construct(SessionScope $session)
34
    {
35
        $this->session = $session;
36
    }
37
38
    /**
39
     * @inheritDoc
40
     */
41
    public function load(string $id): ?TokenInterface
42
    {
43
        try {
44
            $tokenData = $this->session->getSection(self::SESSION_SECTION)->get('token');
45
            $token = Token::unpack($tokenData);
46
        } catch (\Throwable $e) {
47
            throw new TokenStorageException('Unable to load session token', $e->getCode(), $e);
48
        }
49
50
        if ($token->getID() !== $id) {
51
            return null;
52
        }
53
54
        if ($token->getExpiresAt() !== null && $token->getExpiresAt() > new \DateTime()) {
55
            $this->delete($token);
56
            return null;
57
        }
58
59
        return $token;
60
    }
61
62
    /**
63
     * @inheritDoc
64
     */
65
    public function create(array $payload, \DateTimeInterface $expiresAt = null): TokenInterface
66
    {
67
        try {
68
            $token = new Token($this->randomHash(123), $payload, $expiresAt);
69
            $this->session->getSection(self::SESSION_SECTION)->set('token', $token->pack());
70
71
            return $token;
72
        } catch (\Throwable $e) {
73
            throw new TokenStorageException('Unable to create session token', $e->getCode(), $e);
74
        }
75
    }
76
77
    /**
78
     * @inheritDoc
79
     */
80
    public function delete(TokenInterface $token): void
81
    {
82
        $this->session->getSection(self::SESSION_SECTION)->delete('token');
83
    }
84
85
    /**
86
     * @param int $length
87
     * @return string
88
     *
89
     * @throws \Exception
90
     */
91
    private function randomHash(int $length): string
92
    {
93
        return substr(bin2hex(random_bytes($length)), 0, $length);
94
    }
95
}
96