/** * Handle an incoming request. * * @param Request $request * @param \Closure $next * @return Response * @throws InvalidCsrfTokenException */ public function handle(Request $request, Closure $next) : Response { $cookieData = $request->cookie('csrfToken'); if ($cookieData) { $this->_token = $cookieData; } $createCookie = false; if ($request->method() == 'GET' and $cookieData === null) { $this->_token = hash('sha1', Text::uuid()); $createCookie = true; } if (in_array($request->method(), ['PATCH', 'PUT', 'POST', 'DELETE'])) { $post = $request->data['_csrfToken']; $header = $request->header('X-CSRF-Token'); if (empty($cookieData)) { throw new InvalidCsrfTokenException('Missing CSRF token cookie'); } if ($post !== $cookieData and $header !== $cookieData) { throw new InvalidCsrfTokenException('CSRF token mismatch'); } } $response = $next($request); if ($createCookie) { $response->cookie('csrfToken', $this->_token); } return $response; }
/** * testMultipleUuidGeneration method * * @return void */ public function testMultipleUuidGeneration() { $check = []; $count = mt_rand(10, 1000); $pattern = "/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\$/"; for ($i = 0; $i < $count; $i++) { $result = Text::uuid(); $match = (bool) preg_match($pattern, $result); $this->assertTrue($match); $this->assertFalse(in_array($result, $check)); $check[] = $result; } }
/** * Get random bytes from a secure source. * * This method will fall back to an insecure source an trigger a warning * if it cannot find a secure source of random data. * * @param int $length The number of bytes you want. * @return string Random bytes in binary. */ public static function randomBytes($length) { if (function_exists('random_bytes')) { return random_bytes($length); } if (function_exists('openssl_random_pseudo_bytes')) { $bytes = openssl_random_pseudo_bytes($length, $strongSource); if (!$strongSource) { trigger_error('openssl was unable to use a strong source of entropy. ' . 'Consider updating your system libraries, or ensuring ' . 'you have more available entropy.', E_USER_WARNING); } return $bytes; } trigger_error('You do not have a safe source of random data available. ' . 'Install either the openssl extension, or paragonie/random_compat. ' . 'Falling back to an insecure random source.', E_USER_WARNING); $bytes = ''; $byteLength = 0; while ($byteLength < $length) { $bytes .= hash('sha512', Text::uuid() . uniqid(mt_rand(), true)); $byteLength = strlen($bytes); } return substr($bytes, 0, $length); }