Python bottle.response.headers() Examples

The following are 30 code examples of bottle.response.headers(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bottle.response , or try the search function .
Example #1
Source File: bambleweeny.py    From bambleweeny with MIT License 6 votes vote down vote up
def parse_route(content, user_id):
	if re.search('!@\[[_a-zA-Z0-9:]*\]', content):
		response.headers["B9Y-ROUTES"] = "parsed"
		repl1 = re.sub('!@\[[_a-zA-Z0-9:]*\]', '_B9yPrsE_\\g<0>_B9yPrsE_', content)
		items = repl1.split("_B9yPrsE_")
		out = ""
		for i in items:
			if i.startswith("!@["):
				key = re.sub('[^\w:]', "", i)
				val = rc.get("KEY:"+str(user_id)+"::"+str(key))
				if val != None:
					out += val
			else:
				out += str(i)
		return(out)
	else:
		return(content)

# Key names must match this regex 
Example #2
Source File: app.py    From mailchute with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_app():
    app = bottle.app()
    _route(app, '/emails', ['GET'], resource.get_emails)
    _route(
        app, '/emails/<email_id:int>', ['DELETE'],
        resource.delete_email)
    _route(
        app, '/raw_messages/<raw_message_id>', ['GET'],
        resource.get_raw_message)

    @app.hook('after_request')
    def enable_cors():
        ALLOWED_METHODS = 'PUT, GET, POST, DELETE, OPTIONS'
        ALLOWED_HEADERS = \
            'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = ALLOWED_METHODS
        response.headers['Access-Control-Allow-Headers'] = ALLOWED_HEADERS

    return app 
Example #3
Source File: hmac_plugin.py    From JediHTTP with Apache License 2.0 6 votes vote down vote up
def __call__(self, callback):
        def wrapper(*args, **kwargs):
            if not is_local_request():
                self._logger.info('Dropping request with bad Host header.')
                abort(httplib.UNAUTHORIZED,
                      'Unauthorized, received request from non-local Host.')
                return

            if not self.is_request_authenticated():
                self._logger.info('Dropping request with bad HMAC.')
                abort(httplib.UNAUTHORIZED, 'Unauthorized, received bad HMAC.')
                return

            body = callback(*args, **kwargs)
            self.sign_response_headers(response.headers, body)
            return body
        return wrapper 
Example #4
Source File: downloadcontroller.py    From conifer with Apache License 2.0 5 votes vote down vote up
def wasapi_download(self, username, coll_name, filename):
        user = self._get_wasapi_user(username)

        if not user:
            self._raise_error(404, 'no_such_user')

        collection = user.get_collection_by_name(coll_name)

        if not collection:
            self._raise_error(404, 'no_such_collection')

        # self.access.assert_is_curr_user(user)
        # only users with write access can use wasapi
        self.access.assert_can_write_coll(collection)

        warc_key = collection.get_warc_key()
        warc_path = self.redis.hget(warc_key, filename)

        if not warc_path:
            self._raise_error(404, 'file_not_found')

        response.headers['Content-Type'] = 'application/octet-stream'
        response.headers['Content-Disposition'] = "attachment; filename*=UTF-8''" + filename
        response.headers['Transfer-Encoding'] = 'chunked'

        loader = BlockLoader()
        fh = None
        try:
            fh = loader.load(warc_path)
        except Exception:
            self._raise_error(400, 'file_load_error')

        def read_all(fh):
            for chunk in StreamIter(fh):
                yield chunk

        return read_all(fh) 
Example #5
Source File: hmac_plugin.py    From JediHTTP with Apache License 2.0 5 votes vote down vote up
def is_request_authenticated(self):
        return self._hmachelper.is_request_authenticated(request.headers,
                                                         request.method,
                                                         request.path,
                                                         request.body.read()) 
Example #6
Source File: hmac_plugin.py    From JediHTTP with Apache License 2.0 5 votes vote down vote up
def sign_response_headers(self, headers, body):
        self._hmachelper.sign_response_headers(headers, body) 
Example #7
Source File: hmac_plugin.py    From JediHTTP with Apache License 2.0 5 votes vote down vote up
def is_local_request():
    host = urlparse('http://' + request.headers['host']).hostname
    return host == '127.0.0.1' or host == 'localhost' 
Example #8
Source File: web.py    From CuckooSploit with GNU General Public License v3.0 5 votes vote down vote up
def custom_headers():
    """Set some custom headers across all HTTP responses."""
    response.headers["Server"] = "Machete Server"
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-Frame-Options"] = "DENY"
    response.headers["X-XSS-Protection"] = "1; mode=block"
    response.headers["Pragma"] = "no-cache"
    response.headers["Cache-Control"] = "no-cache"
    response.headers["Expires"] = "0" 
Example #9
Source File: api.py    From CuckooSploit with GNU General Public License v3.0 5 votes vote down vote up
def custom_headers():
    """Set some custom headers across all HTTP responses."""
    response.headers["Server"] = "Machete Server"
    response.headers["X-Content-Type-Options"] = "nosniff"
    response.headers["X-Frame-Options"] = "DENY"
    response.headers["X-XSS-Protection"] = "1; mode=block"
    response.headers["Pragma"] = "no-cache"
    response.headers["Cache-Control"] = "no-cache"
    response.headers["Expires"] = "0" 
Example #10
Source File: api2.py    From codex-backend with MIT License 5 votes vote down vote up
def enable_cors():
    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' 
Example #11
Source File: cors.py    From aerial_wildlife_detection with MIT License 5 votes vote down vote up
def enable_cors(fn):
    def _enable_cors(*args, **kwargs):
        # set CORS headers
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

        if bottle.request.method != 'OPTIONS':
            # actual request; reply with the actual response
            return fn(*args, **kwargs)

    return _enable_cors 
Example #12
Source File: contentcontroller.py    From conifer with Apache License 2.0 5 votes vote down vote up
def do_put_record(self):
        reqid = request.query.getunicode('reqid')
        info = self.browser_mgr.init_remote_browser_session(reqid=reqid)
        if not info:
            return self._raise_error(400, 'invalid_connection_source')

        user = info['the_user']
        collection = info['collection']
        recording = info['recording']

        kwargs = dict(user=user.name,
                      coll=collection.my_id,
                      rec=recording.my_id,
                      type='put_record')

        url = request.query.getunicode('target_uri')

        params = {'url': url}

        upstream_url = self.get_upstream_url('', kwargs, params)

        headers = {'Content-Type': request.environ.get('CONTENT_TYPE', 'text/plain')}

        r = requests.put(upstream_url,
                         data=request.body,
                         headers=headers,
                        )
        try:
            res = r.json()
            if res['success'] != 'true':
                print(res)
                return {'error_message': 'put_record_failed'}

            warc_date = res.get('WARC-Date')

        except Exception as e:
            print(e)
            return {'error_message': 'put_record_failed'}

        return res 
Example #13
Source File: contentcontroller.py    From conifer with Apache License 2.0 5 votes vote down vote up
def _filter_headers(self, type, status_headers):
        if type in ('replay', 'replay-coll'):
            new_headers = []
            for name, value in status_headers.headers:
                if name.lower() != 'set-cookie':
                    new_headers.append((name, value))

            status_headers.headers = new_headers 
Example #14
Source File: contentcontroller.py    From conifer with Apache License 2.0 5 votes vote down vote up
def _inject_nocache_headers(self, status_headers, kwargs):
        if 'browser_id' in kwargs:
            status_headers.headers.append(
                ('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate')
            ) 
Example #15
Source File: bambleweeny.py    From bambleweeny with MIT License 5 votes vote down vote up
def _authenticate():
	# Token can be in query string or AUTH header
	if 'token' in request.query:
		access_token = request.query["token"]
	else:
		bearer = request.environ.get('HTTP_AUTHORIZATION','')
		access_token=bearer[7:]

	# Extract the data from the token
	data = _get_token_data(token=access_token)

	# If there was an error, end here
	if data["error"] != "0":
		return(dict(data))

	# Was the token issued by this cluster?
	if data["cluster_id"] != cluster_id:
		return(dict(data))

	# Is the access token still valid?
	token_timestamp = data["timestamp"]
	current_time = int(time.time())
	delta = current_time - token_timestamp
	if delta > token_expiry_seconds:
		# expired
		data["authenticated"] = "False"
		data["info"] = "Token expired"
	else:
		# valid
		data["authenticated"] = "True"
		data["info"] = "Session expires in " + str(token_expiry_seconds - delta) + " seconds."
		# Set response header: username
		response.headers["B9Y-AUTHENTICATED-USER"] = data["user"]

	return(dict(data)) 
Example #16
Source File: snapshotcontroller.py    From conifer with Apache License 2.0 5 votes vote down vote up
def snapshot_cont(self):
        info = self.browser_mgr.init_remote_browser_session()
        if not info:
            return {'error_message': 'conn not from valid containerized browser'}

        user = info['the_user']
        collection = info['collection']

        browser = info['browser']

        url = request.query.getunicode('url')

        title = request.query.getunicode('title')

        html_text = request.body.read().decode('utf-8')

        referrer = request.environ.get('HTTP_REFERER', '')

        user_agent = request.environ.get('HTTP_USER_AGENT')

        noprewriter = NopRewriter()
        html_unrewriter = HTMLDomUnRewriter(noprewriter)

        html_text = html_unrewriter.unrewrite(html_text)

        origin = request.environ.get('HTTP_ORIGIN')
        if origin:
            response.headers['Access-Control-Allow-Origin'] = origin

        #TODO
        return self.write_snapshot(user, collection, url,
                                   title, html_text, referrer,
                                   user_agent, browser) 
Example #17
Source File: basecontroller.py    From conifer with Apache License 2.0 5 votes vote down vote up
def set_options_headers(self, origin_host, target_host, response_obj=None):
        origin = request.environ.get('HTTP_ORIGIN')

        if origin_host:
            expected_origin = request.environ['wsgi.url_scheme'] + '://' + origin_host

            # ensure origin is the content host origin
            if origin != expected_origin:
                return False

        host = request.environ.get('HTTP_HOST')
        # ensure host is the app host
        if target_host and host != target_host:
            return False

        headers = response.headers if not response_obj else response_obj.headers

        headers['Access-Control-Allow-Origin'] = origin if origin_host else '*'

        methods = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
        if methods:
            headers['Access-Control-Allow-Methods'] = methods

        req_headers = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS')
        if req_headers:
            headers['Access-Control-Allow-Headers'] = req_headers

        headers['Access-Control-Allow-Credentials'] = 'true'
        headers['Access-Control-Max-Age'] = '1800'
        return True 
Example #18
Source File: basecontroller.py    From conifer with Apache License 2.0 5 votes vote down vote up
def get_redir_back(self, skip, default='/'):
        redir_to = request.headers.get('Referer', default)
        if redir_to.endswith(skip):
            redir_to = default
        return redir_to 
Example #19
Source File: main.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def enable_cors():
    if response:
        response.headers['Access-Control-Allow-Origin'] = '*' 
Example #20
Source File: index.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def testindex():
    # ip = request.environ.get('REMOTE_ADDR')
    # response.headers['X-IP'] = '{0}'.format(ip)
    response.status=200

# act like elastic search bulk index 
Example #21
Source File: index.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def enable_cors(fn):
    ''' cors decorator for rest/ajax'''
    def _enable_cors(*args, **kwargs):
        # set CORS headers
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

        if bottle.request.method != 'OPTIONS':
            # actual request; reply with the actual response
            return fn(*args, **kwargs)

    return _enable_cors 
Example #22
Source File: index.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def test():
    '''test endpoint for..testing'''
    # ip = request.environ.get('REMOTE_ADDR')
    # response.headers['X-IP'] = '{0}'.format(ip)
    response.status = 200

    sendMessgeToPlugins(request, response, 'test')
    return response 
Example #23
Source File: index.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def index():
    '''
    return a json version of dshield query for an ip address
    https://isc.sans.edu/api/index.html
    '''
    if request.body:
        arequest = request.body.read()
        request.body.close()
    # valid json?
    try:
        requestDict = json.loads(arequest)
    except ValueError:
        response.status = 500
        return
    if 'ipaddress' in requestDict and isIPv4(requestDict['ipaddress']):
        url="https://isc.sans.edu/api/ip/"

        headers = {
            'User-Agent': options.user_agent
        }

        dresponse = requests.get('{0}{1}?json'.format(url, requestDict['ipaddress']), headers=headers)
        if dresponse.status_code == 200:
            response.content_type = "application/json"
            response.body = dresponse.content
        else:
            response.status = dresponse.status_code

    else:
        response.status = 500

    sendMessgeToPlugins(request, response, 'ipdshieldquery')
    return response 
Example #24
Source File: bambleweeny.py    From bambleweeny with MIT License 5 votes vote down vote up
def get_route(id, dummy=0, dummy2=0):
	route_key = "ROUTE:"+str(id)

	# Read Route from Redis
	try:
		route_content = rc.get(route_key)
		if route_content == None:
			raise ValueError('not found')

		route_record = json.loads(route_content)
		user_id = route_record["user_id"]
		key = route_record["key"]
		content_type = route_record["content_type"]

	except:
		response.status = 404
		return dict({"info":"Not found."})

	# Construct Resource Location from user_id and id
	redis_key = "KEY:"+str(user_id)+"::"+str(key)

	# Read from Redis
	try:
		key_content = rc.get(redis_key)
		if key_content == None:
			raise ValueError('not found.')
	except:
		response.status = 404
		return dict({"info":"Not found."})

	response.headers['Access-Control-Allow-Origin'] = '*'
	response.content_type = content_type
	return(parse_route(str(key_content), user_id))

# Create Bins 
Example #25
Source File: bottle2.py    From pyFileFixity with MIT License 5 votes vote down vote up
def set_content_type(self, value):
        self.headers['Content-Type'] = value 
Example #26
Source File: api.py    From ray with MIT License 5 votes vote down vote up
def to_json(fnc):
    @wraps(fnc)
    def inner(*args, **kwargs):
        bottle_resp.headers['Content-Type'] = 'application/json'
        from_func = fnc(*args, **kwargs)
        if from_func is not None:
            return json.dumps({'result': from_func})
    return inner 
Example #27
Source File: wordserver.py    From burgundy with MIT License 5 votes vote down vote up
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*' 
Example #28
Source File: bottle2.py    From pyFileFixity with MIT License 5 votes vote down vote up
def __init__(self, output='', status=200, header=None):
        super(BottleException, self).__init__("HTTP Response %d" % status)
        self.status = int(status)
        self.output = output
        self.headers = HeaderDict(header) if header else None 
Example #29
Source File: bottle2.py    From pyFileFixity with MIT License 5 votes vote down vote up
def apply(self, response):
        if self.headers:
            for key, value in self.headers.iterallitems():
                response.headers[key] = value
        response.status = self.status 
Example #30
Source File: bottle2.py    From pyFileFixity with MIT License 5 votes vote down vote up
def header(self):
        ''' :class:`HeaderDict` filled with request headers.

            HeaderDict keys are case insensitive str.title()d
        '''
        if self._header is None:
            self._header = HeaderDict()
            for key, value in self.environ.iteritems():
                if key.startswith('HTTP_'):
                    key = key[5:].replace('_','-').title()
                    self._header[key] = value
        return self._header