Esempio n. 1
0
 /**
  * {@inheritdoc}
  */
 public function startAuthentication(TokenInterface $token, HttpRequest $request, HttpResponse $response)
 {
     if (!$token instanceof HttpDigestToken) {
         throw new SecurityException(sprintf('Invalid token %s passed to %s', get_class($token), get_class($this)));
     }
     $params = ['realm' => $this->auth->getRealm(), 'qop' => $this->auth->getQualityOfProtection(), 'opaque' => $this->auth->getOpaque(), 'nonce' => $this->auth->createNonce($this->securityContext)];
     if ($token->isStale()) {
         $params['stale'] = true;
     }
     $authString = 'Digest ';
     $i = 0;
     foreach ($params as $name => $value) {
         if ($i++ > 0) {
             $authString .= ',';
         }
         if (is_bool($value)) {
             $authString .= sprintf('%s=%s', $name, $value ? 'true' : 'false');
         } elseif (is_numeric($value)) {
             $authString .= sprintf('%s=%s', $name, $value);
         } else {
             $authString .= sprintf('%s="%s"', $name, str_replace('"', '\\"', trim($value)));
         }
     }
     $response->setStatus(Http::CODE_UNAUTHORIZED);
     $response->setReason(Http::getReason(Http::CODE_UNAUTHORIZED));
     $response->addHeader('WWW-Authenticate', $authString);
 }
 public function generateResponse($result, RoutingContextInterface $context)
 {
     if (is_array($result) || $result instanceof \JsonSerializable) {
         $response = new HttpResponse();
         $response->setEntity(new JsonEntity($result));
         return $response;
     }
 }
Esempio n. 3
0
 public function buildResponse($status = WebDav::CODE_MULTI_STATUS)
 {
     $response = new HttpResponse($status);
     $response->setHeader('Content-Type', 'application/xml; charset="utf-8"');
     $response->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate');
     $response->setEntity([$this, 'streamResponse']);
     return $response;
 }
Esempio n. 4
0
 /**
  * {@inheritdoc}
  */
 public function startAuthentication(TokenInterface $token, HttpRequest $request, HttpResponse $response)
 {
     if (!$token instanceof HttpBasicToken) {
         throw new SecurityException(sprintf('Invalid token %s passed to %s', get_class($token), get_class($this)));
     }
     $response->setStatus(Http::CODE_UNAUTHORIZED);
     $response->setReason(Http::getReason(Http::CODE_UNAUTHORIZED));
     $response->addHeader('WWW-Authenticate', sprintf('Basic realm="%s"', $this->auth->getRealm()));
 }
Esempio n. 5
0
 public function render(ViewModelInterface $model, $onlyEntity = false)
 {
     if ($onlyEntity) {
         return $this->performInclude($model);
     }
     $response = new HttpResponse();
     $response->setHeader('Content-Type', 'text/html; charset="utf-8"');
     $response->setEntity($this->performInclude($model));
     return $response;
 }
 public function __invoke(RoutingContextInterface $context)
 {
     $match = $context->getRouteMatch();
     $identifier = (string) $match->getParameter('identifier');
     $pipeline = $this->manager->findPipeline($identifier);
     $pipeHash = $pipeline->getHash();
     $etag = new EntityTag($pipeHash);
     $ttl = $pipeline->getTtl();
     $expires = new \DateTimeImmutable('@' . (time() + $ttl));
     $response = $context->getRequest()->evaluatePreconditions($etag);
     if ($response !== NULL) {
         $response->setHeader('Cache-Control', sprintf('public, max-age=%u', $ttl));
         $response->setHeader(new ExpiresHeader($expires));
         return $response;
     }
     if (is_dir($this->cachePath)) {
         foreach (glob($this->cachePath . '/' . $identifier . '-*', GLOB_NOSORT) as $file) {
             @unlink($file);
         }
     }
     $response = new HttpResponse();
     $response->setHeader('Content-Type', sprintf('%s; charset="%s"', $pipeline->getMediaType(), $pipeline->getEncoding()));
     $response->setHeader('Access-Control-Allow-Origin', '*');
     $response->setHeader('Cache-Control', sprintf('public, max-age=%u', $ttl));
     $response->setHeader('ETag', $etag);
     $response->setHeader(new ExpiresHeader($expires));
     if (is_dir($this->cachePath)) {
         $file = $this->cachePath . '/' . $identifier . '-' . $pipeHash;
         Filesystem::writeFile($file, $pipeline->dump($this->publisher));
         $response->setEntity(new FileEntity(new \SplFileInfo($file)));
     } else {
         $response->setEntity((string) $pipeline->dump($this->publisher));
     }
     return $response;
 }
Esempio n. 7
0
 public function interceptRequest(HttpRequest $request)
 {
     if ($this->secure && !$request->isSecure()) {
         $response = new HttpResponse(Http::REDIRECT_IDENTICAL);
         $response->setHeader('Location', $request->getUri()->setScheme('https'));
         return $response;
     }
     if (!$this->secure && $request->isSecure()) {
         $response = new HttpResponse(Http::REDIRECT_IDENTICAL);
         $response->setHeader('Location', $request->getUri()->setScheme('http'));
         return $response;
     }
 }
Esempio n. 8
0
 public function startAuthentication(TokenInterface $token, HttpRequest $request, HttpResponse $response)
 {
     if (!$token instanceof NtlmAuthToken) {
         throw new SecurityException(sprintf('Invalid token %s passed to %s', get_class($token), get_class($this)));
     }
     $response->setStatus(Http::CODE_UNAUTHORIZED);
     $response->setReason(Http::getReason(Http::CODE_UNAUTHORIZED));
     if ($token->isMessage1()) {
         $message = $token->getChallengeMessage($this->provider->createChallenge($this->context));
         $response->addHeader('WWW-Authenticate', sprintf('NTLM %s', base64_encode($message)));
     } else {
         $response->addHeader('WWW-Authenticate', 'NTLM');
     }
 }
Esempio n. 9
0
 /**
  * {@inheritdoc}
  */
 public function startAuthentication(TokenInterface $token, HttpRequest $request, HttpResponse $response)
 {
     if (!$token instanceof FormAuthToken) {
         throw new SecurityException(sprintf('Invalid token %s passed to %s', get_class($token), get_class($this)));
     }
     $loginUri = new Uri($this->auth->getLoginUri());
     $path = trim($request->getUri()->getPath(false), '/');
     $loginPath = trim($loginUri->getPath(false), '/');
     $session = $this->securityContext->getSession();
     $data = (array) $session->get($this->auth->getKey(), NULL);
     // Save the current URI when it is not the login URI.
     if ($path !== $loginPath && !array_key_exists(FormAuthenticationProvider::SESSION_URI, $data)) {
         $data[FormAuthenticationProvider::SESSION_URI] = (string) $request->getUri();
     }
     $session->set($this->auth->getKey(), $data);
     $response->setStatus(Http::REDIRECT_TEMPORARY);
     $response->setReason(Http::getReason(Http::REDIRECT_TEMPORARY));
     $response->setHeader('Location', $loginUri);
 }
Esempio n. 10
0
 public function handle($path, Uri $baseUri, HttpRequest $request, StorageInterface $storage)
 {
     if (!$request->isPut()) {
         return;
     }
     if ($request->hasHeader('Content-Range')) {
         throw new BadRequestException();
     }
     $stream = $request->hasEntity() ? $request->getEntity()->getInputStream() : new StringStream();
     $created = false;
     $storage->beginTransaction();
     try {
         try {
             $resource = $storage->findResource($path);
             if ($resource->isCollection()) {
                 throw new MethodNotAllowedException();
             }
             $resource = $storage->updateResource($resource, $stream);
         } catch (\OutOfBoundsException $e) {
             $parts = explode('/', $path);
             $name = array_pop($parts);
             try {
                 $parent = $storage->findResource(implode('/', $parts));
             } catch (\OutOfBoundsException $ex) {
                 throw new WebDavException(WebDav::CODE_CONFLICT, $ex);
             }
             if (!$parent->isCollection()) {
                 throw new WebDavException(WebDav::CODE_CONFLICT);
             }
             $resource = $storage->createResource($parent, $name, $stream);
             $created = true;
         }
     } catch (\Exception $e) {
         $storage->rollBack();
         throw $e;
     }
     $storage->commit();
     $response = new HttpResponse(empty($created) ? WebDav::CODE_NO_CONTENT : WebDav::CODE_CREATED);
     $response->setHeader('ETag', $resource->getEtag());
     return $response;
 }
Esempio n. 11
0
 public function handle($path, Uri $baseUri, HttpRequest $request, StorageInterface $storage)
 {
     if (!$request->isGet() && !$request->isHead()) {
         return;
     }
     try {
         $resource = $storage->findResource($path);
     } catch (\OutOfBoundsException $e) {
         return new HttpResponse(WebDav::CODE_NOT_FOUND);
     }
     if ($resource->isCollection()) {
         return new HttpResponse(WebDav::CODE_NO_CONTENT);
     }
     $cacheControl = new CacheControlHeader();
     $cacheControl->setPrivate(true)->setMustRevalidate(true)->setMaxAge(7200);
     if ($request->isGet() && ($response = $request->evaluatePreconditions($resource->getEtag()))) {
         return $response->setHeader($cacheControl);
     }
     $response = new HttpResponse();
     $response->setHeader($cacheControl);
     $response->setHeader('Content-Type', $resource->getMediaType());
     $response->setHeader('ETag', $resource->getEtag());
     if ($request->isGet()) {
         $response->setEntity($resource->getInputStream());
     }
     return $response;
 }
Esempio n. 12
0
 public function handle($path, Uri $baseUri, HttpRequest $request, StorageInterface $storage)
 {
     if ($request->getMethod() != WebDav::METHOD_MOVE) {
         return;
     }
     $storage->beginTransaction();
     try {
         $resource = $storage->findResource($path);
         $destination = $this->getDestinationPath($baseUri, $request);
         $overwrite = strtoupper($request->getHeader('Overwrite', 'F')) == 'T';
         $replaced = false;
         $resource = $this->performMove($resource, $destination, $overwrite, $replaced, $storage);
     } catch (\Exception $e) {
         $storage->rollBack();
         throw $e;
     }
     $storage->commit();
     $response = new HttpResponse($replaced ? WebDav::CODE_NO_CONTENT : WebDav::CODE_CREATED);
     $response->setHeader('Location', rtrim($baseUri, '/') . '/' . Uri::encode(ltrim($resource->getPath(), '/')));
     if (!$resource->isCollection()) {
         $response->setHeader('ETag', $resource->getEtag());
     }
     return $response;
 }
 public function buildResponse()
 {
     $response = new HttpResponse(WebDav::CODE_MULTI_STATUS, WebDav::getReason(WebDav::CODE_MULTI_STATUS));
     $response->setHeader('Content-Type', 'application/xml; charset="utf-8"');
     $response->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate');
     if ($this->propfind instanceof PropfindRequest) {
         $response->setEntity([$this, 'streamProperties']);
     } elseif ($this->propfind instanceof PropNameRequest) {
         $response->setEntity([$this, 'streamPropertyNames']);
     } else {
         throw new \RuntimeException('Unable to generate response for ' . get_class($this->propfind));
     }
     return $response;
 }
Esempio n. 14
0
 public function invokeHandlers($pathInfo, Uri $baseUri, HttpRequest $request)
 {
     if ($request->isOptions()) {
         $response = new HttpResponse(Http::CODE_NO_CONTENT);
         $response->setHeader('MS-Author-Via', 'DAV');
         try {
             $event = new PopulateOptionsEvent($this->storage->findResource($pathInfo));
         } catch (\OutOfBoundsException $e) {
             return new HttpResponse(WebDav::CODE_NOT_FOUND);
         }
         $this->dispatcher->notify($event);
         $response->setHeader('DAV', implode(', ', $event->features));
         $response->setHeader('Allow', implode(', ', $event->allow));
         $response->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0');
         return $response;
     }
     foreach ($this->handlers as $handler) {
         try {
             $response = $handler->handle($pathInfo, $baseUri, $request, $this->storage);
         } catch (MethodNotAllowedException $e) {
             break;
         } catch (\OutOfBoundsException $e) {
             return new HttpResponse(WebDav::CODE_NOT_FOUND);
         }
         if ($response !== NULL) {
             if (!$response->hasHeader('Cache-Control')) {
                 $response->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0');
             }
             return $response;
         }
     }
     try {
         $resource = $this->storage->findResource($pathInfo);
     } catch (\OutOfBoundsException $e) {
         return new HttpResponse(WebDav::CODE_NOT_FOUND);
     }
     $event = new PopulateOptionsEvent($resource);
     $this->dispatcher->notify($event);
     $response = new HttpResponse(Http::CODE_METHOD_NOT_ALLOWED);
     $response->setHeader('MS-Author-Via', 'DAV');
     $response->setHeader('DAV', implode(', ', $event->features));
     $response->setHeader('Allow', implode(', ', $event->allow));
     $response->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0');
     return $response;
 }
Esempio n. 15
0
 /**
  * @Route("POST /definitions/message/{message}")
  */
 public function startProcessByMessage($message, JsonEntity $input)
 {
     $input = $input->toArray();
     $businessKey = array_key_exists('businessKey', $input) ? (string) $input['businessKey'] : NULL;
     $vars = array_key_exists('variables', $input) ? $input['variables'] : [];
     $process = $this->runtimeService->startProcessInstanceByMessage($message, $businessKey, $vars);
     $response = new HttpResponse(Http::CODE_CREATED);
     $response->setEntity(new JsonEntity(['process' => $process, '_embedded' => ['variables' => $process->getVariables()]]));
     return $response;
 }
Esempio n. 16
0
 protected function createNotFoundResponse(HttpRequest $request)
 {
     $response = new HttpResponse(Http::CODE_NOT_FOUND);
     $response->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0');
     return $response;
 }
Esempio n. 17
0
 public function transform($result, RoutingContextInterface $context)
 {
     if ($result === NULL) {
         return new HttpResponse();
     }
     if ($result instanceof HttpResponse) {
         return $result;
     }
     foreach ($this->plugins->getResponseGenerators() as $generator) {
         $response = $generator->generateResponse($result, $context);
         if ($response instanceof HttpResponse) {
             return $response;
         }
     }
     if (is_string($result)) {
         $response = new HttpResponse();
         $response->setEntity($result);
         return $response;
     }
     if ($result instanceof EntityInterface) {
         $response = new HttpResponse();
         $response->setEntity($result);
         return $response;
     }
     if (is_object($result) && is_callable($result)) {
         $response = new HttpResponse();
         $response->setEntity($result);
         return $response;
     }
     if (is_object($result)) {
         throw new \RuntimeException(sprintf('Unable to convert object of type %s into an HTTP response', get_class($result)));
     }
     throw new \RuntimeException(sprintf('Unable to convert result of type "%s" into an HTTP response', gettype($result)));
 }
Esempio n. 18
0
 protected function createLockResponse($status, LockInfoInterface $lock, Uri $baseUri, $lockHeader = true)
 {
     $response = new HttpResponse($status);
     $response->setHeader('Content-Type', 'application/xml; charset="utf-8"');
     if ($lockHeader) {
         $response->setHeader('Lock-Token', sprintf('<urn:webdav:lock:%s>', $lock->getToken()));
     }
     $response->setEntity(function (StreamInterface $stream) use($lock, $baseUri) {
         $xml = new XmlStreamWriter(new StreamWrapper($stream));
         $xml->registerNamespace(WebDav::NS_DAV, 'D');
         $xml->startDocument();
         $xml->startElement(WebDav::NS_DAV, 'prop');
         $xml->startElement(WebDav::NS_DAV, 'lockdiscovery');
         $lock->toXml($xml, $baseUri);
         $xml->endElement();
         // D:lockdiscovery
         $xml->endElement();
         // D:prop
         $xml->endDocument();
         $xml->flush();
     });
     return $response;
 }
 public function process(DispatchRequest $dispatchRequest)
 {
     $request = $dispatchRequest->getHttpRequest();
     if ($request->getPathInfo() !== '') {
         return $dispatchRequest->proceed();
     }
     if ($request->isOptions()) {
         $response = new HttpResponse(WebDav::CODE_NO_CONTENT);
         $response->setHeader('MS-Author-Via', 'DAV');
         $response->setHeader('DAV', '1, 2, 3');
         $response->setHeader('Allow', 'OPTIONS, PROPFIND');
         $response->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0');
         return $response;
     }
     if ($request->getMethod() == WebDav::METHOD_PROPFIND) {
         $depth = strtolower($request->getHeader('Depth', 'infinity'));
         switch ($depth) {
             case '0':
             case '1':
                 // OK
                 break;
             default:
                 $response = new HttpResponse(WebDav::CODE_FORBIDDEN);
                 $response->setHeader('Content-Type', 'application/xml; charset="utf-8"');
                 $response->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0');
                 $response->setEntity(function (StreamInterface $stream) {
                     $xml = new XmlStreamWriter($stream);
                     $xml->registerNamespace(WebDav::NS_DAV, 'D');
                     $xml->startDocument();
                     $xml->startElement(WebDav::NS_DAV, 'error');
                     $xml->writeElement(WebDav::NS_DAV, 'propfind-finite-depth');
                     $xml->endElement();
                     // D:error
                     $xml->endDocument();
                     $xml->flush();
                 });
                 return $response;
         }
         $response = new HttpResponse(WebDav::CODE_MULTI_STATUS);
         $response->setHeader('Content-Type', 'application/xml; charset="utf-8"');
         $response->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0');
         $response->setEntity(function (StreamInterface $stream) use($request, $depth) {
             $href = rtrim($request->getBaseUri(), '/') . '/';
             $xml = new XmlStreamWriter($stream);
             $xml->registerNamespace(WebDav::NS_DAV, 'D');
             $xml->registerNamespace(WebDav::NS_MS, 'ms');
             $xml->startDocument();
             $xml->startElement(WebDav::NS_DAV, 'multistatus');
             $xml->startElement(WebDav::NS_DAV, 'response');
             $xml->writeElement(WebDav::NS_DAV, 'href', $href);
             $xml->startElement(WebDav::NS_DAV, 'propstat');
             $xml->startElement(WebDav::NS_DAV, 'prop');
             $xml->writeElement(WebDav::NS_DAV, 'isroot', 1);
             $xml->writeElement(WebDav::NS_DAV, 'iscollection', 1);
             $xml->startElement(WebDav::NS_DAV, 'resourcetype');
             $xml->writeElement(WebDav::NS_DAV, 'collection');
             $xml->endElement();
             // D:resourcetype
             $xml->writeElement(WebDav::NS_DAV, 'getcontenttype', 'httpd/unix-directory');
             $xml->writeElement(WebDav::NS_DAV, 'getcontentlength', 0);
             $xml->writeElement(WebDav::NS_DAV, 'creationdate', gmdate(WebDav::DATE_FORMAT_TZ, 1337));
             $xml->startElement(WebDav::NS_DAV, 'getlastmodified');
             $xml->writeAttribute(WebDav::NS_MS, 'dt', 'dateTime.rfc1123');
             $xml->writeText(gmdate(WebDav::DATE_FORMAT_RFC1123, filemtime(__FILE__)));
             $xml->endElement();
             // D:getlastmodified
             $xml->writeElement(WebDav::NS_DAV, 'lockdiscovery');
             $xml->writeElement(WebDav::NS_DAV, 'supportedlock');
             $xml->writeElement(WebDav::NS_DAV, 'supported-report-set');
             $xml->endElement();
             // D:prop
             $xml->writeElement(WebDav::NS_DAV, 'status', 'HTTP/1.1 200 OK');
             $xml->endElement();
             // D:propstat
             $xml->endElement();
             // D:response
             if ($depth == '1') {
                 $xml->startElement(WebDav::NS_DAV, 'response');
                 $xml->writeElement(WebDav::NS_DAV, 'href', $href . 'dav/');
                 $xml->startElement(WebDav::NS_DAV, 'propstat');
                 $xml->startElement(WebDav::NS_DAV, 'prop');
                 $xml->writeElement(WebDav::NS_DAV, 'iscollection', 1);
                 $xml->startElement(WebDav::NS_DAV, 'resourcetype');
                 $xml->writeElement(WebDav::NS_DAV, 'collection');
                 $xml->endElement();
                 // D:resourcetype
                 $xml->writeElement(WebDav::NS_DAV, 'getcontenttype', 'httpd/unix-directory');
                 $xml->writeElement(WebDav::NS_DAV, 'getcontentlength', 0);
                 $xml->writeElement(WebDav::NS_DAV, 'creationdate', gmdate(WebDav::DATE_FORMAT_TZ, 1337));
                 $xml->startElement(WebDav::NS_DAV, 'getlastmodified');
                 $xml->writeAttribute(WebDav::NS_MS, 'dt', 'dateTime.rfc1123');
                 $xml->writeText(gmdate(WebDav::DATE_FORMAT_RFC1123, filemtime(__FILE__)));
                 $xml->endElement();
                 // D:getlastmodified
                 $xml->writeElement(WebDav::NS_DAV, 'lockdiscovery');
                 $xml->writeElement(WebDav::NS_DAV, 'supportedlock');
                 $xml->writeElement(WebDav::NS_DAV, 'supported-report-set');
                 $xml->endElement();
                 // D:prop
                 $xml->writeElement(WebDav::NS_DAV, 'status', 'HTTP/1.1 200 OK');
                 $xml->endElement();
                 // D:propstat
                 $xml->endElement();
                 // D:response
             }
             $xml->endElement();
             // D:multistatus
             $xml->endDocument();
             $xml->flush();
         });
         return $response;
     }
     return $dispatchRequest->proceed();
 }
Esempio n. 20
0
 /**
  * Evaluate preconditions found in this request based on the given values and create an appropriate
  * HTTP response if an HTTP/1.1 304 Not Modified response should be sent.
  * 
  * You can pass an ETag, a modification time or bot of these to the method, every precondition
  * that is not NULL will be checked.
  * 
  * @param EntityTag $etag The ETag of the requested resource.
  * @param \DateTimeInterface $lastModified Date of the last modification of the requested resource.
  * @return HttpResponse An HTTP 304 response or NULL if the client cache is invalid.
  */
 public function evaluatePreconditions(EntityTag $etag = NULL, \DateTimeInterface $lastModified = NULL)
 {
     $response = new HttpResponse();
     if ($etag !== NULL) {
         if ($this->hasHeader('If-None-Match')) {
             $valid = $this->firstHeader(function (IfNoneMatchHeader $match) use($etag) {
                 return $match->isWildcard() || $match->getEntityTag() == $etag;
             });
             if ($valid) {
                 $response->setStatus(Http::CODE_NOT_MODIFIED);
                 $response->setReason(Http::getReason(Http::CODE_NOT_MODIFIED));
                 $response->setHeader(new ETagHeader($etag));
             }
         }
     }
     if ($lastModified !== NULL) {
         $unmodified = false;
         if ($this->hasHeader('If-Modified-Since')) {
             $unmodified = $this->firstHeader(function (IfModifiedSinceHeader $since) use($lastModified) {
                 return $since->getDate() >= $lastModified;
             });
         }
         if ($unmodified) {
             $response->setStatus(Http::CODE_NOT_MODIFIED);
             $response->setReason(Http::getReason(Http::CODE_NOT_MODIFIED));
             $response->setHeader(new LastModifiedHeader($lastModified));
         }
     }
     return $response->isRedirect() ? $response : NULL;
 }
 public function process(DispatchRequest $dispatch)
 {
     if (!$dispatch->isMaster()) {
         return $dispatch->proceed();
     }
     $request = $dispatch->getHttpRequest();
     $path = $request->getPathInfo();
     $m = NULL;
     if (!preg_match("'^_res/+(.+)\$'i", $path, $m)) {
         return $dispatch->proceed();
     }
     $path = $m[1];
     if ('app/' === substr($path, 0, 4)) {
         $resource = 'k2://app/' . substr($path, 4);
     } else {
         $parts = explode('/', $path, 2);
         if (count($parts) !== 2) {
             return new HttpResponse(Http::CODE_NOT_FOUND);
         }
         $resource = 'k2://' . $parts[0] . '/' . $parts[1];
     }
     if (!is_file($resource)) {
         return new HttpResponse(Http::CODE_NOT_FOUND);
     }
     if (!$this->publisher->isPublic($resource)) {
         return new HttpResponse(Http::CODE_FORBIDDEN);
     }
     $response = new HttpResponse();
     // Conditional caching:
     $etag = sprintf('"%x-%x"', filemtime($resource), filesize($resource));
     $response->setHeader('Access-Control-Allow-Origin', '*');
     $response->setHeader('Cache-Control', 'public, max-age=7200');
     $response->setHeader('ETag', $etag);
     $response->setHeader(new ExpiresHeader(new \DateTimeImmutable('@' . (time() + 7200))));
     if ($etag === $request->getHeader('If-None-Match', '')) {
         $response->setStatus(Http::CODE_NOT_MODIFIED);
         return $response;
     }
     $mediaType = new MediaType(Filesystem::guessMimeTypeFromFilename($resource));
     $response->setHeader('X-Content-Type-Options', 'nosniff');
     if ($mediaType->isType('text')) {
         $response->setHeader('Content-Type', $mediaType . '; charset="utf-8"');
     } else {
         $response->setHeader('Content-Type', (string) $mediaType);
     }
     $response->setEntity(new FileEntity(new \SplFileInfo($resource)));
     return $response;
 }
Esempio n. 22
0
 public function toResponse()
 {
     $response = new HttpResponse($this->getCode(), $this->getMessage());
     $response->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate, proxy-revalidate, max-age=0');
     return $response;
 }
 /**
  * {@inheritdoc}
  */
 public function authenticate(SecurityContextInterface $context, TokenInterface $token, HttpRequest $request)
 {
     if (!$token instanceof FormAuthToken) {
         throw new SecurityException(sprintf('Token %s not supported by provider %s', get_class($token), get_class($this)));
     }
     $this->failedLogin = false;
     $this->username = $token->getUsername();
     $this->guard = bin2hex(random_bytes($this->guardByteCount));
     $path = trim($request->getUri()->getPath(false), '/');
     $loginPath = trim((new Uri($this->getLoginUri()))->getPath(false), '/');
     $logoutPath = trim((new Uri($this->getLogoutUri()))->getPath(false), '/');
     $isLogin = $path === $loginPath;
     $isLogout = $path === $logoutPath;
     $session = $context->getSession();
     if ($isLogout) {
         $session->remove($this->getKey());
         $token->setPrincipal(new AnonymousPrincipal());
         $token->setStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
         return;
     }
     if ($isLogin) {
         try {
             if ($request->isPost(false)) {
                 $identity = $token->getUsername();
                 $password = $token->getPassword();
                 // Fetch user independent of guard in order to prevent leakage of timing information.
                 $principal = $this->getPrincipalProvider()->findPrincipalUsingPassword($identity, $password);
                 // Invalidate when guard fails.
                 if (!$token->isGuarded()) {
                     $principal = NULL;
                 }
                 if ($principal !== NULL) {
                     $session = $context->getSession();
                     $data = (array) $session->get($this->getKey(), NULL);
                     $data[self::SESSION_IDENTITY] = (string) $principal->getIdentity();
                     $session->set($this->getKey(), $data);
                     if (array_key_exists(self::SESSION_URI, $data)) {
                         $uri = $data[self::SESSION_URI];
                         unset($data[self::SESSION_URI]);
                         $session->set($this->getKey(), $data);
                         $response = new HttpResponse(Http::REDIRECT_TEMPORARY);
                         $response->setHeader('Location', $uri);
                         return $response;
                     }
                     $token->setPrincipal($principal);
                     $token->setStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
                     return;
                 }
                 $this->failedLogin = true;
             }
             $token->setPrincipal(new AnonymousPrincipal());
             $token->setStatus(TokenInterface::AUTHENTICATION_SUCCESSFUL);
             return;
         } finally {
             $data = (array) $session->get($this->getKey(), []);
             $data[self::SESSION_GUARD] = $this->guard;
             $session->set($this->getKey(), $data);
         }
     }
 }
 public function render(ViewModelInterface $model, $onlyEntity = false)
 {
     $m = NULL;
     if (!preg_match("'.+\\.([a-z0-9]+)\\.xml\$'i", $model->getResource(), $m)) {
         throw new \RuntimeException(sprintf('Unable to determine output format of view "%s"', $model->getResource()));
     }
     $typeName = $this->factory->createView($this, $model->getResource());
     $view = new $typeName($this->factory, $this);
     $response = new HttpResponse();
     $format = strtolower($m[1]);
     $out = $view->render(new OutputBuffer(), $model, ['@format' => $format, '@response' => $response]);
     if ($onlyEntity) {
         return (string) $out;
     }
     if (!$response->hasHeader('Content-Type')) {
         $type = new MediaType(Filesystem::guessMimeTypeFromFilename($format));
         if ($type->isText()) {
             $response->setHeader('Content-Type', $type . '; charset="utf-8"');
         } else {
             $response->setHeader('Content-Type', $type);
         }
         if ($type->is('*/xml')) {
             $out = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $out;
         }
     }
     return $response->setEntity(ltrim($out));
 }
Esempio n. 25
0
 public function filterRequest(FilterRequestEvent $event)
 {
     $router = $this->router;
     $match = NULL;
     $prev = NULL;
     while (true) {
         try {
             $match = $router->route($this->context->getRequest()->getMethod(), '/' . ltrim($this->context->getPathInfo(), '/'));
         } catch (NoRouteMatchedException $e) {
             return NULL;
         } catch (UnsupportedMethodException $e) {
             $response = new HttpResponse(Http::CODE_METHOD_NOT_ALLOWED);
             $response->setHeader('Allow', implode(', ', $e->getAllowedMethods()));
             return $response;
         }
         if ($match instanceof RouteMatch) {
             if ($prev !== NULL) {
                 $tmp = $match;
                 $match = $prev->append($match, $prev->getHandler()->getPathPrefix());
                 $prev = $tmp;
             } else {
                 $prev = $match;
             }
             $this->context->setRouteMatch($match);
             $handler = $match->getHandler();
             if ($handler instanceof DispatchableMountHandler) {
                 // Change mount to method handler.
                 $match = new RouteMatch($match->getRouteName(), $handler->getPathPrefix(), $match->getPathRemainder(), $match->getParameters(), new MethodHandler($handler->getTypeName(), $handler->getMethodName()));
                 $this->context->setRouteMatch($match);
                 break;
             } elseif ($handler instanceof MountHandler) {
                 if (NULL !== ($router = $handler->getRouter())) {
                     continue;
                 }
                 $router = $this->eventDispatcher->publishUntil(new LoadMountedRouterEvent($handler), function ($result) {
                     return $result instanceof Router;
                 });
                 if ($router !== NULL) {
                     $handler->setRouter($router);
                     continue;
                 }
                 throw new \RuntimeException(sprintf('Unable to load router of mounted handler %s', get_class($handler)));
             }
         }
         break;
     }
     if ($match instanceof RouteMatch) {
         $result = $this->eventDispatcher->publishUntil(new DispatchRequestEvent($match, $this->context));
         if ($result === NULL) {
             return new HttpResponse(Http::CODE_NO_CONTENT);
         }
         if ($result instanceof HttpResponse) {
             return $result;
         }
         $response = $this->eventDispatcher->publishUntil(new GenerateResponseEvent($result, $this->context), function ($result) {
             return $result instanceof HttpResponse;
         });
         if ($response instanceof HttpResponse) {
             return $response;
         }
         throw new \RuntimeException(sprintf('%s cannot be transformed into an HTTP response', is_object($result) ? get_class($result) : gettype($result)));
     }
 }
Esempio n. 26
0
 public function __construct(HttpResponse $response, \Exception $cause = NULL)
 {
     parent::__construct($response->getStatus(), $cause);
     $this->response = $response;
 }