@EXT\Route("/assertion/{assertion}", name="apiv2_evidence_create_at")
@EXT\Method("POST")
@EXT\ParamConverter("assertion", class="ClarolineOpenBadgeBundle:Assertion", options={"mapping": {"assertion": "uuid"}})

@return JsonResponse
517155
public function createAtAction(Request $request, Assertion $assertion)
    {
        $object = $this->crud->create(
            $this->getClass(),
            $this->decodeRequest($request),
            []
        );

        $object->setAssertion($assertion);
        $this->om->persist($object);
        $this->om->flush();

        if (is_array($object)) {
            return new JsonResponse($object, 400);
        }

        return new JsonResponse(
            $this->serializer->serialize($object, []),
            201
        );
    }
1218084
function payload()
    {
        if ( $this->IsFault )
        {
            return json_encode( array(
                'result' => null,
                'error' => array( 'faultCode' => $this->FaultCode, 'faultString' => $this->FaultString ),
                'id' => $this->Id ) );
        }
        else
        {
            return json_encode( array(
                'result' => $this->Value,
                'error' => null,
                'id' => $this->Id ) );
        }
    }
591816
function assertTokenParams()
    {
        # Assert Params

        if ( null === $this->getCode() )
            throw new exMissingGrantRequestParams('Request Param "code" must Set.');

        if ( null === $this->getClientId() || null === $this->getClientSecret() )
            throw new exMissingGrantRequestParams('Request Param "client_id" & "client_secret" must Set.');


        # Build Request Params

        $params = $this->__toArray();
        unset($params['response_type']);

        return $params;
    }
253726
final function assertValidate()
    {
        $exceptions = $this->doAssertValidate();
        if (!is_array($exceptions))
            throw new \RuntimeException(sprintf(
                'Unknown Validation Assertion Value Of Type Array (%s).'
                , flatten($exceptions)
            ));

        if ( empty($exceptions) )
            return;


        // Chain Exception:

        // TODO what if assertValidator or exceptions list has \Exception instance instead of exUnexpected

        $_f__chainExceptions = function (exUnexpectedValue $ex, &$list) use (&$_f__chainExceptions)
        {
            if ( empty($list) )
                return $ex;

            /** @var exUnexpectedValue $exception */
            $exception = array_pop($list);

            $r = new exUnexpectedValue(
                $exception->getMessage()
                , $exception->getParameterName()
                , $exception->getError()
                , $_f__chainExceptions($ex, $list)
            );

            return $r;
        };

        $ex = $_f__chainExceptions(new exUnexpectedValue('Validation Error', null), $exceptions);
        throw $ex;
    }
1190157
public function serialize(Assertion $assertion, array $options = [])
    {
        if (in_array(Options::ENFORCE_OPEN_BADGE_JSON, $options)) {
            $data = [
                  'uid' => $assertion->getUuid(),
                'id' => $this->router->generate('apiv2_open_badge__assertion', ['assertion' => $assertion->getUuid()], UrlGeneratorInterface::ABSOLUTE_URL),
                'type' => 'Assertion',
                'verify' => $this->verificationObjectSerializer->serialize($assertion),
                //doc is uncomplete ? verify works but not verification. For mozilla backpack.
                //'verification' => $this->verificationObjectSerializer->serialize($assertion),
                //'recipient' => $this->identityObjectSerializer->serialize($assertion->getRecipient(), [Options::ENFORCE_OPEN_BADGE_JSON]),
                    //they don't follow their owndock ? it's for mozilla backpack
                    'recipient' => $assertion->getRecipient()->getEmail(),
                'badge' => $this->badgeSerializer->serialize($assertion->getBadge(), [Options::ENFORCE_OPEN_BADGE_JSON]),
                'issuedOn' => $assertion->getIssuedOn()->format('Y-m-d'),
                'expires' => $this->getExpireDate($assertion),
                //no implementation right now
                'revoked' => false,
            ];
        } else {
            $data = [
                'id' => $assertion->getUuid(),
                'user' => $this->userSerializer->serialize($assertion->getRecipient()),
                'badge' => $this->badgeSerializer->serialize($assertion->getBadge()),
                'data' => $this->serialize($assertion, [Options::ENFORCE_OPEN_BADGE_JSON]),
            ];
        }

        return $data;
    }
148084
public function getAssertionId()
    {
        if (!$this->validateNumAssertions()) {
            throw new InvalidArgumentException("SAML Response must contain 1 Assertion.");
        }
        $assertionNodes = $this->_queryAssertion("");
        $id = null;
        if ($assertionNodes->length == 1 && $assertionNodes->item(0)->hasAttribute('ID')) {
            $id = $assertionNodes->item(0)->getAttribute('ID');
        }
        return $id;
    }
1170801
public function toResponse(): Response
    {
        $base = [
            'return_code' => is_null($this->fail) ? static::SUCCESS : static::FAIL,
            'return_msg' => $this->fail,
        ];

        $attributes = array_merge($base, $this->attributes);

        if ($this->sign) {
            $attributes['sign'] = Support\generate_sign($attributes, $this->app->getKey());
        }

        return new Response(XML::build($attributes));
    }
385634
public function createDesignDocument()
    {
        if (!$this->doc) {
            throw new \Exception('No DesignDocument Class is connected to this view query, cannot create the design document with its corresponding view automatically!');
        }

        $data = $this->doc->getData();
        if ($data === null) {
            throw \Doctrine\CouchDB\JsonDecodeException::fromLastJsonError();
        }
        $data['_id'] = '_design/'.$this->designDocumentName;

        $response = $this->client->request(
            'PUT',
            sprintf(
                '/%s/_design/%s',
                $this->databaseName,
                $this->designDocumentName
            ),
            json_encode($data)
        );
    }
417510
public function getMyAssertionsAction(Request $request)
    {
        $user = $this->tokenStorage->getToken()->getUser();
        $assertions = $this->finder->search(Assertion::class, array_merge(
            $request->query->all(),
            ['hiddenFilters' => ['recipient' => $user->getUuid()]]
        ));

        return new JsonResponse($assertions);
    }
112243
public function refreshTokenWithAssertion($assertionCredentials = null)
  {
    if (!$assertionCredentials) {
      $assertionCredentials = $this->assertionCredentials;
    }

    $cacheKey = $assertionCredentials->getCacheKey();

    if ($cacheKey) {
      // We can check whether we have a token available in the
      // cache. If it is expired, we can retrieve a new one from
      // the assertion.
      $token = $this->client->getCache()->get($cacheKey);
      if ($token) {
        $this->setAccessToken($token);
      }
      if (!$this->isAccessTokenExpired()) {
        return;
      }
    }

    $this->client->getLogger()->debug('OAuth2 access token expired');
    $this->refreshTokenRequest(
        array(
          'grant_type' => 'assertion',
          'assertion_type' => $assertionCredentials->assertionType,
          'assertion' => $assertionCredentials->generateAssertion(),
        )
    );

    if ($cacheKey) {
      // Attempt to cache the token.
      $this->client->getCache()->set(
          $cacheKey,
          $this->getAccessToken()
      );
    }
  }
531871
public function uploadAction ()
    {
        $handle = $this->getRequest()->files->get('file');
        
        if ($handle && $handle->getError()){
            return new JsonResponse(array(
                'success' => false,
                'err_msg' => $this->container->get('translator')
                    ->trans('file_upload_http_error', array(), 'ThraceMediaBundle')
            ));
        }

        $imageManager = $this->container->get('thrace_media.imagemanager');
        $options = $this->container->getParameter('thrace_media.plupload.options');
        $extension = $handle->getClientOriginalExtension();
        $name = uniqid() . '.' . $extension;
        
        if(!$extension){
            return new JsonResponse(array(
                'success' => false,
                'err_msg' => sprintf('Unknown Mime Type: "%s"', $handle->getMimeType())
            ));
        }

        $validate = $this->validateImage($handle);

        if ($validate !== true) {
            return new JsonResponse(array(
                'success' => false,
                'err_msg' => $validate
            ));
        }

        $content = $imageManager->normalizeImage(
            $name, file_get_contents($handle->getRealPath()), 
            $options['normalize_width'], $options['normalize_height']
        );
        
        $imageManager->saveToTemporaryDirectory($name, $content);
        $imageManager->makeImageCopyToOriginalDirectory($name);
        $hash = $imageManager->checksumTemporaryFileByName($name);

        return new JsonResponse(array(
            'success' => true,
            'name'    => $name,
            'hash'    => $hash
        ));
    }
214335
function payload()
    {
        if ( $this->IsFault )
        {
            return json_encode( array(
                'content' => null,
                'error_text' => $this->FaultString() ) );
        }
        else
        {
            return json_encode( array(
                'content' => $this->Value,
                'error_text' => null ) );
        }
    }
1085845
protected function createDefaultJwtAccessTokenResponseType()
    {
        if (!isset($this->storages['public_key'])) {
            throw new \LogicException('You must supply a storage object implementing OAuth2\Storage\PublicKeyInterface to use crypto tokens');
        }

        $tokenStorage = null;
        if (isset($this->storages['access_token'])) {
            $tokenStorage = $this->storages['access_token'];
        }

        $refreshStorage = null;
        if (isset($this->storages['refresh_token'])) {
            $refreshStorage = $this->storages['refresh_token'];
        }

        $config = array_intersect_key($this->config, array_flip(explode(' ', 'store_encrypted_token_string issuer access_lifetime refresh_token_lifetime jwt_extra_payload_callable')));

        return new JwtAccessToken($this->storages['public_key'], $tokenStorage, $refreshStorage, $config);
    }
1147440
public function templateAction()
    {
        try {
            $jobEntity = $this->initializeJob()->get($this->params());
            $jobEntity->setTemplate($this->params('template', 'default'));
            $this->repositoryService->store($jobEntity);
            $this->notification()->success(/* @translate*/ 'Template changed');
        } catch (\Exception $e) {
            $this->notification()->danger(/* @translate */ 'Template not changed');
        }

        return new JsonModel(array());
    }
1212250
public function verifyAssertion($assertion)
    {

        /*$url = 'https://verifier.login.persona.org/verify';
        $data = 'assertion='.$assertion.'&audience=http://persona.localhost:80';

        $params = array(
            'http' => array(
                'method' => 'POST',
                'content' => $data
            ),
            'ssl' => array(
                'verify_peer' => true,
                'verify_host' => true
            )
        );
        $context = stream_context_create($params);
        $result = file_get_contents($url, false, $context);

        return $result;*/

        $postdata = 'assertion=' . urlencode($assertion) . '&audience='.$this->guessAudience();

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://verifier.login.persona.org/verify");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        $response = curl_exec($ch);
        curl_close($ch);



        return json_decode($response);
    }
588926
protected function doExecute(AssertionContext $context)
    {
        $authnContext = new AuthnContext();
        $authnContextClassRef = $this->sessionInfoProvider->getAuthnContextClassRef() ?: SamlConstants::AUTHN_CONTEXT_UNSPECIFIED;
        $authnContext->setAuthnContextClassRef($authnContextClassRef);

        $authnStatement = new AuthnStatement();
        $authnStatement->setAuthnContext($authnContext);
        $sessionIndex = $this->sessionInfoProvider->getSessionIndex();
        if ($sessionIndex) {
            $authnStatement->setSessionIndex($sessionIndex);
        }
        $authnInstant = $this->sessionInfoProvider->getAuthnInstant() ?: new \DateTime();
        $authnStatement->setAuthnInstant($authnInstant);

        $subjectLocality = new SubjectLocality();
        $subjectLocality->setAddress($context->getProfileContext()->getHttpRequest()->getClientIp());
        $authnStatement->setSubjectLocality($subjectLocality);

        $context->getAssertion()->addItem($authnStatement);
    }
55041
protected function getToken()
    {
        /* @var ResponseInterface $response */
        $response = $this->post(self::TOKEN_URI, [
            'body' => [
                'grant_type' => 'authorization_code',
                'code' => $this->getCodeQueryField(),
                'client_id' => $this->clientId,
                'client_secret' => $this->clientSecret
            ]
        ]);

        if ($response->getStatusCode() == 200) {
            $this->setPropertiesBasedOnSuccessResponse($response->json());

            return;
        }

        $response = $response->json();
        throw new OAuthException("{$response['error']}:{$response['error_description']}");
    }