async def feedback(request): if not APP_EMAIL: raise errors.HttpProcessingError(code=500, message="Invalid configuration.") data = await request.post() recaptchaResponse = data['recaptchaResponse'] async with ClientSession() as session: async with session.post("https://www.google.com/recaptcha/api/siteverify", data={ 'secret': RECAPTCHA_SECRET_KEY, 'response': recaptchaResponse }) as response: if response.status != 200: raise RecaptchaError() response = await response.read() response = ujson.loads(response) if not response['success']: raise RecaptchaError() if data['email'] and EMAIL_REGEXP.match(data['email']): sender = data['email'] else: sender = "*****@*****.**" message = "Subject: Kana app feedback from {name}\n\nname: {name}\nemail: {email}\nmessage: {message}".format( name=data['name'], email=data['email'], message=data['message'] ) smtp = aiosmtplib.SMTP(hostname=SMTP_HOST, port=SMTP_PORT, loop=asyncio.get_event_loop()) await smtp.connect() await smtp.sendmail(sender, [APP_EMAIL], message) await smtp.close() return web.Response(text="Ok", content_type='text/plain')
def test_http_error_exception(): exc = errors.HttpProcessingError(code=500, message='Internal error') assert exc.code == 500 assert exc.message == 'Internal error'
def do_handshake(method, headers, transport, protocols=()): """Prepare WebSocket handshake. It return http response code, response headers, websocket parser, websocket writer. It does not perform any IO. `protocols` is a sequence of known protocols. On successful handshake, the returned response headers contain the first protocol in this list which the server also knows.""" # WebSocket accepts only GET if method.upper() != 'GET': raise errors.HttpProcessingError(code=405, headers=(('Allow', 'GET'), )) if 'websocket' != headers.get('UPGRADE', '').lower().strip(): raise errors.HttpBadRequest(message='No WebSocket UPGRADE hdr: {}\n' 'Can "Upgrade" only to "WebSocket".'. format(headers.get('UPGRADE'))) if 'upgrade' not in headers.get('CONNECTION', '').lower(): raise errors.HttpBadRequest( message='No CONNECTION upgrade hdr: {}'.format( headers.get('CONNECTION'))) # find common sub-protocol between client and server protocol = None if 'SEC-WEBSOCKET-PROTOCOL' in headers: req_protocols = [ str(proto.strip()) for proto in headers['SEC-WEBSOCKET-PROTOCOL'].split(',') ] for proto in req_protocols: if proto in protocols: protocol = proto break else: # No overlap found: Return no protocol as per spec ws_logger.warning( 'Client protocols %r don’t overlap server-known ones %r', protocols, req_protocols) # check supported version version = headers.get('SEC-WEBSOCKET-VERSION') if version not in ('13', '8', '7'): raise errors.HttpBadRequest( message='Unsupported version: {}'.format(version), headers=(('Sec-WebSocket-Version', '13', '8', '7'), )) # check client handshake for validity key = headers.get('SEC-WEBSOCKET-KEY') try: if not key or len(base64.b64decode(key)) != 16: raise errors.HttpBadRequest( message='Handshake error: {!r}'.format(key)) except binascii.Error: raise errors.HttpBadRequest( message='Handshake error: {!r}'.format(key)) from None response_headers = [ ('UPGRADE', 'websocket'), ('CONNECTION', 'upgrade'), ('TRANSFER-ENCODING', 'chunked'), ('SEC-WEBSOCKET-ACCEPT', base64.b64encode(hashlib.sha1(key.encode() + WS_KEY).digest()).decode()) ] if protocol: response_headers.append(('SEC-WEBSOCKET-PROTOCOL', protocol)) # response code, headers, parser, writer, protocol return (101, response_headers, WebSocketParser, WebSocketWriter(transport), protocol)
def do_handshake(method, headers, transport, protocols=(), write_buffer_size=DEFAULT_LIMIT): """Prepare WebSocket handshake. It return HTTP response code, response headers, websocket parser, websocket writer. It does not perform any IO. `protocols` is a sequence of known protocols. On successful handshake, the returned response headers contain the first protocol in this list which the server also knows. `write_buffer_size` max size of write buffer before `drain()` get called. """ # WebSocket accepts only GET if method.upper() != hdrs.METH_GET: raise errors.HttpProcessingError(code=405, headers=((hdrs.ALLOW, hdrs.METH_GET), )) if 'websocket' != headers.get(hdrs.UPGRADE, '').lower().strip(): raise errors.HttpBadRequest( message='No WebSocket UPGRADE hdr: {}\n Can ' '"Upgrade" only to "WebSocket".'.format(headers.get(hdrs.UPGRADE))) if 'upgrade' not in headers.get(hdrs.CONNECTION, '').lower(): raise errors.HttpBadRequest( message='No CONNECTION upgrade hdr: {}'.format( headers.get(hdrs.CONNECTION))) # find common sub-protocol between client and server protocol = None if hdrs.SEC_WEBSOCKET_PROTOCOL in headers: req_protocols = [ str(proto.strip()) for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(',') ] for proto in req_protocols: if proto in protocols: protocol = proto break else: # No overlap found: Return no protocol as per spec ws_logger.warning( 'Client protocols %r don’t overlap server-known ones %r', req_protocols, protocols) # check supported version version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, '') if version not in ('13', '8', '7'): raise errors.HttpBadRequest( message='Unsupported version: {}'.format(version), headers=((hdrs.SEC_WEBSOCKET_VERSION, '13'), )) # check client handshake for validity key = headers.get(hdrs.SEC_WEBSOCKET_KEY) try: if not key or len(base64.b64decode(key)) != 16: raise errors.HttpBadRequest( message='Handshake error: {!r}'.format(key)) except binascii.Error: raise errors.HttpBadRequest( message='Handshake error: {!r}'.format(key)) from None response_headers = [ (hdrs.UPGRADE, 'websocket'), (hdrs.CONNECTION, 'upgrade'), (hdrs.TRANSFER_ENCODING, 'chunked'), (hdrs.SEC_WEBSOCKET_ACCEPT, base64.b64encode(hashlib.sha1(key.encode() + WS_KEY).digest()).decode()) ] if protocol: response_headers.append((hdrs.SEC_WEBSOCKET_PROTOCOL, protocol)) # response code, headers, parser, writer, protocol return (101, response_headers, WebSocketParser, WebSocketWriter(transport, limit=write_buffer_size), protocol)
def test_http_error_exception(self): exc = errors.HttpProcessingError(code=500, message='Internal error') self.assertEqual(exc.code, 500) self.assertEqual(exc.message, 'Internal error')