Csrf::saveToSession()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Faulancer\Security;
4
5
use Faulancer\ServiceLocator\ServiceInterface;
6
use Faulancer\ServiceLocator\ServiceLocator;
7
use Faulancer\Session\SessionManager;
8
9
/**
10
 * Class Csrf
11
 *
12
 * @package Faulancer\Security
13
 * @author Florian Knapp <[email protected]>
14
 */
15
class Csrf
16
{
17
    /**
18
     * Generates a token and save it to session
19
     *
20
     * @param string $identifier
21
     *
22
     * @return string
23
     */
24
    public static function getToken(string $identifier = '') :string
25
    {
26
        $token = self::_getSessionManager()->get('csrf' . $identifier);
27
28
        if (!self::_getSessionManager()->has('csrf' . $identifier)) {
29
            $token = bin2hex(openssl_random_pseudo_bytes(16));
30
            self::saveToSession($token, $identifier);
31
        }
32
33
        return $token;
34
    }
35
36
    /**
37
     * Check if token is valid
38
     *
39
     * @param string $token
40
     * @param string $identifier
41
     *
42
     * @return bool
43
     */
44
    public static function isValid(string $token, string $identifier = '') :bool
45
    {
46
        $sessionToken = self::_getSessionManager()->get('csrf' . $identifier);
47
        $isValid      = $token === $sessionToken;
48
49
        if ($isValid) {
50
            self::_getSessionManager()->delete('csrf' . $identifier);
51
            return true;
52
        }
53
54
        return false;
55
    }
56
57
    /**
58
     * Saves token into session
59
     *
60
     * @param string $token
61
     * @param string $identifier
62
     *
63
     * @return void
64
     */
65
    private static function saveToSession(string $token, string $identifier = '')
66
    {
67
        self::_getSessionManager()->set('csrf' . $identifier, $token);
68
    }
69
70
    /**
71
     * @return SessionManager|ServiceInterface
72
     */
73
    private static function _getSessionManager()
74
    {
75
        return ServiceLocator::instance()->get(SessionManager::class);
76
    }
77
78
}