Skip to content

Instantly share code, notes, and snippets.

@ger86
Created November 29, 2018 15:36
Show Gist options
  • Save ger86/9ba471aa42e1a48b207cbb8bd2505fa1 to your computer and use it in GitHub Desktop.
Save ger86/9ba471aa42e1a48b207cbb8bd2505fa1 to your computer and use it in GitHub Desktop.
<?php
namespace App\Service;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
class AmpService {
/**
*
* AmpService constructor.
*
* @param Symfony\Component\HttpFoundation\RequestStack $requestStack
* @param array $allowedOrigins
* @param string $allowedSourceOrigin
*
*/
public function __construct(
RequestStack $requestStack,
array $allowedOrigins,
string $allowedSourceOrigin
) {
$this->requestStack = $requestStack;
$this->allowedOrigins = $allowedOrigins;
$this->allowedSourceOrigin = $allowedSourceOrigin;
}
/**
* Validates an AMP Request
* @return JsonResponse
*/
public function validateRequest() {
$request = $this->requestStack->getCurrentRequest();
$headers = $request->headers->all();
$origin = "";
$ampSourceOrigin = (isset($_GET['__amp_source_origin'])) ? $_GET['__amp_source_origin'] : '';
// if same origin
if (isset($headers['amp-same-origin']) && $headers['amp-same-origin']) {
$origin = $this->allowedSourceOrigin;
}
// If allowed CORS origin & allowed source origin
else if (in_array($headers['ORIGIN'], $this->allowedOrigins) &&
$ampSourceOrigin == $this->allowedSourceOrigin) {
$origin = $headers['ORIGIN'];
} else {
$response = new JsonResponse(['message' => 'Unauthorized Request']);
$response->setStatusCode(Response::HTTP_FORBIDDEN);
return $response;
}
$response = new JsonResponse(['ok' => true]);
$response->headers->set('Access-Control-Allow-Credentials', true);
$response->headers->set('Access-Control-Allow-Origin', $origin);
$response->headers->set('Access-Control-Expose-Headers','AMP-Access-Control-Allow-Source-Origin');
$response->headers->set('AMP-Access-Control-Allow-Source-Origin', $ampSourceOrigin);
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment