You are here

function farm_access_add_cors_headers in farmOS 7

Add CORS headers.

1 call to farm_access_add_cors_headers()
farm_access_init in modules/farm/farm_access/farm_access.module
Implements hook_init().

File

modules/farm/farm_access/farm_access.module, line 22
Farm Access module.

Code

function farm_access_add_cors_headers() {

  // Load the list of allowed origins.
  $allowed_origins = explode("\n", variable_get('farm_access_allow_origin', FARM_ACCESS_DEFAULT_ALLOWED_ORIGINS));

  // Trim whitespace from each item.
  foreach ($allowed_origins as &$value) {
    $value = trim($value);
  }

  // Add "app://localhost" to the list of allowed origins, so that requests from
  // Field Kit on iOS native (WKWebView) are accepted.
  $allowed_origins[] = 'app://localhost';

  // Get the request headers.
  $headers = getallheaders();

  // If the "Origin" header is set, check to see if it is in the allowed list.
  if (!empty($headers['Origin'])) {
    if (in_array($headers['Origin'], $allowed_origins)) {

      // Add headers to allow CORS requests.
      drupal_add_http_header('Access-Control-Allow-Origin', $headers['Origin']);
      drupal_add_http_header('Access-Control-Allow-Credentials', 'true');
      drupal_add_http_header('Access-Control-Allow-Headers', 'Content-Type,Authorization,X-CSRF-Token');
      drupal_add_http_header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,HEAD,OPTIONS');

      // Add a "Vary: Origin" header to indicate to clients that server
      // responses will differ based on the value of the "Origin" request
      // header.
      // See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
      drupal_add_http_header('Vary', 'Origin');
    }
  }
}