1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the Shieldon package. |
4
|
|
|
* |
5
|
|
|
* (c) Terry L. <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
* |
10
|
|
|
* php version 7.1.0 |
11
|
|
|
* |
12
|
|
|
* @category Web-security |
13
|
|
|
* @package Shieldon |
14
|
|
|
* @author Terry Lin <[email protected]> |
15
|
|
|
* @copyright 2019 terrylinooo |
16
|
|
|
* @license https://github.com/terrylinooo/shieldon/blob/2.x/LICENSE MIT |
17
|
|
|
* @link https://github.com/terrylinooo/shieldon |
18
|
|
|
* @see https://shieldon.io |
19
|
|
|
*/ |
20
|
|
|
|
21
|
|
|
declare(strict_types=1); |
22
|
|
|
|
23
|
|
|
namespace Shieldon\Firewall\Panel; |
24
|
|
|
|
25
|
|
|
use function count; |
26
|
|
|
use function is_string; |
27
|
|
|
|
28
|
|
|
/* |
29
|
|
|
* Tradit for demonstration. |
30
|
|
|
*/ |
31
|
|
|
trait CsrfTrait |
32
|
|
|
{ |
33
|
|
|
/** |
34
|
|
|
* See $this->csrf() |
35
|
|
|
* |
36
|
|
|
* @var array |
37
|
|
|
*/ |
38
|
|
|
protected $csrfField = []; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Most popular PHP framework has a built-in CSRF protection such as Laravel. |
42
|
|
|
* We need to pass the CSRF token for our form actions. |
43
|
|
|
* |
44
|
|
|
* @param string|array ...$csrfparams The arguments. |
45
|
|
|
* |
46
|
|
|
* @return void |
47
|
|
|
*/ |
48
|
|
|
public function csrf(...$csrfparams): void |
49
|
|
|
{ |
50
|
|
|
$count = count($csrfparams); |
51
|
|
|
|
52
|
|
|
if (1 === $count) { |
53
|
|
|
foreach ($csrfparams as $key => $value) { |
54
|
|
|
$this->csrfField[] = [ |
55
|
|
|
'name' => $key, |
56
|
|
|
'value' => $value, |
57
|
|
|
]; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
} elseif (2 === $count) { |
61
|
|
|
|
62
|
|
|
if (!empty($csrfparams[0]) && is_string($csrfparams[0])) { |
63
|
|
|
$csrfKey = $csrfparams[0]; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
if (!empty($csrfparams[1]) && is_string($csrfparams[1])) { |
67
|
|
|
$csrfValue = $csrfparams[1]; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
if (!empty($csrfKey)) { |
71
|
|
|
$this->csrfField[] = [ |
72
|
|
|
'name' => $csrfKey, |
73
|
|
|
'value' => $csrfValue, |
|
|
|
|
74
|
|
|
]; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* Output HTML input element with CSRF token. |
81
|
|
|
* |
82
|
|
|
* @return void |
83
|
|
|
*/ |
84
|
|
|
public function fieldCsrf(): void |
85
|
|
|
{ |
86
|
|
|
if (!empty($this->csrfField)) { |
87
|
|
|
foreach ($this->csrfField as $value) { |
88
|
|
|
echo '<input type="hidden" name="' . $value['name'] . '" value="' . $value['value'] . '" id="csrf-field">'; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|