Build a CORS settings object.
187086
private function buildSettings(ServerRequestInterface $request, ResponseInterface $response): CorsSettings
    {
        $settings = new CorsSettings;

        $origin = array_fill_keys((array) $this->options["origin"], true);
        $settings->setRequestAllowedOrigins($origin);

        if (is_callable($this->options["methods"])) {
            $methods = (array) $this->options["methods"]($request, $response);
        } else {
            $methods = $this->options["methods"];
        }
        $methods = array_fill_keys($methods, true);
        $settings->setRequestAllowedMethods($methods);

        $headers = array_fill_keys($this->options["headers.allow"], true);
        $headers = array_change_key_case($headers, CASE_LOWER);
        $settings->setRequestAllowedHeaders($headers);

        $headers = array_fill_keys($this->options["headers.expose"], true);
        $settings->setResponseExposedHeaders($headers);

        $settings->setRequestCredentialsSupported($this->options["credentials"]);

        if (is_string($this->options["origin.server"])) {
            $settings->setServerOrigin($this->options["origin.server"]);
        }

        $settings->setPreFlightCacheMaxAge($this->options["cache"]);

        return $settings;
    }
1109329
def cors_configuration(self):
        
        endpoint = '/'.join((
            self.server_url, '_api', 'v2', 'user', 'config', 'cors'))
        resp = self.r_session.get(endpoint)
        resp.raise_for_status()

        return response_to_json_dict(resp)
1319494
def configure(self, endpoint=None, **kwargs):
        """"""
        if endpoint:
            kwargs['endpoint'] = endpoint
        keywords = self._keywords.copy()
        keywords.update(kwargs)
        if 'endpoint' in kwargs:
            # Then we need to correctly format the endpoint.
            endpoint = kwargs['endpoint']
            keywords['endpoint'] = self._configure_endpoint(endpoint)
        self.api_key = keywords['api_key'] or self._global_api_key()
        self.endpoint = keywords['endpoint']
        self.format = keywords['format'] or 'json'
        self.jurisdiction = keywords['jurisdiction']
        self.proxy = keywords['proxy']
        self.discovery_url = keywords['discovery'] or None

        # Use a custom requests session and set the correct SSL version if
        # specified.
        self.session = requests.Session()
        if 'ssl_version' in keywords:
            self.session.mount('https://', SSLAdapter(keywords['ssl_version']))
290879
private void setCorsResponseHeaders(ServiceRequestContext ctx, HttpRequest req,
                                        HttpHeaders headers) {
        final CorsPolicy policy = setCorsOrigin(ctx, req, headers);
        if (policy != null) {
            policy.setCorsAllowCredentials(headers);
            policy.setCorsAllowHeaders(headers);
            policy.setCorsExposeHeaders(headers);
        }
    }
723400
public CorsConfig build() {
        if (preflightHeaders.isEmpty() && !noPreflightHeaders) {
            preflightHeaders.put(HttpHeaderNames.DATE, DateValueGenerator.INSTANCE);
            preflightHeaders.put(HttpHeaderNames.CONTENT_LENGTH, new ConstantValueGenerator("0"));
        }
        return new CorsConfig(this);
    }
308198
private boolean applyCorsConfig(final HttpRequest req, final AbstractHttpQuery query) 
        throws BadRequestException {
    final String domain = req.headers().get("Origin");
    
    // catch CORS requests and add the header or refuse them if the domain
    // list has been configured
    if (query.method() == HttpMethod.OPTIONS || 
        (cors_domains != null && domain != null && !domain.isEmpty())) {          
      if (cors_domains == null || domain == null || domain.isEmpty()) {
        throw new BadRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED, 
            "Method not allowed", "The HTTP method [" + 
            query.method().getName() + "] is not permitted");
      }
      
      if (cors_domains.contains("*") || 
          cors_domains.contains(domain.toUpperCase())) {

        // when a domain has matched successfully, we need to add the header
        query.response().headers().add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN,
            domain);
        query.response().headers().add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS,
            "GET, POST, PUT, DELETE");
        query.response().headers().add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS,
            cors_headers);

        // if the method requested was for OPTIONS then we'll return an OK
        // here and no further processing is needed.
        if (query.method() == HttpMethod.OPTIONS) {
          query.sendStatusOnly(HttpResponseStatus.OK);
          return true;
        }
      } else {
        // You'd think that they would want the server to return a 403 if
        // the Origin wasn't in the CORS domain list, but they want a 200
        // without the allow origin header. We'll return an error in the
        // body though.
        throw new BadRequestException(HttpResponseStatus.OK, 
            "CORS domain not allowed", "The domain [" + domain + 
            "] is not permitted access");
      }
    }
    return false;
  }
310508
function clientRes(res) {
    if (!res || !res.statusCode) {
        return (res);
    }

    return ({
        statusCode: res.statusCode,
        headers: res.headers
    });
}
943905
function initWebServer(settings) {

    const server = {
        app:       null,
        server:    null,
        io:        null,
        settings:  settings
    };

    settings.port = parseInt(settings.port, 10) || 0;

    if (settings.port) {
        if (settings.secure) {
            if (!settings.certificates) return null;
        }
        if (settings.auth) {
            const session =          require('express-session');
            const AdapterStore =     require(utils.controllerDir + '/lib/session.js')(session, settings.ttl);
            // Authentication checked by server itself
            store = new AdapterStore({adapter: adapter});
            settings.secret           = secret;
            settings.store            = store;
            settings.ttl              = settings.ttl || 3600;
            settings.forceWebSockets  = settings.forceWebSockets || false;
        }

        adapter.getPort(settings.port, port => {
            if (parseInt(port, 10) !== settings.port && !adapter.config.findNextPort) {
                adapter.log.error('port ' + settings.port + ' already in use');
                process.exit(1);
            }
            settings.port = port;

            server.server = LE.createServer((req, res) => {
                res.writeHead(501);
                res.end('Not Implemented');
            }, settings, adapter.config.certificates, adapter.config.leConfig, adapter.log);

            server.server.listen(settings.port, (settings.bind && settings.bind !== '0.0.0.0') ? settings.bind : undefined);

            settings.crossDomain     = true;
            settings.ttl             = settings.ttl || 3600;
            settings.forceWebSockets = settings.forceWebSockets || false;

            server.io = new IOSocket(server.server, settings, adapter);
        });
    } else {
        adapter.log.error('port missing');
        process.exit(1);
    }

    return server;
}
308598
def enable_cors(self):
        '''
        '''
        def access_control_headers():
            bottle.response.headers['Access-Control-Allow-Origin'] = '*'
            bottle.response.headers['Access-Control-Allow-Methods'] = \
                'GET, POST, PUT, DELETE, OPTIONS'
            bottle.response.headers['Access-Control-Allow-Headers'] = \
                'Origin, X-Requested-With, Content-Type, Accept, Authorization'

        def options_response(res):
            if bottle.request.method == 'OPTIONS':
                new_res = bottle.HTTPResponse()
                new_res.headers['Access-Control-Allow-Origin'] = '*'
                new_res.headers['Access-Control-Allow-Methods'] = \
                    bottle.request.headers.get(
                        'Access-Control-Request-Method', '')
                new_res.headers['Access-Control-Allow-Headers'] = \
                    bottle.request.headers.get(
                        'Access-Control-Request-Headers', '')
                return new_res
            res.headers['Allow'] += ', OPTIONS'
            return bottle.request.app.default_error_handler(res)

        self.app.add_hook('after_request', access_control_headers)
        self.app.error_handler[int(405)] = options_response
        return self
491262
function start (settings) {

  settings = settings || {};

  // Populate security values with the corresponding files.
  if (settings.secure) {
    settings.passphrase = settings.passphrase || '1234';
    settings.key = settings.key || 'https.key';
    settings.cert = settings.cert || 'https.crt';
    settings.ca = settings.ca || [];
  }

  settings.port = settings.port || (settings.secure ? 443 : 80);

  return startServer(settings);
}
1371423
def create_and_setup_cors(self, restapi, resource, uri, depth, config):
        
        if config is True:
            config = {}
        method_name = "OPTIONS"
        method = troposphere.apigateway.Method(method_name + str(depth))
        method.RestApiId = troposphere.Ref(restapi)
        if type(resource) is troposphere.apigateway.Resource:
            method.ResourceId = troposphere.Ref(resource)
        else:
            method.ResourceId = resource
        method.HttpMethod = method_name.upper()
        method.AuthorizationType = "NONE"
        method_response = troposphere.apigateway.MethodResponse()
        method_response.ResponseModels = {
            "application/json": "Empty"
        }
        response_headers = {
            "Access-Control-Allow-Headers": "'%s'" % ",".join(config.get(
                "allowed_headers", ["Content-Type", "X-Amz-Date",
                                    "Authorization", "X-Api-Key",
                                    "X-Amz-Security-Token"])),
            "Access-Control-Allow-Methods": "'%s'" % ",".join(config.get(
                "allowed_methods", ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"])),
            "Access-Control-Allow-Origin": "'%s'" % config.get(
                "allowed_origin", "*")
        }
        method_response.ResponseParameters = {
            "method.response.header.%s" % key: True for key in response_headers
        }
        method_response.StatusCode = "200"
        method.MethodResponses = [
            method_response
        ]
        self.cf_template.add_resource(method)
        self.cf_api_resources.append(method.title)

        integration = troposphere.apigateway.Integration()
        integration.Type = 'MOCK'
        integration.PassthroughBehavior = 'NEVER'
        integration.RequestTemplates = {
            "application/json": "{\"statusCode\": 200}"
        }
        integration_response = troposphere.apigateway.IntegrationResponse()
        integration_response.ResponseParameters = {
            "method.response.header.%s" % key: value for key, value in response_headers.items()
        }
        integration_response.ResponseTemplates = {
            "application/json": ""
        }
        integration_response.StatusCode = "200"
        integration.IntegrationResponses = [
            integration_response
        ]

        integration.Uri = uri
        method.Integration = integration
533994
def set_default_headers(self):
        '''
        
        '''
        mod_opts = self.application.mod_opts

        if mod_opts.get('cors_origin'):
            origin = self.request.headers.get('Origin')

            allowed_origin = _check_cors_origin(origin, mod_opts['cors_origin'])

            if allowed_origin:
                self.set_header("Access-Control-Allow-Origin", allowed_origin)
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
1362272
def _configure_endpoint(self, endpoint):
        """"""
        if not endpoint.startswith('http'):
            endpoint = 'https://' + endpoint
        if not endpoint.endswith('/'):
            endpoint += '/'
        return endpoint
1242731
def _build_response(self, resp):
        """"""
        # rememberLogin
        # if self.method is 'LOGIN' and resp.json().get('code') == 200:
        #     cookiesJar.save_cookies(resp, NCloudBot.username)
        self.response.content = resp.content
        self.response.status_code = resp.status_code
        self.response.headers = resp.headers
615086
def cors_setup(self, request):
        
        def cors_headers(request, response):
            if request.method.lower() == 'options':
                response.headers.update({
                    '-'.join([p.capitalize() for p in k.split('_')]): v
                    for k, v in self.cors_options.items()
                })
            else:
                origin = self.cors_options.get('access_control_allow_origin', '*')
                expose_headers = self.cors_options.get('access_control_expose_headers', '')
                response.headers['Access-Control-Allow-Origin'] = origin
                if expose_headers:
                    response.headers['Access-Control-Expose-Headers'] = expose_headers

        # setup the CORS supported response
        request.add_response_callback(cors_headers)
802514
protected function configureCorsIfEnabled(): void
    {
        $reflection = new \ReflectionClass($this);
        $reader = new AnnotationReader();

        $annotation = $reader->getClassAnnotation($reflection, CORS::class);

        if (empty($annotation)) {
            return;
        }

        $corsConfig = [
            'Access-Control-Allow-Origin' => $annotation->origins ?? '*',
            'Access-Control-Allow-Methods' => $annotation->methods ?? 'GET, POST, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers' => $annotation->headers ?? '*',
            'Access-Control-Allow-Credentials' => $annotation->credentials ?? true,
            'Access-Control-Allow-Max-Age' => $annotation->maxAge ?? 3600
        ];

        foreach ($corsConfig as $key => $value) {
            $this->getResponse()->headers->set($key, $value);
        }
    }