Fixed some cross-origin issues

This commit is contained in:
Alejandro Celaya 2016-07-05 19:08:34 +02:00
parent 431169eb8c
commit bd36c65a73
4 changed files with 15 additions and 9 deletions

View File

@ -17,7 +17,7 @@ return [
'name' => 'rest-authenticate',
'path' => '/rest/authenticate',
'middleware' => Rest\AuthenticateMiddleware::class,
'allowed_methods' => ['POST'],
'allowed_methods' => ['POST', 'OPTIONS'],
],
[
'name' => 'rest-create-shortcode',

View File

@ -37,15 +37,16 @@ class CrossDomainMiddleware implements MiddlewareInterface
/** @var Response $response */
$response = $out($request, $response);
if ($request->hasHeader('X-Requested-With')
&& strtolower($request->getHeaderLine('X-Requested-With')) === 'xmlhttprequest'
) {
if (strtolower($request->getMethod()) === 'options') {
$response = $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->withHeader('Access-Control-Max-Age', '1000')
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', '*');
->withHeader(
// Allow all requested headers
'Access-Control-Allow-Headers',
$request->getHeaderLine('Access-Control-Request-Headers')
);
}
return $response;
return $response->withHeader('Access-Control-Allow-Origin', '*');
}
}

View File

@ -56,6 +56,10 @@ class AuthenticateMiddleware implements MiddlewareInterface
*/
public function __invoke(Request $request, Response $response, callable $out = null)
{
if (strtolower($request->getMethod()) === 'options') {
return $response;
}
$authData = $request->getParsedBody();
if (! isset($authData['username'], $authData['password'])) {
return new JsonResponse([

View File

@ -74,14 +74,15 @@ class CreateShortcodeMiddleware implements MiddlewareInterface
$longUrl = $postData['longUrl'];
try {
$shortcode = $this->urlShortener->urlToShortCode(new Uri($longUrl));
$shortUrl = (new Uri())->withPath($shortcode)
$shortCode = $this->urlShortener->urlToShortCode(new Uri($longUrl));
$shortUrl = (new Uri())->withPath($shortCode)
->withScheme($this->domainConfig['schema'])
->withHost($this->domainConfig['hostname']);
return new JsonResponse([
'longUrl' => $longUrl,
'shortUrl' => $shortUrl->__toString(),
'shortCode' => $shortCode,
]);
} catch (InvalidUrlException $e) {
return new JsonResponse([