CSRF::verifyForm()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 13
rs 10
1
<?php
2
3
namespace ThallesDella\GateKeeper\Modules;
4
5
use ThallesDella\SimpleSession\Session;
6
7
/**
8
 * Gate Keeper | Class CSRF [ MODULE ]
9
 *
10
 * @category GateKeeper\Modules
11
 * @package  ThallesDella\GateKeeper\Modules
12
 * @author   Thalles D. koester <[email protected]>
13
 * @license  https://choosealicense.com/licenses/mit/ MIT
14
 * @link     https://github.com/thallesdella/gate-keeper
15
 */
16
class CSRF
17
{
18
    /**
19
     * @var Session
20
     */
21
    private $_session;
22
    
23
    /**
24
     * @var string
25
     */
26
    private $_token;
27
    
28
    /**
29
     * CSRF constructor.
30
     */
31
    public function __construct()
32
    {
33
        $this->_session = new Session();
34
        $this->_createToken();
35
    }
36
    
37
    /**
38
     * @return string
39
     */
40
    public function getToken()
41
    {
42
        return $this->_token;
43
    }
44
    
45
    /**
46
     * @return string
47
     */
48
    public function generateInput(): string
49
    {
50
        return "<input type=\"hidden\" name=\"_token\" value=\"{$this->_token }\"/>";
51
    }
52
    
53
    /**
54
     * @param array $request
55
     *
56
     * @return bool
57
     */
58
    public function verifyForm(array $request): bool
59
    {
60
        $token = filter_var($request['_token'], FILTER_DEFAULT);
61
        
62
        if (!$this->_session->has('_token')
63
            || empty($token)
64
            || $token != $this->_session->_token
65
        ) {
66
            return false;
67
        }
68
        
69
        $this->_updateToken();
70
        return true;
71
    }
72
    
73
    /**
74
     * @return void
75
     */
76
    private function _createToken(): void
77
    {
78
        if (!$this->_session->has('_token')) {
79
            $this->_session->_token = $this->_generateToken();
80
        }
81
        $this->_token = $this->_session->_token;
82
    }
83
    
84
    /**
85
     * @return void
86
     */
87
    private function _updateToken(): void
88
    {
89
        $this->_session->_token = $this->_generateToken();
90
        $this->_token = $this->_session->_token;
91
    }
92
    
93
    /**
94
     * @return string
95
     */
96
    private function _generateToken(): string
97
    {
98
        return sha1(uniqid(rand(), true));
99
    }
100
    
101
}