Loads a token to the request and response

@param *Request  $request
@param *Response $response

@return Csrf
485733
public function load(Request $request, Response $response) {
        //render the key
        $key = md5(uniqid());
        if($request->hasSession('csrf')) {
            $key = $request->getSession('csrf');
        }

        $request->setSession('csrf', $key);
        $response->setResults('csrf', $key);

        return $this;
    }
89585
protected function sendResetFailedResponse(Request $request, $response): JsonResponse
    {
        return $this->response->error(trans($response));
    }
235199
public function token(Request $request)
    {
        $user = $this->getUser($request);
        
        $client = $user->clients->first();
        if (null !== $client && $client instanceof Client) {

            $serverRequest = $this->createRequest(
                $client,
                $user->id,
                $request, $scope = []
            );
            $reponse = parent::issueToken($serverRequest);
            $responseArray = json_decode($reponse->content(), true);
            unset($responseArray['refresh_token']);
            return response()->json($responseArray)
                ->setStatusCode($reponse->getStatusCode());
        }
        return response(['error' => 'Please create a client first'], 401);
    }
464082
public function resolve(Request $request, Response $response)
    {
        // Ensure to put *route* in before ;) - here.
        $route  = $request->getAttribute('route');
        $target = $route->getPresenter();

        $this
            ->response($response)
            ->route($route)
            ->className($target)
            ->action($route->getAction())
            ->initMvp($target, $this->getRegistry(), $request);

        return $this->run();
    }
1374033
public function run(Request $request, Response $response)
    {
        $this->initController($request, $response);
        $event = $this->eventDispatcher->raiseEvent(
            $this->createLoadedEvent()
        );

        if ($event->isHandled() && $event->getResponse() instanceof Response) {
            return $event->getResponse();
        }

        $this->eventDispatcher->raiseEvent(
            $this->createFinishedEvent(
                $this->runController($request, $response)
            )
        );

        return $response;
    }
1043586
private function authenticate(Request $request, Response $response)
    {
        $authenticationProvider = $this->injector->getInstance(AuthenticationProvider::class);
        try {
            $user = $authenticationProvider->authenticate($request);
            if (null == $user && $this->authConstraint->loginAllowed()) {
                $response->redirect($authenticationProvider->loginUri($request));
            } elseif (null == $user) {
                // TODO should become 401 Unauthorized
                // see https://github.com/stubbles/stubbles-webapp-core/issues/73
                $this->error = $response->forbidden();
                return null;
            }

            return $user;
        } catch (AuthProviderException $ahe) {
            $this->handleAuthProviderException($ahe, $response);
            return null;
        }
    }
551119
private function addCommonHeaders(Request $request, Response $response)
    {
        // replace content-type if a schema was requested
        if ($request->attributes->get('schemaRequest')) {
            $response->headers->set('Content-Type', 'application/schema+json');
        }

        if ($request->attributes->has('recordCount')) {
            $response->headers->set(
                'X-Record-Count',
                (string) $request->attributes->get('recordCount')
            );
        }

        // search source header?
        if ($request->attributes->has('X-Search-Source')) {
            $response->headers->set(
                'X-Search-Source',
                (string) $request->attributes->get('X-Search-Source')
            );
        }
    }
164591
protected function nonXhrJavascriptResponse($request, $response)
    {
        return ($request->getFormat($response->headers->get('Content-Type')) === 'js' &&
            ! $request->ajax()
        );
    }
135372
public function doFilter(Request $request, Response $response)
    {
        if ((int) $request->get('error') === 1) {
            return
                $response
                    ->withStatusCode(404)
                    ->write('error')
            ;
        }
    }
878321
public function handleResponse(Request $request, Response $response)
    {
        if ($response->getStatusCode() == 422) {
            $errors = $response->getOriginalContent()['validation_errors'];

            throw new HttpResponseException(
                redirect()->back()->withInput($request->input())->withErrors($errors)
            );
        }

        if ($response->getStatusCode() == 403) {
            abort(403);
        }

        return $response->isNotFound() ? abort(404) : $response->getOriginalContent();
    }
214490
public static function toResponse($request, $response)
    {
        if ($response instanceof View) {
            $response = $response->render();
        }

        if ($response instanceof Responsable) {
            $response = $response->toResponse();
        }

        if (! $response instanceof SymfonyResponse) {
            $response = response($response);
        }

        if ($response->getStatusCode() === Response::HTTP_NOT_MODIFIED) {
            $response->setNotModified();
        }

        // Tratamento finais do response
        $response = $response->prepare($request->getBaseRequest());

        // Fix Content-Type to application/json
        $charset = $response->getCharset() ?: 'UTF-8';
        if (0 === stripos($response->headers->get('Content-Type'), 'application/json') && false === stripos($response->headers->get('Content-Type'), 'charset')) {
            $response->headers->set('Content-Type', $response->headers->get('Content-Type').'; charset=' . $charset);
        }

        return $response;
    }
1023112
private function send(Response $response, Request $request = null): \Generator
    {
        \assert($this->client, "The driver has not been setup; call setup first");

        if ($this->lastWrite) {
            yield $this->lastWrite; // Prevent writing another response until the first is finished.
        }

        $shouldClose = false;

        $protocol = $request !== null ? $request->getProtocolVersion() : "1.0";

        $status = $response->getStatus();
        $reason = $response->getReason();

        $headers = $this->filter($response, $protocol, $request ? $request->getHeaderArray("connection") : []);

        $chunked = !isset($headers["content-length"])
            && $protocol === "1.1"
            && $status >= Status::OK;

        if (!empty($headers["connection"])) {
            foreach ($headers["connection"] as $connection) {
                if (\strcasecmp($connection, "close") === 0) {
                    $chunked = false;
                    $shouldClose = true;
                }
            }
        }

        if ($chunked) {
            $headers["transfer-encoding"] = ["chunked"];
        }

        $buffer = "HTTP/{$protocol} {$status} {$reason}\r\n";
        $buffer .= Rfc7230::formatHeaders($headers);
        $buffer .= "\r\n";

        if ($request !== null && $request->getMethod() === "HEAD") {
            ($this->write)($buffer, $shouldClose);
            return;
        }

        $chunk = ""; // Required for the finally, not directly overwritten, even if your IDE says otherwise.
        $body = $response->getBody();
        $streamThreshold = $this->options->getStreamThreshold();

        try {
            while (null !== $chunk = yield $body->read()) {
                if (!($length = \strlen($chunk))) {
                    continue;
                }

                if ($chunked) {
                    $chunk = \sprintf("%x\r\n%s\r\n", $length, $chunk);
                }

                if (\strlen($buffer) < $streamThreshold) {
                    $buffer .= $chunk;
                    continue;
                }

                // Initially the buffer won't be empty and contains the headers.
                // We save a separate write or the headers here.
                $promise = ($this->write)($buffer);

                $buffer = $chunk;
                $chunk = ""; // Don't use null here, because of the finally

                yield $promise;
            }

            if ($buffer !== "" || $chunked || $shouldClose) {
                yield ($this->write)($chunked ? "{$buffer}0\r\n\r\n" : $buffer, $shouldClose);
            }
        } catch (ClientException $exception) {
            return; // Client will be closed in finally.
        } finally {
            if ($chunk !== null) {
                $this->client->close();
            }
        }
    }
42503
private function create404(Http\Request $request, Http\Response $response)
    {
        $response        = $response->withStatus(404);
        $originalRequest = $request->getOriginalRequest();
        $uri             = $originalRequest->getUri();
        $escaper         = new Escaper();
        $message         = sprintf(
            "Cannot %s %s\n",
            $escaper->escapeHtml($request->getMethod()),
            $escaper->escapeHtml((string) $uri)
        );
        return $response->end($message);
    }
543193
public function check(Request $request, Response $response) {
        $actual = $request->getStage('g-recaptcha-response');
        $config = $this->app->package('global')->service('captcha-main');

        //if no config
        if(!$config
            || !isset($config['token'], $config['secret'])
            || $config['token'] === '<GOOGLE CAPTCHA TOKEN>'
            || $config['secret'] === '<GOOGLE CAPTCHA SECRET>'
        )
        {
            //let it pass
            $this->app->subflow($this->yes, $request, $response);
            return $this;
        }

        $result = CurlHandler::i()
            ->setUrl(self::END_POINT)
            ->verifyHost(false)
            ->verifyPeer(false)
            ->setPostFields(http_build_query(array(
                'secret' => $config['secret'],
                'response' => $actual
            )))
            ->getJsonResponse();

        if(!isset($result['success']) || !$result['success']) {
            //prepare to error
            $message = $this->app->package('global')->translate(static::ATTACK);
            $response->setError(true, $message);

            //and trigger a subflow
            $this->app->subflow($this->no, $request, $response);
            return $this;
        }

        //it passed
        $this->app->subflow($this->yes, $request, $response);
        return $this;
    }
1159223
protected function addCookieToResponse($request, $response)
    {
        $config = config('session');

        $response->headers->setCookie(
            new Cookie(
                'XSRF-TOKEN', $request->session()->token(), $this->availableAt(60 * $config['lifetime']),
                $config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null
            )
        );

        return $response;
    }
69254
public function authenticate(Request $request, Response $response)
    {
        $fields = $this->_config['fields'];
        if (!$this->_checkFields($request, $fields)) {
            return false;
        }
        return $this->findAdUser($request->data[$fields['username']], $request->data[$fields['password']]);
    }
469071
public function run(Request $request, Response $response) : Response {

		$strict = $this->getParam('STRICT_ROUTING');
		$case = $this->getParam('CASE_SENSITIVE');
		$method = $request->getMethod();
		$url = $request->getUri()->getPath();

		//Matching
		foreach($this->routes as $route) {
			if($route->match($url, $strict, $case) && $method == $route->getMethod()) {
				return $route->call($request, $response);
			} elseif($route->match($url, $strict, $case) && $method == 'HEAD') {
				$body = $response->getBody();
				$body->close();
				$response = $response->withBody($body);
				return $response;
			}
		}

		//Error
		$methods = array();
		foreach($this->routes as $route) {
			array_push($methods, $route->getMethod());
			if($route->match($url, $strict, $case) && $method != $route->getMethod() && in_array($method, self::$_METHODS))
				return call_user_func($this->httpErrors['405'], $request, $response);

			elseif($route->match($url, $strict, $case) && $method != $route->getMethod() && !in_array($method, self::$_METHODS))
				return call_user_func($this->httpErrors['400'], $request, $response);
		}

		if(!in_array($method, $methods) && !in_array($method, self::$_METHODS))
			return call_user_func($this->httpErrors['400'], $request, $response);
		else
			return call_user_func($this->httpErrors['404'], $request, $response);
		
	}