Give back CORS preflight check headers
170821
def OPTIONS_preflight( self, path_info ):
        
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')    # CORS
        self.send_header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE')
        self.send_header('Access-Control-Allow-Headers', 'content-type, authorization, range')
        self.send_header('Access-Control-Expose-Headers', 'content-length, content-range')
        self.send_header('Access-Control-Max-Age', 21600)
        self.end_headers()
        return
163114
def get_headers(server):
    """"""
    try:
        response = requests.head(
            server, allow_redirects=False, verify=False, timeout=5)
    except requests.exceptions.ConnectionError:
        return False

    return dict(response.headers)
40955
def _check_cors_origin(origin, allowed_origins):
    '''
    
    '''
    if isinstance(allowed_origins, list):
        if origin in allowed_origins:
            return origin
    elif allowed_origins == '*':
        return allowed_origins
    elif allowed_origins == origin:
        # Cors origin is either * or specific origin
        return allowed_origins
1263804
function cors(options, successCallback, errorCallback) {

    options = options || {};

    // The browser sets the Content-type header for FormData requests
    // automatically, so we need to remove it.
    if(options.formData && options.headers){
      delete options.headers['content-type'];
    }

    var method = options.method || 'get',
      url = Utils.buildUrl(options),
      xhr = _createXhr(method, url, options),
      sendable;

    // Create form data or send simple request.
    if(options.formData){
      sendable = new FormData();
      for(var key in options.formData){
        sendable.append(key, options.formData[key]);
      }

    } else {
      // Serialise JSON data before sending.
      sendable = options.data ? JSON.stringify(options.data) : null;
    }


    // Do a normal asynchronous request and return a promise. If there
    // are callbacks execute them as well before resolving the promise.
    return new Promise(function (resolve, reject) {

      // Define internal error handler.
      function errorHandler(response) {
        if (response) {
          var errorData = _buildError(xhr, url, method, response);
          Logger.error(errorData);

          if (errorCallback) {
            Logger.warnCallbackDeprecation();
            errorCallback(errorData);
          }
          reject(errorData);
        }
      }

      // Define the response handler.
      function handler() {
        try {
          if (this.readyState === this.DONE) {

            var response = _buildResponse(this, options.fullResponse);

            // Resolve or reject promise given the response status.
            // HTTP status of 2xx is considered a success.
            if (this.status >= 200 && this.status < 300) {

              if (successCallback) {
                Logger.warnCallbackDeprecation();
                successCallback(response);
              }
              resolve(response);

            } else {
              errorHandler(response);
            }
          }
        } catch (exception) {
          // Do nothing, will be handled by ontimeout.
        }
      }

      // Set timeout handler if needed.
      if (options.timeout > 0) {
        xhr.ontimeout = function () {
          var timeoutErrResponse = {errors: ['Request timed out.']};
          errorHandler(timeoutErrResponse);
        };
      }

      // Could not execute request at all (destination unreachable, offline, ...?)
      xhr.onerror = function () {
        var networkErrResponse = {errors: ['Network error.']};
        errorHandler(networkErrResponse);
      };

      // Send the request and wait for the response in the handler.
      xhr.onreadystatechange = handler;

      xhr.send(sendable);
    });
  }
250093
protected function handleCorsPreflightRequest()
    {
        // Automatic CORS preflight response
        $existing_verbs = array();
        foreach (HttpMethods::getAllMethods() as $http_verb) {
            if (isset($this->map[$http_verb])) {
                $urls = $this->map[$http_verb];

                foreach (array_keys($urls) as $url) {
                    if (strstr($url, '$')) {
                        $matches = $this->matchRequestUriWithMap($this->getPath(), $url);

                        if (count($matches) > 0) {
                            $existing_verbs[] = $http_verb;
                            break;
                        }
                    } elseif (isset($this->map[$http_verb][$this->getPath()])) {
                        $existing_verbs[] = $http_verb;
                        break;
                    }
                }
            }
        }
        // OPTIONS is always part of the allowed methods
        $existing_verbs[] = HttpMethods::OPTIONS;

        // RFC5789: PATCH verb OPTIONS response
        // RFC4180: "Spaces are considered part of a field and should not be ignored."
        $comma_devider = ',';
        $this->header_manager->addHeader('Allow', join($comma_devider, $existing_verbs));

        // CORS Headers
        // Access-Control-Allow-Origin will be handled in ::handle()
        $this->header_manager->addHeader('Access-Control-Allow-Methods', join($comma_devider, $existing_verbs));
        $this->header_manager->addHeader('Access-Control-Max-Age', intval($this->cors_max_age));
        if (count($this->cors_allowed_headers) > 0) {
            $this->header_manager->addHeader('Access-Control-Allow-Headers',
                join($comma_devider, $this->cors_allowed_headers));
        }

        $this->sendData('');
    }
1167983
private function headers()
    {
        $headers = '';
        foreach (config('cors.headers') as $header) {
            $headers = $headers . $header . ', ';
        }
        header('Access-Control-Allow-Headers: ' . $headers);
    }
546248
def allow_cors(func):
    """"""
    def wrapper(*args, **kwargs):
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = \
            'PUT, GET, POST, DELETE, OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = \
            'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
        return func(*args, **kwargs)
    return wrapper
495918
public static function checkCORS()
    {
        Logger::log('Checking CORS');
        $corsEnabled = Config::getParam('cors.enabled');
        $request = Request::getInstance();
        if (NULL !== $corsEnabled) {
            if ($corsEnabled === '*' || preg_match($corsEnabled, $request->getServer('HTTP_REFERER'))) {
                if (!headers_sent()) {
                    // TODO include this headers in Template class output method
                    header('Access-Control-Allow-Credentials: true');
                    header('Access-Control-Allow-Origin: ' . Request::getInstance()->getServer('HTTP_ORIGIN', '*'));
                    header('Vary: Origin');
                    header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH, OPTIONS');
                    header('Access-Control-Allow-Headers: ' . implode(', ', self::getCorsHeaders()));
                }
                if (Request::getInstance()->getMethod() === Request::VERB_OPTIONS) {
                    Logger::log('Returning OPTIONS header confirmation for CORS pre flight requests', LOG_DEBUG);
                    header('HTTP/1.1 200 OK');
                    exit();
                }
            }
        }
    }
570912
public static function enableCORS($origin='*'){

        // Allow from any origin
        if ($origin = $origin ?:( isset($_SERVER['HTTP_ORIGIN'])
                    ? $_SERVER['HTTP_ORIGIN']
                    : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '*')
        )) {
          static::header('Access-Control-Allow-Origin',      $origin);
          static::header('Access-Control-Allow-Credentials', 'true');
          static::header('Access-Control-Max-Age',           86400);
        }

        // Access-Control headers are received during OPTIONS requests
        if (filter_input(INPUT_SERVER,'REQUEST_METHOD') == 'OPTIONS') {
            static::clean();

            if (filter_input(INPUT_SERVER,'HTTP_ACCESS_CONTROL_REQUEST_METHOD')) {
              static::header('Access-Control-Allow-Methods',
                'GET, POST, PUT, DELETE, OPTIONS, HEAD, CONNECT, PATCH, TRACE');
            }
            if ($req_h = filter_input(INPUT_SERVER,'HTTP_ACCESS_CONTROL_REQUEST_HEADERS')) {
              static::header('Access-Control-Allow-Headers',$req_h);
            }

            self::trigger('cors.preflight');
            static::send();
            exit;
        }
    }
451173
def cors_allow_any(request, response):
    
    origin = request.META.get('HTTP_ORIGIN')
    if not origin:
        return response

    # From the CORS spec: The string "*" cannot be used for a resource that supports credentials.
    response['Access-Control-Allow-Origin'] = origin
    patch_vary_headers(response, ['Origin'])
    response['Access-Control-Allow-Credentials'] = 'true'

    if request.method == 'OPTIONS':
        if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in request.META:
            response['Access-Control-Allow-Headers'] \
                = request.META['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']
        response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'

    return response
135736
def check_origin(self, origin):
        

        mod_opts = self.application.mod_opts

        if mod_opts.get('cors_origin'):
            return bool(_check_cors_origin(origin, mod_opts['cors_origin']))
        else:
            return super(AllEventsHandler, self).check_origin(origin)
1054687
def is_cors_enabled_on_request(self, request: web.Request) -> bool:
        """"""

        return self._request_resource(request) in self._resource_config
835554
def _default_headers(self):
        """"""
        headers = {
            "Authorization": 'Bearer {}'.format(self.api_key),
            "User-agent": self.useragent,
            "Accept": 'application/json'
        }
        if self.impersonate_subuser:
            headers['On-Behalf-Of'] = self.impersonate_subuser

        return headers
1036027
def csrf_protect_all_post_and_cross_origin_requests():
    """"""
    success = None

    if is_cross_origin(request):
        logger.warning("Received cross origin request. Aborting")
        abort(403)
    if request.method in ["POST", "PUT"]:
        token = session.get("csrf_token")
        if token == request.form.get("csrf_token"):
            return success

        elif token == request.environ.get("HTTP_X_CSRFTOKEN"):
            return success

        else:
            logger.warning("Received invalid csrf token. Aborting")
            abort(403)
938868
def cors_headers
      rack = Jets::Controller::Middleware::Cors.new(Jets.application)
      rack.cors_headers(true)
    end
876487
def _send_headers(self, status_code=200, content_type='application/json', more_headers={}):
        
        self.send_response(status_code)
        self.send_header('content-type', content_type)
        self.send_header('Access-Control-Allow-Origin', '*')    # CORS
        for (hdr, val) in more_headers.items():
            self.send_header(hdr, val)

        self.end_headers()
529410
function(req) {
	return ((req.headers.origin && req.headers.origin !== "null") ? req.headers.origin : "*");
}