This is a decorator which enable CORS for the specified endpoint.
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
583501
def _add_cors(self):
        

        INVALID_ERROR = "Invalid value for 'Cors' property"

        if not self.cors:
            return

        if self.cors and not self.definition_body:
            raise InvalidResourceException(self.logical_id,
                                           "Cors works only with inline Swagger specified in "
                                           "'DefinitionBody' property")

        if isinstance(self.cors, string_types) or is_instrinsic(self.cors):
            # Just set Origin property. Others will be defaults
            properties = CorsProperties(AllowOrigin=self.cors)
        elif isinstance(self.cors, dict):

            # Make sure keys in the dict are recognized
            if not all(key in CorsProperties._fields for key in self.cors.keys()):
                raise InvalidResourceException(self.logical_id, INVALID_ERROR)

            properties = CorsProperties(**self.cors)

        else:
            raise InvalidResourceException(self.logical_id, INVALID_ERROR)

        if not SwaggerEditor.is_valid(self.definition_body):
            raise InvalidResourceException(self.logical_id, "Unable to add Cors configuration because "
                                                            "'DefinitionBody' does not contain a valid Swagger")

        if properties.AllowCredentials is True and properties.AllowOrigin == _CORS_WILDCARD:
            raise InvalidResourceException(self.logical_id, "Unable to add Cors configuration because "
                                                            "'AllowCredentials' can not be true when "
                                                            "'AllowOrigin' is \"'*'\" or not set")

        editor = SwaggerEditor(self.definition_body)
        for path in editor.iter_on_path():
            editor.add_cors(path, properties.AllowOrigin, properties.AllowHeaders, properties.AllowMethods,
                            max_age=properties.MaxAge, allow_credentials=properties.AllowCredentials)

        # Assign the Swagger back to template
        self.definition_body = editor.swagger
274543
def OPTIONS(self, *args, **kwargs):
        
        if not self.cors:
            raise CallError(405)

        req = self.request

        origin = req.get_header('origin')
        if not origin:
            raise CallError(400, 'Need Origin header') 
        call_headers = [
            ('Access-Control-Request-Headers', 'Access-Control-Allow-Headers'),
            ('Access-Control-Request-Method', 'Access-Control-Allow-Methods')
        ]
        for req_header, res_header in call_headers:
            v = req.get_header(req_header)
            if v:
                self.response.set_header(res_header, v)
            else:
                raise CallError(400, 'Need {} header'.format(req_header))

        other_headers = {
            'Access-Control-Allow-Credentials': 'true',
            'Access-Control-Max-Age': 3600
        }
        self.response.add_headers(other_headers)
397988
def put(self, endpoint: str, **kwargs) -> dict:
        """"""

        return self._request('PUT', endpoint, **kwargs)
800248
def post(self, endpoint, data):
        
        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "x-standardize-only": "true" if self.standardize else "false",
            "x-include-invalid": "true" if self.invalid else "false",
            "x-accept-keypair": "true" if self.accept_keypair else "false",
        }
        if not self.logging:
            headers["x-suppress-logging"] = "true"

        params = {"auth-id": self.auth_id, "auth-token": self.auth_token}
        url = self.BASE_URL + endpoint
        response = self.session.post(
            url,
            json.dumps(stringify(data)),
            params=params,
            headers=headers,
            timeout=self.timeout,
        )
        if response.status_code == 200:
            return response.json()

        raise ERROR_CODES.get(response.status_code, SmartyStreetsError)
1190540
def allow_origins(self, *origins, methods=None, max_age=None, credentials=None, headers=None, **overrides):
        """"""
        response_headers = {}
        if origins:
            @hug.response_middleware()
            def process_data(request, response, resource):
                if 'ORIGIN' in request.headers:
                    origin = request.headers['ORIGIN']
                    if origin in origins:
                        response.set_header('Access-Control-Allow-Origin', origin)
        else:
            response_headers['Access-Control-Allow-Origin'] = '*'

        if methods:
            response_headers['Access-Control-Allow-Methods'] = ', '.join(methods)
        if max_age:
            response_headers['Access-Control-Max-Age'] = max_age
        if credentials:
            response_headers['Access-Control-Allow-Credentials'] = str(credentials).lower()
        if headers:
            response_headers['Access-Control-Allow-Headers'] = headers
        return self.add_response_headers(response_headers, **overrides)
1021799
def get(self, endpoint, **kwargs):
        
        return self._request(requests.get, endpoint, **kwargs)
271031
@Nullable
    private CorsPolicy setCorsOrigin(ServiceRequestContext ctx, HttpRequest request, HttpHeaders headers) {
        if (!config.isEnabled()) {
            return null;
        }

        final String origin = request.headers().get(HttpHeaderNames.ORIGIN);
        if (origin != null) {
            final CorsPolicy policy = config.getPolicy(origin, ctx.pathMappingContext());
            if (policy == null) {
                logger.debug(
                        "{} There is no CORS policy configured for the request origin '{}' and the path '{}'.",
                        ctx, origin, ctx.path());
                return null;
            }
            if (NULL_ORIGIN.equals(origin)) {
                setCorsNullOrigin(headers);
                return policy;
            }
            if (config.isAnyOriginSupported()) {
                if (policy.isCredentialsAllowed()) {
                    echoCorsRequestOrigin(request, headers);
                    setCorsVaryHeader(headers);
                } else {
                    setCorsAnyOrigin(headers);
                }
                return policy;
            }
            setCorsOrigin(headers, origin);
            setCorsVaryHeader(headers);
            return policy;
        }
        return null;
    }
989586
function restifyCORSSimple(req, res, next) {
    var origin;
    if (!(origin = matchOrigin(req, origins))) {
      next();
      return;
    }

    function corsOnHeader() {
      origin = req.headers.origin;

      if (opts.credentials) {
        res.setHeader(AC_ALLOW_CREDS, 'true');
      }

      res.setHeader(AC_ALLOW_ORIGIN, origin);
      res.setHeader(AC_EXPOSE_HEADERS, headers.join(', '));
      res.setHeader(AC_ALLOW_METHODS, ALLOW_METHODS.join(', '));
      res.setHeader(AC_ALLOW_HEADERS, ALLOW_HEADERS.join(', '));
      res.setHeader(AC_REQUEST_HEADERS, REQUEST_HEADERS.join(', '));
    }

    res.once('header', corsOnHeader);
    next();
  }
1045783
public Blade enableCors(boolean enableCors, CorsConfiger corsConfig) {
        this.environment.set(ENV_KEY_CORS_ENABLE, enableCors);
        if (enableCors) {
            this.corsMiddleware = new CorsMiddleware(corsConfig);
        }
        return this;
    }
229003
def set_cors_config(app):
    
    if "CORS" in app.config:
        for k, v in app.config["CORS"].items():
            _ = "CORS_" + k.upper()
            if _ not in app.config:
                app.config[_] = v
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
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;
  }
1120119
def init_app(self, app):
        
        self.init_config(app)

        # Enable CORS support if desired
        if app.config['REST_ENABLE_CORS']:
            from flask_cors import CORS
            CORS(app)
            # CORS can be configured using CORS_* configuration variables.

        app.errorhandler(400)(create_api_errorhandler(
            status=400, message='Bad Request'))
        app.errorhandler(401)(create_api_errorhandler(
            status=401, message='Unauthorized'))
        app.errorhandler(403)(create_api_errorhandler(
            status=403, message='Forbidden'))
        app.errorhandler(404)(create_api_errorhandler(
            status=404, message='Not Found'))
        app.errorhandler(405)(create_api_errorhandler(
            status=405, message='Method Not Allowed'))
        app.errorhandler(406)(create_api_errorhandler(
            status=406, message='Not Acceptable'))
        app.errorhandler(409)(create_api_errorhandler(
            status=409, message='Conflict'))
        app.errorhandler(410)(create_api_errorhandler(
            status=410, message='Gone'))
        app.errorhandler(412)(create_api_errorhandler(
            status=412, message='Precondition Failed'))
        app.errorhandler(415)(create_api_errorhandler(
            status=415, message='Unsupported media type'))
        app.errorhandler(422)(create_api_errorhandler(
            status=422, message='Unprocessable Entity'))
        app.errorhandler(429)(create_api_errorhandler(
            status=429, message='Rate limit exceeded'))
        app.errorhandler(500)(create_api_errorhandler(
            status=500, message='Internal Server Error'))
        app.errorhandler(501)(create_api_errorhandler(
            status=501, message='Not Implemented'))
        app.errorhandler(502)(create_api_errorhandler(
            status=502, message='Bad Gateway'))
        app.errorhandler(503)(create_api_errorhandler(
            status=503, message='Service Unavailable'))
        app.errorhandler(504)(create_api_errorhandler(
            status=504, message='Gateway Timeout'))

        app.extensions['invenio-rest'] = self
1093665
def register(self, endpoint, procedure=None, options=None):
        
        def proxy_endpoint(*args, **kwargs):
            return self._callbacks_runner.put(partial(endpoint, *args, **kwargs))
        return self._async_session.register(proxy_endpoint, procedure=procedure, options=options)
1298727
def cors_wrapper(func):
    
    def _setdefault(obj, key, value):
        if value == None:
            return
        obj.setdefault(key, value)

    def output(*args, **kwargs):
        response = func(*args, **kwargs)
        headers = response.headers
        _setdefault(headers, "Access-Control-Allow-Origin", "*")
        _setdefault(headers, "Access-Control-Allow-Headers", flask.request.headers.get("Access-Control-Request-Headers"))
        _setdefault(headers, "Access-Control-Allow-Methods", flask.request.headers.get("Access-Control-Request-Methods"))
        _setdefault(headers, "Content-Type", "application/json")
        _setdefault(headers, "Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
        return response

    output.provide_automatic_options = False
    output.__name__ = func.__name__
    return output
1362272
def _configure_endpoint(self, endpoint):
        """"""
        if not endpoint.startswith('http'):
            endpoint = 'https://' + endpoint
        if not endpoint.endswith('/'):
            endpoint += '/'
        return endpoint