Sends a response when HTTP basic authentication fails.

@return mixed
@throws \RuntimeException
428183
public function getBasicResponse()
    {
        // Default the basic response
        if ($this->basicResponse === null) {
            $this->basicResponse = function () {
                if (headers_sent()) {
                    throw new RuntimeException('Attempting basic auth after headers have already been sent.');
                }

                header('WWW-Authenticate: Basic');
                header('HTTP/1.0 401 Unauthorized');

                echo 'Invalid credentials.';
                exit;
            };
        }

        $response = $this->basicResponse;

        return $response();
    }
232551
private function handleResponse()
    {
        if (curl_errno($this->curl)) {
            throw new NetworkError(curl_error($this->curl), curl_errno($this->curl));
        }

        $body = ($this->rawResponse) ? $this->getBody() : json_decode($this->getBody());

        $status = $this->getStatus();

        if ($status >= 400 && $status <= 499) {
            if ($this->failOnError) {
                throw new ClientError($body, $status);
            } else {
                $this->lastError = $body;
                return false;
            }
        } elseif ($status >= 500 && $status <= 599) {
            if ($this->failOnError) {
                throw new ServerError($body, $status);
            } else {
                $this->lastError = $body;
                return false;
            }
        }

        if ($this->followLocation) {
            $this->followRedirectPath();
        }

        return $body;
    }
562233
public function send()
    {
        if (empty($this->uri)) {
            throw new InvalidArgumentException('Invalid url for request.');
        }

        $customRequest = new Request();
        $customRequest->setHeaders($this->_headers);
        $this->httpClient->setRequest($customRequest);

        $this->httpClient->setMethod($this->method);
        $this->httpClient->setUri($this->uri);

        if ($this->method == Request::METHOD_GET) {
            if (!empty($this->params)) {
                $this->httpClient->setParameterGet($this->params);
            }
        }

        if ($this->method == Request::METHOD_POST) {
            if (!empty($this->params)) {
                $this->httpClient->setParameterPost($this->params);
            }
        }

        if ($this->postRawData !== null) {
            $this->httpClient->setRawBody($this->postRawData);
        }

        try {
            $this->response = $this->httpClient->send();
            if (!$this->response->isSuccess()) {
                throw new RuntimeException('Http request failure!');
            }
            $this->request = $this->httpClient->getRequest();

            return $this->response;

        } catch (HttpClientRuntimeException $exception) {
            throw new RuntimeException($exception->getMessage());
        } catch (HttpRuntimeException $exception) {
            throw new RuntimeException($exception->getMessage());
        }
    }
1223633
public function run(): SendableResponse
    {
        $request  = WebRequest::fromRawSource();
        $response = new WebResponse($request);
        if ($response->isFixed()) {
            return $response; // http version of request not supported
        }

        try {
            $requestUri = $request->uri();
        } catch (MalformedUri $mue) {
            $response->status()->badRequest();
            return $response;
        }

        $this->configureRouting($this->routing);
        $uriResource = $this->routing->findResource($requestUri, $request->method());
        if ($this->switchToHttps($request, $uriResource)) {
            $response->redirect($uriResource->httpsUri());
            return $response;
        }

        try {
            if (!$uriResource->negotiateMimeType($request, $response)) {
                return $response;
            }

            $this->sessionHandshake($request, $response);
            if ($uriResource->applyPreInterceptors($request, $response)) {
                $response->write($uriResource->resolve($request, $response));
                $uriResource->applyPostInterceptors($request, $response);
            }
        } catch (\Exception $e) {
            $this->injector->getInstance(ExceptionLogger::class)->log($e);
            $response->write($response->internalServerError($e->getMessage()));
        }

        return $response;
    }
1276468
public function index(): HTTPResponse
    {
        $body = null;
        $contentType = $this->getRequest()->getHeader('Content-Type');

        if ($contentType === 'application/json') {
            $body = json_decode($this->getRequest()->getBody(), true);
        } else {
            $body = $this->getRequest()->postVars();
        }

        if (empty($body)) {
            return $this->getErrorResponse(
                'No parameters could be found in request body. Did you correctly set the Content-Type header?',
                500
            );
        }

        // request needs parsed body
        $psrRequest = (new HttpRequestAdapter())->toPsr7($this->getRequest())
            ->withParsedBody($body);
        $psrResponse = new Response();

        $authServer = $this->serverGenerator->getServer();

        try {
            return (new HttpResponseAdapter())
                ->fromPsr7($authServer->respondToAccessTokenRequest($psrRequest, $psrResponse));
        } catch (OAuthServerException $e) {
            return $this->convertResponse($e->generateHttpResponse(new Response()));
        } catch (Exception $e) {
            return $this->getErrorResponse($e->getMessage());
        }
    }
833590
public function getResponseData(): Response
    {
        $connectionResponse = new ConnectionResponseImpl();
        $errorResponse = $this->streamSocket->read();
        if ($errorResponse !== null) {
            $this->getLogger()->error('Send error: ' . $errorResponse);
            $this->streamSocket->disconnect();
            $response = @unpack('Ccommand/Cstatus/Nidentifier', $errorResponse);
            if (!empty($response)) {
                $connectionResponse->setErrorResponse($response);
            } else {
                $connectionResponse->setErrorResponse(null);
            }
        }

        return $connectionResponse;
    }
662105
protected function authenticate()
  {
      $keys = KeyStream::GenerateKeys(base64_decode($this->password), $this->parent->getChallengeData());
      $this->inputKey = new KeyStream($keys[2], $keys[3]);
      $this->outputKey = new KeyStream($keys[0], $keys[1]);
      $array = "\0\0\0\0".$this->phoneNumber.$this->parent->getChallengeData().''.time().'000'.hex2bin('00').'000'.hex2bin('00')
       .Constants::OS_VERSION.hex2bin('00').Constants::MANUFACTURER.hex2bin('00').Constants::DEVICE.hex2bin('00').Constants::BUILD_VERSION;
      $response = $this->outputKey->EncodeMessage($array, 0, 4, strlen($array) - 4);
      $this->parent->setOutputKey($this->outputKey);

      return $response;
  }
987410
public function login() {
        if ($this->isLoggedIn()) {
            throw new BadMethodCallException('Client is already logged-in.');
        }

        // Auto-connect:
        if ($this->isConnected() === false) {
            $this->connect();
        }

        $response = $this->request(
            'idoit.login'
        );

        if (!array_key_exists('session-id', $response)) {
            throw new RuntimeException('Failed to login because i-doit responded without a session ID');
        }

        $this->session = $response['session-id'];

        return $this;
    }
300253
public function authenticate(string $username, string $password, ?string $scope = '*'): Response
    {
        $body = $this->mergeApiBody(
            \array_filter(\compact('username', 'password', 'scope'))
        );

        return $this->send('POST', 'oauth/token', $this->getApiHeaders(), $body)
                    ->validateWith(function ($statusCode, $response) {
                        if ($statusCode !== 200) {
                            throw new RuntimeException('Unable to generate access token!');
                        }

                        $this->client->setAccessToken($response->toArray()['access_token']);
                    });
    }
379480
private function getStatus()
    {
        if (!($statusArray = preg_grep('/^HTTP\/(1.0|1.1)\s+(\d+)\s+(.+)/', $this->headers))) {
            throw new \RuntimeException('Could not determine HTTP status from API response');
        }

        if (!preg_match('/^HTTP\/(1.0|1.1)\s+(\d+)\s+(.+)/', $statusArray[0], $matchesArray)) {
            throw new \RuntimeException('Could not determine HTTP status from API response');
        }

        return array(
            'code' => $matchesArray[2],
            'message' => $matchesArray[3],
        );
    }
227143
public function getTokenResponse()
    {
        $query = [
            'grant_type' => 'client_credential',
            'appid' => $this['appid'],
            'secret' => $this['appsecret'],
        ];

        $response = Http::request('GET', static::ACCESS_TOKEN)
            ->withQuery($query)
            ->send();

        if ($response->containsKey('errcode')) {
            throw new \Exception($response['errmsg'], $response['errcode']);
        }

        return $response;
    }
640282
protected function login()
    {
        if ($this->_auth) {
            return $this->_auth;
        }

        $writeBinn= new BinnList;

        $writeBinn->addInt16(self::DAEMON_SERVER_MODE_AUTH);
        $writeBinn->addStr($this->username);
        $writeBinn->addStr($this->password);
        $writeBinn->addInt16($this->mode);

        $read = $this->writeAndReadSocket($writeBinn->serialize());

        $readBinn = new BinnList;
        $readBinn->binnOpen($read);
        $results = $readBinn->unserialize();

        if ($results[0] == self::STATUS_OK) {
            $this->_auth = true;
        } else {
            throw new RuntimeException('Could not login with connection: ' . $this->host . ':' . $this->port
                . ', username: ' . $this->username);
        }

        return $this->_auth;
    }
1000744
public function noCode()
    {
        $param['TextBox1'] = $this->username;
        $param['TextBox2'] = $this->password;
        $param['RadioButtonList1_2'] = '学生';
        $param['Button1'] = "";

        $url = Config::get('url.login_no_code');
        $cookie = $this->getCookieOrNew();
        $response = $this->request('post', [$url, $param, ['cookies' => $cookie]]);

        $body = (string)$response->getBody();
        // Check the request whether have any error
        if (preg_match("/err=4/", $body)) {
            throw new HttpException("account or password error", 10002);
        } elseif (!preg_match("/xs_main/", $body)) {
            throw new HttpException("login failed!", 10003);
        }

        return $cookie;
    }
264419
public function createResponse()
    {
        if (empty($this->headers)) {
            throw new \RuntimeException('No headers have been received');
        }

        // HTTP-version SP status-code SP reason-phrase
        $startLine = explode(' ', array_shift($this->headers), 3);
        $headers = \GuzzleHttp\headers_from_lines($this->headers);
        $normalizedKeys = \GuzzleHttp\normalize_header_keys($headers);

        if (!empty($this->options['decode_content'])
            && isset($normalizedKeys['content-encoding'])
        ) {
            $headers['x-encoded-content-encoding']
                = $headers[$normalizedKeys['content-encoding']];
            unset($headers[$normalizedKeys['content-encoding']]);
            if (isset($normalizedKeys['content-length'])) {
                $headers['x-encoded-content-length']
                    = $headers[$normalizedKeys['content-length']];

                $bodyLength = (int) $this->sink->getSize();
                if ($bodyLength) {
                    $headers[$normalizedKeys['content-length']] = $bodyLength;
                } else {
                    unset($headers[$normalizedKeys['content-length']]);
                }
            }
        }

        // Attach a response to the easy handle with the parsed headers.
        $this->response = new Response(
            $startLine[1],
            $headers,
            $this->sink,
            substr($startLine[0], 5),
            isset($startLine[2]) ? (string) $startLine[2] : null
        );
    }
997386
public function getStatuses()
    {
        if (!$this->response) {
            $this->response = $this->prepareRequest()->send();
        }

        if (200 !== $this->response->getStatusCode()) {
            throw new \RuntimeException(sprintf('Client faild with "%s". Status: "%s"', $this->feedUrl , $this->response->getStatusCode()));
        }

        $statuses = $this->extractRawStatuses($this->response->getBody());

        foreach ($statuses as $status) {
            $this->statuses[] = $this->createNewStatusInstance($status);
        }

        return $this->statuses;
    }
1198798
public function handler(): Response
    {
        $data = $this->validate([
            'role_id' => [
                new NotBlank()
            ],
            'permission' => [
                new NotBlank()
            ],
            'value' => []
        ]);
        $role = Role::find($data['role_id']);
        if (!$role) {
            throw new HttpForbiddenException();
        }
        $attr = [
            'role' => $role,
            'permission' => $data['permission']
        ];
        if ($data['value'] === true) {
            (new Permission($attr))->save();
            $this->log('info', 'Add permission [' . $data['permission'] . '] of role [' . $role->getSlug() . ']');
        } else {
            $permission = Permission::findBy($attr);
            if (!$permission) {
                throw new HttpForbiddenException();
            }
            $permission->delete(true);
            $this->log('info', 'Delete permission [' . $data['permission'] . '] of role [' . $role->getSlug() . ']');
        }
        return response();
    }
88232
public function actionStopExecutable()
    {
        $rr = new RequestResponse();
        if ($rr->isRequestAjaxPost()) {
            $stoppedLong = CmsAgent::stopLongExecutable(0);
            $rr->message = \Yii::t('skeeks/agent', 'Running agents stopped');
            $rr->success = true;
            return $rr;
        }
    }