Process the SAML Response sent by the IdP.

@param string|null $requestId The ID of the AuthNRequest sent by this SP to the IdP

@throws OneLogin_Saml2_Error
342473
public function processResponse($requestId = null)
    {
        $this->_errors = array();
        $this->_errorReason = null;
        if (isset($_POST) && isset($_POST['SAMLResponse'])) {
            // AuthnResponse -- HTTP_POST Binding
            $response = new OneLogin_Saml2_Response($this->_settings, $_POST['SAMLResponse']);
            $this->_lastResponse = $response->getXMLDocument();

            if ($response->isValid($requestId)) {
                $this->_attributes = $response->getAttributes();
                $this->_attributesWithFriendlyName = $response->getAttributesWithFriendlyName();
                $this->_nameid = $response->getNameId();
                $this->_nameidFormat = $response->getNameIdFormat();
                $this->_nameidNameQualifier = $response->getNameIdNameQualifier();
                $this->_authenticated = true;
                $this->_sessionIndex = $response->getSessionIndex();
                $this->_sessionExpiration = $response->getSessionNotOnOrAfter();
                $this->_lastMessageId = $response->getId();
                $this->_lastAssertionId = $response->getAssertionId();
                $this->_lastAssertionNotOnOrAfter = $response->getAssertionNotOnOrAfter();
            } else {
                $this->_errors[] = 'invalid_response';
                $this->_errorReason = $response->getError();
            }
        } else {
            $this->_errors[] = 'invalid_binding';
            throw new OneLogin_Saml2_Error(
                'SAML Response not found, Only supported HTTP_POST Binding',
                OneLogin_Saml2_Error::SAML_RESPONSE_NOT_FOUND
            );
        }
    }
234206
public function read($sessionId) {
        try {
            // try to retrieve the session content first to see if it exists
            $result = $this->_tableRestProxy->getEntity($this->_sessionContainer, $this->_sessionContainerPartition, $sessionId);
            // get the entity instance
            $entity = $result->getEntity();
            // deflat the serialized data
            return unserialize(base64_decode($entity->getPropertyValue('data')));
        } catch (ServiceException $e) {
            // the entity doesn't exist, return empty string according to the spec:
            //   http://www.php.net/manual/en/sessionhandlerinterface.read.php
            return '';
        }
    }
986688
private function parseAuthnStatement(DOMElement $xml) : void
    {
        /** @var \DOMElement[] $authnStatements */
        $authnStatements = Utils::xpQuery($xml, './saml_assertion:AuthnStatement');
        if (empty($authnStatements)) {
            $this->authnInstant = null;

            return;
        } elseif (count($authnStatements) > 1) {
            throw new \Exception('More than one <saml:AuthnStatement> in <saml:Assertion> not supported.');
        }
        $authnStatement = $authnStatements[0];

        if (!$authnStatement->hasAttribute('AuthnInstant')) {
            throw new \Exception('Missing required AuthnInstant attribute on <saml:AuthnStatement>.');
        }
        $this->authnInstant = Utils::xsDateTimeToTimestamp($authnStatement->getAttribute('AuthnInstant'));

        if ($authnStatement->hasAttribute('SessionNotOnOrAfter')) {
            $this->sessionNotOnOrAfter = Utils::xsDateTimeToTimestamp(
                $authnStatement->getAttribute('SessionNotOnOrAfter')
            );
        }

        if ($authnStatement->hasAttribute('SessionIndex')) {
            $this->sessionIndex = $authnStatement->getAttribute('SessionIndex');
        }

        $this->parseAuthnContext($authnStatement);
    }
334750
public static function cancel_data_request($requestid) {
        global $USER;

        $warnings = [];
        $params = external_api::validate_parameters(self::cancel_data_request_parameters(), [
            'requestid' => $requestid
        ]);
        $requestid = $params['requestid'];

        // Validate context and access to manage the registry.
        $context = context_user::instance($USER->id);
        self::validate_context($context);

        // Ensure the request exists.
        $select = 'id = :id AND (userid = :userid OR requestedby = :requestedby)';
        $params = ['id' => $requestid, 'userid' => $USER->id, 'requestedby' => $USER->id];
        $requests = data_request::get_records_select($select, $params);
        $requestexists = count($requests) === 1;

        $result = false;
        if ($requestexists) {
            $request = reset($requests);
            $datasubject = $request->get('userid');

            if ($datasubject !== $USER->id) {
                // The user is not the subject. Check that they can cancel this request.
                if (!api::can_create_data_request_for_user($datasubject)) {
                    $forusercontext = \context_user::instance($datasubject);
                    throw new required_capability_exception($forusercontext,
                            'tool/dataprivacy:makedatarequestsforchildren', 'nopermissions', '');
                }
            }

            // TODO: Do we want a request to be non-cancellable past a certain point? E.g. When it's already approved/processing.
            $result = api::update_request_status($requestid, api::DATAREQUEST_STATUS_CANCELLED);
        } else {
            $warnings[] = [
                'item' => $requestid,
                'warningcode' => 'errorrequestnotfound',
                'message' => get_string('errorrequestnotfound', 'tool_dataprivacy')
            ];
        }

        return [
            'result' => $result,
            'warnings' => $warnings
        ];
    }
644777
function acs()
    {

        /** @var $auth OneLogin_Saml2_Auth */
        $auth = $this->auth;

        $auth->processResponse();

        $errors = $auth->getErrors();

        if (!empty($errors)) {
            return $errors;
        }

        if (!$auth->isAuthenticated()) {
            return array('error' => 'Could not authenticate');
        }

        return null;

    }
334078
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $requestHandler = $request->getAttributes()['requestHandler'][2]['handler'] ?? '';
        $service = App::getBean(AuthServiceInterface::class);
        if (!$service instanceof AuthServiceInterface) {
            throw new AuthException(ErrorCode::POST_DATA_NOT_PROVIDED, 'AuthService should implement Swoft\Auth\Mapping\AuthServiceInterface');
        }
        if (!$service->auth($requestHandler, $request)) {
            throw new AuthException(ErrorCode::ACCESS_DENIED);
        }
        $response = $handler->handle($request);
        return $response;
    }
619170
public function delete($attachmentId = null)
    {
        $attachment = $this->Attachments->get($attachmentId);
        $this->_checkAuthorization($attachment);
        $this->Attachments->delete($attachment);
        return new ServiceResponse('success');
    }
116074
public function handleRemove(int $userId) : void
    {
        if ($this->presenter->isAjax())
        {
            $this->userEntity = $this->userRepository->findOneById($userId);

            $allowRemove = (
                (
                    !$this->userEntity->isInRole(UserAuthorizator::ROLE_ADMIN)
                    || $this->presenter->user->isAllowed(UserAuthorizator::RES_EDIT_ADMINS)
                )
                && $this->presenter->user->isAllowed(UserAuthorizator::RES_REMOVE_HANDLE)
                && $userId !== $this->presenter->user->getId()
            );

            if (!$allowRemove)
            {
                throw new ForbiddenRequestException;
            }

            $this->userManager->delete($this->userEntity);

            $this->presenter->notificationAjax(
                'Uživatel odstaněn.',
                "Uživatel {$this->userEntity->getEmail()} byl úspěšně odstaněn.",
                    'info',
                    FALSE
                );

            $this->presenter->handleModalToggle('hide', '#wakers_user_remove_modal', FALSE);

            $this->onRemove();
        }
    }
647304
private function process()
    {
        $this->processor->post($this->url, $this->requestJson);

        if (!$this->processor->error) {
            return $this->processor->response;
        }
        $error_message = null;
        $error_code    = null;
        if ($this->processor->error_code) {
            $error_message = $this->processor->error_message;
            $error_code    = $this->processor->error_code;
        }
        throw new AuthnetCurlException(sprintf('Connection error: %s (%s)', $error_message, $error_code));
    }
236198
public function getSessionTokenWithLogin($requestToken, $username, $password)
    {
        $validatedRequestToken = $this->validateRequestTokenWithLogin($requestToken, $username, $password);

        if (!$validatedRequestToken['success']) {
            throw new \InvalidArgumentException('Unable to validate the request_token, please check your credentials.');
        }

        return $this->getNewSession($validatedRequestToken['request_token']);
    }
1030178
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $parser = App::getBean(AuthorizationParserInterface::class);
        if (!$parser instanceof AuthorizationParserInterface) {
            throw new AuthException(ErrorCode::POST_DATA_NOT_PROVIDED, 'AuthorizationParser should implement Swoft\Auth\Mapping\AuthorizationParserInterface');
        }
        $request = $parser->parse($request);
        $response = $handler->handle($request);
        return $response;
    }
265271
protected function processRequest($requestData)
    {
        $responseData = ['jsonrpc' => '2.0'];

        try {
            $method = ArrayHelper::getValue($requestData, 'method', '-');
            \Yii::trace('Running JSON-RPC 2.0 method: ' . $method, 'jsonrpc\Action::processRequest');

            \Yii::beginProfile('jsonrpc.controller.rpc.' . $method);

            $requestModel = $this->getRequestModel($requestData);
            $responseData['id'] = $requestModel->id;

            $reflectionMethod = $this->getControllerMethod($requestModel->method);
            $methodParams = $this->getMethodParams($reflectionMethod, $requestModel->params);

            $responseData['result'] = $this->runControllerAction($reflectionMethod->getName(), $methodParams);

            \Yii::endProfile('jsonrpc.controller.rpc.' . ArrayHelper::getValue($requestData, 'method', '-'));
        } catch (\Exception $ex) {
            unset($responseData['result']);

            $responseData['error'] = [
                'code' => $ex->getCode(),
                'message' => $ex->getMessage(),
                'data' => ($ex instanceof ValidationException) 
                    ? $ex->getData()
                    : null,
            ];
        }

        return $responseData;
    }
112877
protected function emitShorteningEvents($requestId, $url)
    {
        $host = Url::extractHost($url);
        list($privateDeferred, $userFacingPromise) = $this->preparePromises();

        $eventName = 'url.shorten.';
        if (count($this->emitter->listeners($eventName . $host)) > 0) {
            $eventName .= $host;
            $this->logDebug('[' . $requestId . ']Emitting: ' . $eventName);
            $this->emitter->emit($eventName, [$url, $privateDeferred]);
        } elseif (count($this->emitter->listeners($eventName . 'all')) > 0) {
            $eventName .= 'all';
            $this->logDebug('[' . $requestId . ']Emitting: ' . $eventName);
            $this->emitter->emit($eventName, [$url, $privateDeferred]);
        } else {
            $this->loop->addTimer(0.1, function () use ($privateDeferred) {
                $privateDeferred->reject();
            });
        }

        return $userFacingPromise;
    }
599934
public function userIdToOpenid(string $userId, int $agentId = null)
    {
        $params = [
            'userid' => $userId,
            'agentid' => $agentId,
        ];

        return $this->httpPostJson('cgi-bin/user/convert_to_openid', $params);
    }
195657
protected function _handleAuth( $userid,  $password)
    {
        if (!$this->_auth) {
            return true;
        }
        $this->_auth->setCredentials($userid, $password);
        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($this->_auth);
        if ($result->isValid()) {
            if (!$this->isSession()) {
                $this->setSession();
            }
            return true;
        } else {
            // authentication failed, good bye
            require_once 'Zend/Amf/Server/Exception.php';
            throw new Zend_Amf_Server_Exception(
                "Authentication failed: " . join("\n",
                    $result->getMessages()), $result->getCode());
        }

    }
335991
public function loginAsUser($userId, $originalUserId)
    {
        $this->session->put('sudosu.has_sudoed', true);
        $this->session->put($this->sessionKey, $originalUserId);

        $this->auth->loginUsingId($userId);
    }
1265350
public function beforeMethod(RequestInterface $request, ResponseInterface $response)
    {
        if ($this->currentPrincipal) {
            // We already have authentication information. This means that the
            // event has already fired earlier, and is now likely fired for a
            // sub-request.
            //
            // We don't want to authenticate users twice, so we simply don't do
            // anything here. See Issue #700 for additional reasoning.
            //
            // This is not a perfect solution, but will be fixed once the
            // "currently authenticated principal" is information that's not
            // not associated with the plugin, but rather per-request.
            //
            // See issue #580 for more information about that.
            return;
        }

        $authResult = $this->check($request, $response);

        if ($authResult[0]) {
            // Auth was successful
            $this->currentPrincipal = $authResult[1];
            $this->loginFailedReasons = null;

            return;
        }

        // If we got here, it means that no authentication backend was
        // successful in authenticating the user.
        $this->currentPrincipal = null;
        $this->loginFailedReasons = $authResult[1];

        if ($this->autoRequireLogin) {
            $this->challenge($request, $response);
            throw new NotAuthenticated(implode(', ', $authResult[1]));
        }
    }