Generate allow origin header
193356
def allow_origin(self, request):
        # type: (BaseHttpRequest) -> str
        
        origins = self.origins
        if origins is AnyOrigin:
            return '*'
        else:
            origin = request.origin
            return origin if origin in origins else ''
243467
def pale_webapp2_request_handler_generator(pale_endpoint):
    
    def pale_handler(self, *args, **kwargs):
        if self.request.method == "OPTIONS":
            origin = self.request.headers.get("Origin", None)
            self.response.headers['Access-Control-Allow-Origin'] = origin
            self.response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
            self.response.headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE'
            self.response.headers['Access-Control-Allow-Credentials'] = 'true'
            return self.response

        try:
            return pale_endpoint._execute(self.request)
        finally:
            pale_endpoint._finally()

    cls = type(pale_endpoint._route_name,
            (webapp2.RequestHandler,),
            dict(pale_handler=pale_handler))
    return cls
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)
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();
  }
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)
681400
function ( xhr, uri, type ) {
		var headers = string.trim( xhr.getAllResponseHeaders() ).split( "\n" ),
		    items   = {},
		    o       = {},
		    allow   = null,
		    expires = new Date(),
		    cors    = client.cors( uri );

		array.each( headers, function ( i ) {
			var header, value;

			value         = i.replace( regex.header_value_replace, "" );
			header        = i.replace( regex.header_replace, "" );
			header        = string.unhyphenate( header, true ).replace( /\s+/g, "-" );
			items[header] = value;

			if ( allow === null ) {
				if ( ( !cors && regex.allow.test( header) ) || ( cors && regex.allow_cors.test( header) ) ) {
					allow = value;
				}
			}
		});

		if ( regex.no.test( items["Cache-Control"] ) ) {
			// Do nothing
		}
		else if ( items["Cache-Control"] !== undefined && regex.number_present.test( items["Cache-Control"] ) ) {
			expires = expires.setSeconds( expires.getSeconds() + number.parse( regex.number_present.exec( items["Cache-Control"] )[0], 10 ) );
		}
		else if ( items.Expires !== undefined ) {
			expires = new Date( items.Expires );
		}
		else {
			expires = expires.setSeconds( expires.getSeconds() + $.expires );
		}

		o.expires    = expires;
		o.headers    = items;
		o.permission = client.bit( allow !== null ? string.explode( allow ) : [type] );

		if ( type === "get" ) {
			cache.set( uri, "expires",    o.expires );
			cache.set( uri, "headers",    o.headers );
			cache.set( uri, "permission", o.permission );
		}

		return o;
	}
265291
function corsPrefetch(req, res, next) {
	res.header('Access-Control-Allow-Origin', req.headers.origin);
	res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
	res.header('Access-Control-Allow-Headers', 'Content-Type, *');
	res.setHeader('Access-Control-Allow-Credentials', 'true');

	if (req.method === 'OPTIONS') {
		res.sendStatus(200);
		return;
	}

	next();
}
1133065
private String checkOriginHeader(HttpServletRequest request, JCorsConfig config) {

		String originHeader = request.getHeader(CorsHeaders.ORIGIN_HEADER);
		Constraint.ensureNotEmpty(originHeader, "Cross-Origin requests must specify an Origin Header");

		String[] origins = originHeader.split(" ");

		for (String origin : origins) {
			Constraint.ensureTrue(config.isOriginAllowed(origin), String.format("The specified origin is not allowed: '%s'", origin));
		}

		return originHeader;
	}
1183894
def disable_cors(self):
        
        return self.update_cors_configuration(
            enable_cors=False,
            allow_credentials=False,
            origins=[],
            overwrite_origins=True
        )
560817
public static function attachOriginHeader($response, $origin)
	{
		if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
			$response->headers->set('Access-Control-Allow-Origin', $origin);
			return true;
		}
		
		if ('*' == config('api.cors_allowed_origin', 'client')) {
			$response->headers->set('Access-Control-Allow-Origin', '*');
			return true;
		}
		
		if ('client' == config('api.cors_allowed_origin', 'client')) {
			$client = Authentication::instance()->client();
			if (empty($client) || empty($client->endpoints())) {
				return false;
			}
			
			foreach ($client->endpoints() as $endpoint) {
				$parts = parse_url($endpoint);
				if (empty($parts['scheme']) || empty($parts['host'])) {
					continue;
				}
				
				$port = '';
				if (array_get($parts, 'port')) {
					$port = ':' . array_get($parts, 'port');
				}
				
				$url = $parts['scheme'] . '://' . $parts['host'] . $port;
				
				if ($origin == $url) {
					$response->headers->set('Access-Control-Allow-Origin', $url);
					return true;
				}
			}
		}
		
		return false;
	}
995439
function proxy()
    {
        if (!UserRights(EDITOR))
            die;

        $filename = Eresus_CMS::getLegacyKernel()->request['path'] .
            Eresus_CMS::getLegacyKernel()->request['file'];
        $filename = Eresus_CMS::getLegacyKernel()->froot . substr($filename,
                strlen(Eresus_CMS::getLegacyKernel()->root));

        if (is_dir($filename))
        {
            $filename = Eresus_FS_Tool::normalize($filename . '/index.php');
        }

        if (!is_file($filename))
        {
            header('Not found', true, 404);
            die('<h1>Not found.</h1>');
        }

        $ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

        switch (true)
        {
            case in_array($ext, array('png', 'jpg', 'jpeg', 'gif')):
                $info = getimagesize($filename);
                header('Content-type: '.$info['mime']);
                echo file_get_contents($filename);
                break;

            case $ext == 'js':
                header('Content-type: text/javascript');
                $s = file_get_contents($filename);
                $s = $this->replaceMacros($s);
                echo $s;
                break;

            case $ext == 'css':
                header('Content-type: text/css');
                $s = file_get_contents($filename);
                $s = $this->replaceMacros($s);
                echo $s;
                break;

            case $ext == 'html':
            case $ext == 'htm':
                header('Content-type: text/html');
                $s = file_get_contents($filename);
                $s = $this->replaceMacros($s);
                echo $s;
                break;

            case $ext == 'php':
                Eresus_CMS::getLegacyKernel()->conf['debug']['enable'] = false;
                restore_error_handler();
                chdir(dirname($filename));
                require $filename;
                break;
        }
    }
1040253
function generate(allows) {
  return function (req, res, next) {
    req.route.allows = allows;
    next();
  };
}
415379
function handleOptions(req, res) {
  var acrh = req.headers['access-control-request-headers'];
  var origin = req.headers['origin'];
  if (acrh) res.setHeader('Access-Control-Allow-Headers', acrh);
  if (origin) res.setHeader('Access-Control-Allow-Origin', origin);
  res.end();
}
603401
private function cors($request)
  {
    $origin  = $request->server->http_origin;
    $allowed = Config::get('cors.allowedOrigins');

    if (in_array('*', $allowed) || in_array($origin, $allowed) ) {
      $this->withHeaders($request);
    }
  }
788504
protected function CORS()
    {
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
            $this->header('Access-Control-Allow-Headers: ' . $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
        }
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] !== 'null') {
            $this->header('Access-Control-Allow-Origin:' . $_SERVER['HTTP_ORIGIN']);
        } else {
            $this->header('Access-Control-Allow-Origin: *');
        }
        $this->header('Access-Control-Allow-Credentials: true');
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            $this->header('204 No Content');
            $this->header('Cache-Control: max-age=31536000, public, pre-check=0, post-check=0');
            $this->header('Access-Control-Max-Age: 31536000');
            $this->header('Access-Control-Allow-Methods: OPTIONS, ' . $this->allowedMethods);
            $this->header('Expires: ' . date('r', strtotime('+1 year')));
            $this->finish();
        } elseif (!in_array($_SERVER['REQUEST_METHOD'], explode(', ', $this->allowedMethods), true)) {
            $this->header('405 Method Not Allowed');
            $this->finish();
        }
    }
907267
def build_extra_headers(request, proxyMode, orgaMode, currentOrga):
    """"""

    things_to_add = {}

    # If in proxymode, add needed infos to headers
    if proxyMode:

        # User
        for prop in settings.PIAPI_USERDATA:
            if hasattr(request.user, prop):
                things_to_add['user_' + prop] = getattr(request.user, prop)

        # Orga
        if orgaMode:
            things_to_add['orga_pk'] = currentOrga.pk
            things_to_add['orga_name'] = currentOrga.name
            things_to_add['orga_codops'] = currentOrga.ebu_codops

        # General
        things_to_add['base_url'] = baseURI

    if request and hasattr(request, 'META'):
        if 'REMOTE_ADDR' in request.META:
            things_to_add['remote-addr'] = request.META['REMOTE_ADDR']

        if 'HTTP_X_FORWARDED_FOR' in request.META and getattr(settings, 'HONOR_X_FORWARDED_FOR'):
            things_to_add['remote-addr'] = request.META['HTTP_X_FORWARDED_FOR']

        for meta_header, dest_header in [('HTTP_IF_NONE_MATCH', 'If-None-Match'), ('HTTP_ORIGIN', 'Origin'), ('HTTP_ACCESS_CONtROL_REQUEST_METHOD', 'Access-Control-Request-Method'), ('HTTP_ACCESS_CONTROL_REQUEST_HEADERS', 'Access-Control-Request-Headers')]:
            if meta_header in request.META:
                things_to_add[dest_header] = request.META[meta_header]

    return things_to_add
1275555
def create_header(self, service_id, version_number, name, destination, source, _type=FastlyHeaderType.RESPONSE, action=FastlyHeaderAction.SET, regex=None, substitution=None, ignore_if_set=None, priority=10, response_condition=None, cache_condition=None, request_condition=None):
		body = self._formdata({
			"name": name,
			"dst": destination,
			"src": source,
			"type": _type,
			"action": action,
			"regex": regex,
			"substitution": substitution,
			"ignore_if_set": ignore_if_set,
			"priority": priority,
			"response_condition": response_condition,
			"request_condition": request_condition,
			"cache_condition": cache_condition,
		}, FastlyHeader.FIELDS)
		""""""
		content = self._fetch("/service/%s/version/%d/header" % (service_id, version_number), method="POST", body=body)
		return FastlyHeader(self, content)