Validates the signature of the current request

@access protected
@author Joel Bout, <joel@taotesting.com>
@param  common_http_Request request
@throws common_Exception exception thrown if validation fails
488512
public function validate(common_http_Request $request, \common_http_Credentials $credentials = null) {
        $server = new OAuthServer($this->getDataStore());
		$method = new OAuthSignatureMethod_HMAC_SHA1();
        $server->add_signature_method($method);
        
        try {
            $oauthRequest = $this->getOauthRequest($request);
            $server->verify_request($oauthRequest);
        } catch (OAuthException $e) {
            throw new \common_http_InvalidSignatureException('Validation failed: '.$e->getMessage());
        }
    }
358495
public function isValid()
    {
        $singleAssertion = $this->validateNumAssertions();
        if (!$singleAssertion) {
            throw new Exception('Multiple assertions are not supported');
        }

        $validTimestamps = $this->validateTimestamps();
        if (!$validTimestamps) {
            throw new Exception('Timing issues (please check your clock settings)');
        }

        $objXMLSecDSig = new XMLSecurityDSig();

        $objDSig = $objXMLSecDSig->locateSignature($this->_document);
        if (!$objDSig) {
            throw new Exception('Cannot locate Signature Node');
        }
        $objXMLSecDSig->canonicalizeSignedInfo();
        $objXMLSecDSig->idKeys = array('ID');

        $objKey = $objXMLSecDSig->locateKey();
        if (!$objKey) {
            throw new Exception('We have no idea about the key');
        }

        try {
            $objXMLSecDSig->validateReference();
        } catch (Exception $e) {
            throw new Exception('Reference Validation Failed');
        }

        XMLSecEnc::staticLocateKeyInfo($objKey, $objDSig);

        $objKey->loadKey($this->_settings->idpPublicCertificate, false, true);

        return ($objXMLSecDSig->verify($objKey) === 1);
    }
174522
public function check()
    {
        $request = Request::createFromGlobals();
        $serverSoftware = $request->server->get('SERVER_SOFTWARE', '');
        $isApache = strpos($serverSoftware, 'Apache') !== false;
        if (!$isApache) {
            return;
        }

        $path = $this->pathResolver->resolve('%web%/.htaccess');
        if (is_readable($path)) {
            return;
        }

        throw new ApacheValidationException();
    }
905762
def validate_query_params(self, request):
        
        # TODO: For jsonapi error object conformance, must set jsonapi errors "parameter" for
        # the ValidationError. This requires extending DRF/DJA Exceptions.
        for qp in request.query_params.keys():
            if not self.query_regex.match(qp):
                raise ValidationError('invalid query parameter: {}'.format(qp))
            if len(request.query_params.getlist(qp)) > 1:
                raise ValidationError(
                    'repeated query parameter not allowed: {}'.format(qp))
977912
public function load() {

        if (!$this->hasRequestParameter('uri')) {
            throw new common_exception_MissingParameter('uri', __METHOD__);
        }
        if (!$this->hasRequestParameter('stylesheetUri')) {
            throw new common_exception_MissingParameter('stylesheetUri', __METHOD__);
        }
        if (!$this->hasRequestParameter('lang')) {
            throw new common_exception_MissingParameter('lang', __METHOD__);
        }
        
        $item = new \core_kernel_classes_Resource($this->getRequestParameter('uri'));
        $lang = $this->getRequestParameter('lang');
        $styleSheet = $this->getRequestParameter('stylesheetUri');
        if (!\tao_helpers_File::securityCheck($styleSheet, true)) {
            throw new \common_exception_Error('invalid stylesheet path "'.$styleSheet.'"');
        }



        $cssArray = CssHelper::loadCssFile($item, $lang, $styleSheet);
        echo json_encode($cssArray);
    }
1076742
public function login()
    {
        try {

            if (!$this->hasRequestParameter('successCallback')) {
                throw new \common_exception_MissingParameter ('Internal error, please retry in few moment');
            }

            if ($this->isRequestPost()) {
                $authorizationService = $this->getServiceLocator()->get(Authorization::SERVICE_ID);

                if (!$authorizationService instanceof RequireUsername) {
                    throw new InvalidCallException('Authenticator need to be call by requireusername');
                }

                if ($authorizationService->validateLogin($this->getRequestParameter('login'))) {
                    $baseUrl = $this->getServiceLocator()
                        ->get(\common_ext_ExtensionsManager::SERVICE_ID)
                        ->getExtensionById('taoClientDiagnostic')
                        ->getConstant('BASE_URL');
                    $elements = parse_url($baseUrl);
                    $this->setCookie('login', $this->getRequestParameter('login'), null, $elements['path']);
                    $this->redirect($this->getRequestParameter('successCallback'));
                }
            }

        } catch (InvalidLoginException $e) {
            $this->setData('errorMessage', $e->getUserMessage());
        }

        $this->setData('successCallback', $this->getRequestParameter('successCallback'));
        $this->setData('client_config_url', $this->getClientConfigUrl());
        $this->setData('content-controller', 'taoClientDiagnostic/controller/Authenticator/login');
        $this->setData('content-template', 'Authenticator' . DIRECTORY_SEPARATOR . 'login.tpl');
        $this->setView('index.tpl');
    }
868382
@RequirePOST
    public FormValidation doPostBack(StaplerRequest req) throws IOException, GeneralSecurityException {
        DownloadSettings.checkPostBackAccess();
        return updateData(IOUtils.toString(req.getInputStream(),"UTF-8"), true);
    }
1315468
public function startLtiSession(common_http_Request $request)
    {
        try {
            /** @var FactoryLtiAuthAdapterService $factoryAuth */
            $factoryAuth = $this->getServiceLocator()->get(FactoryLtiAuthAdapterServiceInterface::SERVICE_ID);
            $adapter     = $factoryAuth->create($request);

            $user = $adapter->authenticate();

            $session = new TaoLtiSession($user);

            $this->getServiceLocator()->propagate($session);
            common_session_SessionManager::startSession($session);
        } catch (LtiInvalidVariableException $e) {
            $this->getServiceLocator()
                ->get(LoggerService::SERVICE_ID)
                ->log(LogLevel::INFO, $e->getMessage());

            throw new LtiException(
                __('You are not authorized to use this system'),
                LtiErrorMessage::ERROR_UNAUTHORIZED
            );
        }
    }
111065
protected function validate()
    {
        if (!CommonUtils::isRegexExpr($this->pattern)) {
            return false;
        }

        return (bool) preg_match(
            $this->pattern,
            $this->getRequestValue()
        );
    }
358620
private static void validateForCurrentMode(HttpMessage request) throws ApiException {
		if (!isValidForCurrentMode(request.getRequestHeader().getURI())) {
			throw new ApiException(ApiException.Type.MODE_VIOLATION);
		}
	}
562086
private function checkSignature($request, $consumer, $token)
    {
        // this should probably be in a different method
        $timestamp = $request instanceof Request
            ? $request->getParameter('oauth_timestamp')
            : null;
        $nonce = $request instanceof Request
            ? $request->getParameter('oauth_nonce')
            : null;

        $this->checkTimestamp($timestamp);
        $this->checkNonce($consumer, $token, $nonce, $timestamp);

        $signature_method = $this->getSignatureMethod($request);

        $signature = $request->getParameter('oauth_signature');
        $valid_sig = $signature_method->checkSignature(
            $request,
            $consumer,
            $token,
            $signature
        );

        if (!$valid_sig) {
            throw new Exception("Invalid signature");
        }
    }
394337
public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature )
	{
		$decoded_sig = base64_decode($request->urldecode($signature));
		  
		// Fetch the public key cert based on the request
		$cert = $this->fetch_public_cert($request);
		
		// Pull the public key ID from the certificate
		$publickeyid = openssl_get_publickey($cert);
		
		// Check the computed signature against the one passed in the query
		$ok = openssl_verify($base_string, $decoded_sig, $publickeyid);   
		
		// Release the key resource
		openssl_free_key($publickeyid);
		return $ok == 1;
	}
1364029
public function fileExists()
    {
        if (!$this->hasRequestParameter('uri') || !$this->hasRequestParameter('path') || !$this->hasRequestParameter('lang')) {
            throw new common_exception_MissingParameter();
        }

        $item = $this->getResource($this->getRequestParameter('uri'));
        $itemLang = $this->getRequestParameter('lang');

        try {
            $resolver = new ItemMediaResolver($item, $itemLang);
            $asset = $resolver->resolve($this->getRequestParameter('path'));
            $asset->getMediaSource()->getFileInfo($asset->getMediaIdentifier());
            $found = true;
        } catch (tao_models_classes_FileNotFoundException $exception) {
            $found = false;
        }
        return $this->returnJson(array(
            'exists' => $found
        ));
    }
660204
protected final void validateSuccess(final Status status) {
        String statusValue = status.getStatusCode().getValue();
        if (!StatusCode.SUCCESS.equals(statusValue)) {
            final StatusMessage statusMessage = status.getStatusMessage();
            if (statusMessage != null) {
                statusValue += " / " + statusMessage.getMessage();
            }
            throw new SAMLException("Response is not success ; actual " + statusValue);
        }
    }
570596
private static function validation() {
        if (isset(self::$config['validators'])) {
            $validators = self::$config['validators'];
        }
        else {
            $validators = true;
        }

        // action name validation
        if ($validators === true || (!isset($validators['actionName']) || $validators['actionName'] === true)) {
            if (substr(PHPMVC_ACTION, 0, 2) == '__') {
                throw new ActionNameValidationException();
            }
        }

        // request verification token
        $antiForgeryTokenForAction = InternalHelper::getStaticPropertyValue('\\PhpMvc\\ValidateAntiForgeryToken', 'enable');
        if ($antiForgeryTokenForAction === true || (($validators === true || (!isset($validators['antiForgeryToken']) || $validators['antiForgeryToken'] === true)) && $antiForgeryTokenForAction !== false)) {
            $request = self::$config['httpContext']->getRequest();

            if ($request->isPost()) {
                $post = $request->post();
                $expected = $request->cookies('__requestVerificationToken');

                if (!isset($post)) { $post = array(); }

                if (
                    (isset($expected) && $expected !== 'false' && (!isset($post['__requestVerificationToken']) || $post['__requestVerificationToken'] != $expected)) ||
                    (isset($expected) && $expected === 'false' && !empty($post['__requestVerificationToken'])) ||
                    (isset($post['__requestVerificationToken']) && empty($expected))
                   ) {
                    throw new HttpAntiForgeryException();
                }
            }
        }

        // cross site scripting validation
        if ($validators === true || (!isset($validators['crossSiteScripting']) || $validators['crossSiteScripting'] === true)) {
            $request = self::$config['httpContext']->getRequest();

            $get = $request->get();
            $post = $request->post();

            if (!isset($get)) { $get = array(); }
            if (!isset($post)) { $post = array(); }

            $items = array_merge($get, $post);

            foreach ($items as $key => $value) {
                $isDangerousString = CrossSiteScriptingValidation::IsDangerousString($key) || CrossSiteScriptingValidation::IsDangerousString($value);
    
                if ($isDangerousString) {
                    $source = null;

                    if (!empty($get[$key])) {
                        $source = '$_GET';
                    }
                    elseif (!empty($post[$key])) {
                        $source = '$_POST';
                    }
    
                    throw new HttpRequestValidationException($source, $key, $value);
                }
            }
        }
    }
1309494
public function submitResponses() {

        $success = false;
        $itemUri = $this->getItemUri();

        if(!empty($itemUri)){

            $this->processResponses(new core_kernel_classes_Resource($itemUri));
            $success = true;
        }else{
            throw new common_Exception('missing required itemId');
        }
    }
442869
public function verify()
    {
        $data = file_get_contents("php://input");
        $data = Xml::xmlToArr($data);
        if ($data['sign'] != Helper::signature($data, Datasheet::get('md5_key'))) {
            throw new \Exception('微信异步通信签名验证失败');
        }
        return $data;
    }