-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcsrf.php
More file actions
124 lines (109 loc) · 2.43 KB
/
csrf.php
File metadata and controls
124 lines (109 loc) · 2.43 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php
/**
* LightPHP Framework
* LitePHP is a framework that has been designed to be lite waight, extensible and fast.
*
* @author Robert Pitt <robertpitt1988@gmail.com>
* @category core
* @copyright 2013 Robert Pitt
* @license GPL v3 - GNU Public License v3
* @version 1.0.0
*/
class CSRF_Library
{
protected $session;
/**
* Session key
*/
protected $session_identifier = '_csrf_library_token_';
/**
* Get / Post key
*/
protected $gp_identifier = '_csrf_gp_token_';
/**
* Session Token
*/
protected $_token = null;
/**
*
*/
public function __construct()
{
/**
* Fetch the session library
*/
$this->session = Registry::get("LibraryLoader")->session;
/**
* Fetch the session library
*/
$this->bcrypt = Registry::get("LibraryLoader")->bcrypt;
/**
* Fetch the session library
*/
$this->input = Registry::get("Input");
/**
* Generate an access token if we do not have one.
*/
if($this->session->exists($this->session_identifier) === false)
{
/**
* Create a unique identifier using the session id.
*/
$this->_token = $this->bcrypt->encrypt($this->session->id(), 1);
/**
* Assign the token to the session
*/
$this->session->set($this->session_identifier, $this->_token);
}
/**
* Return the token from the session and assign in localy
*/
$this->_token = $this->session->get($this->session_identifier);
}
/**
* Generate
* @throws Exception If the token is invalid
*/
public function validate()
{
/**
* If we do not have the CSRF token in the storage, throw exception.
*/
if($this->session->exists($this->session_identifier) === false)
{
throw new Exception("Missing CSRF Token in session");
}
/**
* Check the input parameters
*/
if(!$this->input->get($this->gp_identifier) && !$this->input->post($this->gp_identifier))
{
throw new Exception("Missing CSRF Token in request");
}
/**
* Run a validation
*/
if(!$this->bcrypt->validate($this->session->id(), $this->session->get($this->session_identifier)))
{
throw new Exception("CSRF Detected.");
}
/**
* Mark the request as accepted.
*/
return true;
}
/**
* Generate a html block with the key and the
*/
public function html()
{
return sprintf('<input type="hidden" name="%s" value="%s" />', $this->gp_identifier, $this->_token);
}
/**
* Return the token for the session
*/
public function token()
{
return $ths->_token;
}
}