Python bottle.request.headers() Examples

The following are 16 code examples of bottle.request.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.request , or try the search function .
Example #1
Source File: trigger.py    From infrabox with MIT License 6 votes vote down vote up
def get_next_page(r):
    link = r.headers.get('Link', None)

    if not link:
        return None

    n1 = link.find('rel=\"next\"')

    if n1 < 0:
        return None

    n2 = link.rfind('<', 0, n1)

    if n2 < 0:
        return None

    n2 += 1
    n3 = link.find('>;', n2)
    return link[n2:n3] 
Example #2
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 #3
Source File: bson_bottle_plugin.py    From bii-server with MIT License 6 votes vote down vote up
def _getBson(self):
        ''' If the ``Content-Type`` header is ``application/bson``, this
            property holds the parsed content of the request body. Only requests
            smaller than :attr:`MEMFILE_MAX` are processed to avoid memory
            exhaustion. '''
        max_size = BII_MAX_MEMORY_PER_REQUEST
        if request.headers['Content-Type'] == 'application/bson':
            if 0 < request.content_length < max_size:
                return decode_bson(request.body.read(max_size))
            else:
                logger.error("Max size of bson for request: %i" % request.content_length)
                # DO NOT REMOVE: BODY NEEDS TO BE READED BEFORE RAISE, IT SEEMS LIKE A BOTTLE BUG
                request.body.read(0)
                raise BSONBottlePluginException("Max request size overtaken")
        else:
            raise BSONBottlePluginException("Not Bson request in a method with bson_param specified")
        return None 
Example #4
Source File: restapi.py    From lokun-record with GNU Affero General Public License v3.0 5 votes vote down vote up
def key_auth(name=""):
    """Authenticates a API key."""
    if 'secret' in request.forms:
        secret = request.forms["secret"]
    elif 'X-Lokun-Secret' in request.headers:
        secret = request.headers["X-Lokun-Secret"]
    else:
        abort(401, "Must include a secret")
    try:
        return model.APIKey.auth(secret, name=name)
    except ValueError:
        log("Not accepted: " + repr(request.forms['secret']))
        abort(403, "Secret not accepted")    

# ------------
# /users/
# ------------ 
Example #5
Source File: restapi.py    From lokun-record with GNU Affero General Public License v3.0 5 votes vote down vote up
def getuser(name):
    """This is POST only because GET shows passwords in url.
    TODO: Move key to headers"""
    user = auth(name)
    return dict(user) 
Example #6
Source File: app.py    From aws-servicebroker with Apache License 2.0 5 votes vote down vote up
def post_method(data=None, content_type=None):
    if not data:
        data = request.body.read().decode('utf-8')
    if not content_type:
        content_type = request.content_type
    if 'x-amz-sns-message-type' not in request.headers.keys():
        raise Exception('missing headers')
    if request.headers['x-amz-sns-message-type'] != 'SubscriptionConfirmation':
        return
    url = json.loads(data)['SubscribeURL']
    requests.get(url)
    return 
Example #7
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def session(callback):
    cookie_name = 'session'
    serializer = URLSafeSerializer(conf['SECRET'])

    def inner(*args, **kwargs):
        data_raw = data = request.get_cookie(cookie_name)
        if data_raw:
            try:
                data = serializer.loads(data_raw)
            except (BadSignature, BadData):
                data = None

        if data:
            conf['USER'] = data['username']

        request.session = data or {}

        try:
            return callback(*args, **kwargs)
        finally:
            if request.session:
                save(request.session)
            elif not data_raw:
                pass
            else:
                response.delete_cookie(cookie_name)

    def save(session):
        cookie_opts = {
            # keep session for 3 days
            'max_age': 3600 * 24 * 3,

            # for security
            'httponly': True,
            'secure': request.headers.get('X-Forwarded-Proto') == 'https',
        }
        data = serializer.dumps(session)
        response.set_cookie(cookie_name, data, **cookie_opts)
    return inner 
Example #8
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def nginx():
    h = request.headers
    try:
        login, pw = h['Auth-User'], h['Auth-Pass']
        protocol = h['Auth-Protocol']
    except KeyError as e:
        return abort(400, repr(e))

    if login in conf['IMAP_OFF']:
        response.set_header('Auth-Status', 'Disabled')
        response.set_header('Auth-Wait', 3)
        return ''

    port = {'imap': '143', 'smtp': '25'}[protocol]

    try:
        local.connect(login, pw)
        response.set_header('Auth-Status', 'OK')
        response.set_header('Auth-Server', '127.0.0.1')
        response.set_header('Auth-Port', port)
    except imap.Error as e:
        response.set_header('Auth-Status', str(e))
        response.set_header('Auth-Wait', 3)
    return '' 
Example #9
Source File: trigger.py    From infrabox with MIT License 5 votes vote down vote up
def get_commits(url, token):
    headers = {
        "Authorization": "token " + token,
        "User-Agent": "InfraBox"
    }

    s = requests.Session()

    retries = Retry(total=5,
                    backoff_factor=0.1,
                    status_forcelist=[500, 502, 503, 504])

    s.mount('http://', HTTPAdapter(max_retries=retries))

    # TODO(ib-steffen): allow custom ca bundles
    r = requests.get(url + '?per_page=100', headers=headers, verify=False)
    result = []
    result.extend(r.json())

    p = get_next_page(r)
    while p:
        r = requests.get(p, headers=headers, verify=False)
        p = get_next_page(r)
        result.extend(r.json())

    return result 
Example #10
Source File: trigger.py    From infrabox with MIT License 5 votes vote down vote up
def trigger_build(conn):
    headers = dict(request.headers)

    if 'X-Github-Event' not in headers:
        return res(400, "X-Github-Event not set")

    if 'X-Hub-Signature' not in headers:
        return res(400, "X-Hub-Signature not set")

    event = headers['X-Github-Event']
    sig = headers['X-Hub-Signature']
    #pylint: disable=no-member
    body = request.body.read()
    secret = get_env('INFRABOX_GITHUB_WEBHOOK_SECRET')
    signed = sign_blob(secret, body)

    if signed != sig:
        return res(400, "X-Hub-Signature does not match blob signature")

    trigger = Trigger(conn)
    if event == 'push':
        return trigger.handle_push(request.json)
    elif event == 'pull_request':
        return trigger.handle_pull_request(request.json)

    return res(200, "OK") 
Example #11
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 #12
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 #13
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 #14
Source File: server.py    From homu with MIT License 5 votes vote down vote up
def travis():
    logger = g.logger.getChild('travis')

    info = json.loads(request.forms.payload)

    lazy_debug(logger, lambda: 'info: {}'.format(utils.remove_url_keys_from_json(info)))

    try: state, repo_label = find_state(info['commit'])
    except ValueError:
        lazy_debug(logger, lambda: 'Invalid commit ID from Travis: {}'.format(info['commit']))
        return 'OK'

    lazy_debug(logger, lambda: 'state: {}, {}'.format(state, state.build_res_summary()))

    if 'travis' not in state.build_res:
        lazy_debug(logger, lambda: 'travis is not a monitored target for {}'.format(state))
        return 'OK'

    repo_cfg = g.repo_cfgs[repo_label]
    token = repo_cfg['travis']['token']
    auth_header = request.headers['Authorization']
    code = hashlib.sha256(('{}/{}{}'.format(state.owner, state.name, token)).encode('utf-8')).hexdigest()
    if auth_header != code:
        # this isn't necessarily an error, e.g. maybe someone is
        # fabricating travis notifications to try to trick Homu, but,
        # I imagine that this will most often occur because a repo is
        # misconfigured.
        logger.warn('authorization failed for {}, maybe the repo has the wrong travis token? ' \
                    'header = {}, computed = {}'
                    .format(state, auth_header, code))
        abort(400, 'Authorization failed')

    succ = info['result'] == 0

    report_build_res(succ, info['build_url'], 'travis', state, logger, repo_cfg)

    return 'OK' 
Example #15
Source File: proxy.py    From maloja with GNU General Public License v3.0 4 votes vote down vote up
def instructions(keys):
	authenticated = False
	if "Cookie" in request.headers:
		cookies = request.headers["Cookie"].split(";")
		for c in cookies:
			if c.strip().startswith("apikey="):
				authenticated = checkAPIkey(c.strip()[7:])

	if "token" in keys and authenticated:
		token = keys.get("token")
		parameters = {
			"method":"auth.getSession",
			"token":token,
			"api_key":get_settings("LASTFM_API_KEY")
		}
		response = urllib.request.urlopen("http://ws.audioscrobbler.com/2.0/?" + lfmbuild(parameters))
		xml = response.read()
		data = ET.fromstring(xml)
		if data.attrib.get("status") == "ok":
			username = data.find("session").find("name").text
			sessionkey = data.find("session").find("key").text

			update_settings("settings/settings.ini",{"LASTFM_API_SK":sessionkey,"LASTFM_USERNAME":username},create_new=True)

		return "/proxy"

	else:
		key,secret,sessionkey,name = get_settings("LASTFM_API_KEY","LASTFM_API_SECRET","LASTFM_API_SK","LASTFM_USERNAME")

		if key is None:
			lastfm = "<td>No Last.fm key provided</td>"
		elif secret is None:
			lastfm = "<td>No Last.fm secret provided</td>"
		elif sessionkey is None and authenticated:
			url = "http://www.last.fm/api/auth/?api_key=" + key + "&cb="
			lastfm = "<td class='button'><a id='lastfmlink' href='" + url + "'><div>Connect</div></a></td>"
		elif sessionkey is None:
			lastfm = "<td>Not active</td>"
		else:

			lastfm = "<td>Account: " + name + "</td>"



	return {"KEY_STATUS_LASTFM":lastfm},[] 
Example #16
Source File: uploadcontroller.py    From conifer with Apache License 2.0 4 votes vote down vote up
def init_routes(self):
        wr_api_spec.set_curr_tag('Uploads')

        @self.app.put(['/_upload', '/api/v1/upload'])
        def upload_file():
            user = self.access.session_user
            force_coll_name = request.query.getunicode('force-coll', '')

            if force_coll_name:
                collection = user.get_collection_by_name(force_coll_name)
            else:
                collection = None

            # allow uploading to external collections
            if not collection or not collection.is_external():
                if user.is_anon():
                    return self._raise_error(400, 'not_logged_in')

            expected_size = int(request.headers['Content-Length'])

            if not expected_size:
                return self._raise_error(400, 'no_file_specified')

            filename = request.query.getunicode('filename')
            stream = request.environ['wsgi.input']

            res = self.uploader.upload_file(user,
                                    stream,
                                    expected_size,
                                    filename,
                                    force_coll_name)

            if 'error' in res:
                return self._raise_error(400, res['error'])

            Stats(self.redis).incr_upload(user, expected_size)
            return res

        @self.app.get(['/_upload/<upload_id>', '/api/v1/upload/<upload_id>'])
        def get_upload_status(upload_id):
            user = self.get_user(api=True)

            props = self.uploader.get_upload_status(user, upload_id)

            if not props:
                return self._raise_error(400, 'upload_expired')

            return props