2014-07-03 18:26:09 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
class CORSHelper
|
|
|
|
{
|
2017-03-10 15:10:56 +01:00
|
|
|
public static function enableCrossOriginRequests(&$request, &$response)
|
2014-07-03 18:26:09 +02:00
|
|
|
{
|
2022-03-14 11:15:04 +01:00
|
|
|
// Chrome sends the Origin header for all requests, so we whitelist the webserver's hostname as well.
|
2014-07-03 18:26:09 +02:00
|
|
|
$origin = $request->getHeader('Origin');
|
2021-10-07 19:05:56 +02:00
|
|
|
$allowedOrigins = self::getAllowedOrigins($request);
|
2017-07-18 20:39:53 +02:00
|
|
|
|
2022-05-23 17:12:40 +02:00
|
|
|
if (!($origin == '' || preg_match('/https?:\/\/localhost/', $origin) === 1 || in_array($origin, $allowedOrigins))) {
|
2022-03-14 11:15:04 +01:00
|
|
|
// Don't allow CORS from other domains to prevent XSS.
|
2023-02-01 20:11:00 +01:00
|
|
|
Logging::error(
|
|
|
|
"request origin '{$origin}' is not in the configured 'allowed_cors_origins' '" . implode(', ', $allowedOrigins) . "'"
|
|
|
|
);
|
2021-10-11 16:10:47 +02:00
|
|
|
|
2014-07-03 18:26:09 +02:00
|
|
|
throw new Zend_Controller_Action_Exception('Forbidden', 403);
|
|
|
|
}
|
2022-03-14 11:15:04 +01:00
|
|
|
// Allow AJAX requests from configured websites. We use this to allow other pages to use LibreTimes API.
|
2017-03-10 15:10:56 +01:00
|
|
|
if ($origin) {
|
|
|
|
$response = $response->setHeader('Access-Control-Allow-Origin', $origin);
|
|
|
|
}
|
2014-07-03 18:26:09 +02:00
|
|
|
}
|
2014-11-21 01:33:11 +01:00
|
|
|
|
2017-07-18 20:39:53 +02:00
|
|
|
/**
|
2021-10-11 16:10:47 +02:00
|
|
|
* Get all allowed origins.
|
2017-07-18 20:39:53 +02:00
|
|
|
*
|
|
|
|
* @param Request $request request object
|
|
|
|
*/
|
|
|
|
public static function getAllowedOrigins($request)
|
2014-11-21 01:33:11 +01:00
|
|
|
{
|
2022-10-11 13:38:31 +02:00
|
|
|
return Config::get('general.allowed_cors_origins');
|
2014-11-21 01:33:11 +01:00
|
|
|
}
|
2014-09-05 01:11:09 +02:00
|
|
|
}
|