Passed
Push — develop ( 9820b2...1bde09 )
by nguereza
04:09
created

CsrfManager::validate()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 11
c 1
b 0
f 0
nc 8
nop 2
dl 0
loc 22
rs 9.2222
1
<?php
2
3
/**
4
 * Platine Framework
5
 *
6
 * Platine Framework is a lightweight, high-performance, simple and elegant PHP
7
 * Web framework
8
 *
9
 * This content is released under the MIT License (MIT)
10
 *
11
 * Copyright (c) 2020 Platine Framework
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a copy
14
 * of this software and associated documentation files (the "Software"), to deal
15
 * in the Software without restriction, including without limitation the rights
16
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
 * copies of the Software, and to permit persons to whom the Software is
18
 * furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in all
21
 * copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
 * SOFTWARE.
30
 */
31
32
/**
33
 *  @file CsrfManager.php
34
 *
35
 *  The CSRF manager class
36
 *
37
 *  @package    Platine\Framework\Security\Csrf
38
 *  @author Platine Developers team
39
 *  @copyright  Copyright (c) 2020
40
 *  @license    http://opensource.org/licenses/MIT  MIT License
41
 *  @link   https://www.platine-php.com
42
 *  @version 1.0.0
43
 *  @filesource
44
 */
45
46
declare(strict_types=1);
47
48
namespace Platine\Framework\Security\Csrf;
49
50
use Platine\Config\Config;
51
use Platine\Framework\Http\RequestData;
52
use Platine\Framework\Security\Csrf\CsrfStorageInterface;
53
use Platine\Framework\Security\Csrf\Storage\CsrfNullStorage;
54
use Platine\Http\ServerRequestInterface;
55
use Platine\Stdlib\Helper\Str;
56
57
/**
58
 * @class CsrfManager
59
 * @package Platine\Framework\Security\Csrf
60
 */
61
class CsrfManager
62
{
63
    /**
64
     * The application configuration class
65
     * @var Config
66
     */
67
    protected Config $config;
68
69
    /**
70
     * The storage to be used
71
     * @var CsrfStorageInterface
72
     */
73
    protected CsrfStorageInterface $storage;
74
75
    /**
76
     * Whether return need generate token per request or not
77
     * @var bool
78
     */
79
    protected bool $unique = false;
80
81
    /**
82
     * Create new instance
83
     * @param Config $config
84
     * @param CsrfStorageInterface|null $storage
85
     */
86
    public function __construct(
87
        Config $config,
88
        ?CsrfStorageInterface $storage = null
89
    ) {
90
        $this->config = $config;
91
        $this->storage = $storage ??  new CsrfNullStorage();
92
    }
93
94
    /**
95
     * Validate the token
96
     * @param ServerRequestInterface $request
97
     * @param string|null $key
98
     * @return bool
99
     */
100
    public function validate(ServerRequestInterface $request, ?string $key = null): bool
101
    {
102
        if ($key === null) {
103
            $key = $this->getConfigValue('key');
104
        }
105
106
        $storageToken = $this->storage->get($key);
107
        if ($storageToken === null) {
108
            return false;
109
        }
110
111
        $token = $this->getRequestToken($request, $key);
112
113
        if ($token === null || $token !== $storageToken) {
114
            return false;
115
        }
116
117
        if ($this->unique === false) {
118
            $this->storage->delete($key);
119
        }
120
121
        return true;
122
    }
123
124
    /**
125
     * Return the token
126
     * @param string|null $key
127
     * @return string
128
     */
129
    public function getToken(?string $key = null): string
130
    {
131
        if ($key === null) {
132
            $key = $this->getConfigValue('key');
133
        }
134
135
        $value = $this->storage->get($key);
136
        if ($value === null) {
137
            // Generate the token
138
            $value = sha1(Str::randomToken(24));
139
            $expire = $this->getConfigValue('expire') ?? 300;
140
            $expireTime = time() + $expire;
141
142
            $this->storage->set($key, $value, $expireTime);
143
        }
144
145
        return $value;
146
    }
147
148
    /**
149
     * Return the token query to be used in query string
150
     * @param string|null $key
151
     * @return array<string, string>
152
     */
153
    public function getTokenQuery(?string $key = null): array
154
    {
155
        $token = $this->getToken($key);
156
157
        if ($key === null) {
158
            $key = $this->getConfigValue('key');
159
        }
160
161
        return [$key => $token];
162
    }
163
164
    /**
165
     * Clear all CSRF data from storage
166
     * @return void
167
     */
168
    public function clear(): void
169
    {
170
        $this->storage->clear();
171
    }
172
173
    /**
174
     *
175
     * @param bool $status
176
     * @return $this
177
     */
178
    public function unique(bool $status = true): self
179
    {
180
        $this->unique = $status;
181
182
        return $this;
183
    }
184
185
    /**
186
     * Return the token from request
187
     * @param ServerRequestInterface $request
188
     * @param string $key
189
     * @return string|null
190
     */
191
    protected function getRequestToken(ServerRequestInterface $request, string $key): ?string
192
    {
193
        $param = new RequestData($request);
194
        $token = $param->post($key);
195
        if ($token === null) {
196
            $token = $param->get($key);
197
        }
198
199
        if ($token === null) {
200
            $token = $request->getHeaderLine('X-Csrf-Token');
201
        }
202
203
204
        return $token;
205
    }
206
207
    /**
208
     * Return the CSRF configuration value
209
     * @param string $key
210
     * @return mixed
211
     */
212
    private function getConfigValue(string $key)
213
    {
214
        $config = $this->config->get('security.csrf', []);
215
216
        return $config[$key] ?? null;
217
    }
218
}
219