FormTimestamp::isValid()   C
last analyzed

Complexity

Conditions 8
Paths 7

Size

Total Lines 41
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 41
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 19
nc 7
nop 1
1
<?php
2
3
namespace Psr7Middlewares\Middleware;
4
5
use Psr7Middlewares\Utils;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use Exception;
9
10
/**
11
 * Middleware to span protection using the timestamp value in forms.
12
 */
13
class FormTimestamp
14
{
15
    use Utils\FormTrait;
16
    use Utils\CryptTrait;
17
    use Utils\AttributeTrait;
18
19
    const KEY_GENERATOR = 'FORM_TIMESTAMP_GENERATOR';
20
21
    /**
22
     * @var string The honeypot input name
23
     */
24
    private $inputName = 'hpt_time';
25
26
    /**
27
     * @var int Minimum seconds to determine whether the request is a bot
28
     */
29
    private $min = 3;
30
31
    /**
32
     * @var int Max seconds to expire the form. Zero to do not expire
33
     */
34
    private $max = 0;
35
36
    /**
37
     * Returns a callable to generate the inputs.
38
     *
39
     * @param ServerRequestInterface $request
40
     *
41
     * @return callable|null
42
     */
43
    public static function getGenerator(ServerRequestInterface $request)
44
    {
45
        return self::getAttribute($request, self::KEY_GENERATOR);
46
    }
47
48
    /**
49
     * Set the field name.
50
     *
51
     * @param string $inputName
52
     *
53
     * @return self
54
     */
55
    public function inputName($inputName)
56
    {
57
        $this->inputName = $inputName;
58
59
        return $this;
60
    }
61
62
    /**
63
     * Minimum time required.
64
     *
65
     * @param int $seconds
66
     *
67
     * @return self
68
     */
69
    public function min($seconds)
70
    {
71
        $this->min = $seconds;
72
73
        return $this;
74
    }
75
76
    /**
77
     * Max time before expire the form.
78
     *
79
     * @param int $seconds
80
     *
81
     * @return self
82
     */
83
    public function max($seconds)
84
    {
85
        $this->max = $seconds;
86
87
        return $this;
88
    }
89
90
    /**
91
     * Execute the middleware.
92
     *
93
     * @param ServerRequestInterface $request
94
     * @param ResponseInterface      $response
95
     * @param callable               $next
96
     *
97
     * @return ResponseInterface
98
     */
99
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
100
    {
101
        if (Utils\Helpers::getMimeType($response) !== 'text/html') {
102
            return $next($request, $response);
103
        }
104
105
        if (Utils\Helpers::isPost($request) && !$this->isValid($request)) {
106
            return $response->withStatus(403);
107
        }
108
109
        $value = $this->encrypt(time());
110
111
        $generator = function () use ($value) {
112
            return '<input type="hidden" name="'.$this->inputName.'" value="'.$value.'">';
113
        };
114
115 View Code Duplication
        if (!$this->autoInsert) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
116
            $request = self::setAttribute($request, self::KEY_GENERATOR, $generator);
117
118
            return $next($request, $response);
119
        }
120
121
        $response = $next($request, $response);
122
123
        return $this->insertIntoPostForms($response, function ($match) use ($generator) {
124
            return $match[0].$generator();
125
        });
126
    }
127
128
    /**
129
     * Check whether the request is valid.
130
     *
131
     * @param ServerRequestInterface $request
132
     *
133
     * @return bool
134
     */
135
    private function isValid(ServerRequestInterface $request)
136
    {
137
        $data = $request->getParsedBody();
138
139
        //value does not exists
140
        if (empty($data[$this->inputName])) {
141
            return false;
142
        }
143
144
        try {
145
            $time = $this->decrypt($data[$this->inputName]);
146
        } catch (Exception $e) {
147
            return false;
148
        }
149
150
        //value is not valid
151
        if (!is_numeric($time)) {
152
            return false;
153
        }
154
155
        $now = time();
156
157
        //sent from future
158
        if ($now < $time) {
159
            return false;
160
        }
161
162
        $diff = $now - $time;
163
164
        //check min
165
        if ($diff < $this->min) {
166
            return false;
167
        }
168
169
        //check max
170
        if ($this->max && $diff > $this->max) {
171
            return false;
172
        }
173
174
        return true;
175
    }
176
}
177