Exemplo n.º 1
0
    async def renew_token(self, scope: Scope, info: Info,
                          matches: RouteMatches,
                          content: Content) -> HttpResponse:
        try:
            payload = self.token_manager.get_jwt_payload_from_headers(
                scope['headers'])
            if payload is None:
                return http_status_code.UNAUTHORIZED, None, None

            email = payload['sub']
            issued_at = payload['iat']

            logger.debug(
                f'Token renewal request: user={email}, iat={issued_at}')

            utc_now = datetime.utcnow()

            authentication_expiry = issued_at + self.login_expiry
            if utc_now > authentication_expiry:
                return http_status_code.FORBIDDEN, [
                    (b'content-type', b'text/plain')
                ], text_writer('Expired')

            if not await self.auth_service.user_valid(email):
                return http_status_code.FORBIDDEN, [
                    (b'content-type', b'text/plain')
                ], text_writer('Invalid user')

            logger.debug(f'Token renewed: {email}')

            return self._authenticated_response(scope, email)
        except Exception as error:
            return http_status_code.INTERNAL_SERVER_ERROR, [
                (b'content-type', b'text/plain')
            ], text_writer(str(error))
async def raise_writer_exception(scope: Scope, _info: Info,
                                 _matches: RouteMatches,
                                 _content: Content) -> HttpResponse:
    """A request handler which raises an exception with a writer content"""
    raise HTTPError(make_url(scope), 401, text_writer('Unauthorized - writer'),
                    [(b'content-type', b'text/plain')], None)
    # pylint: disable=unreachable
    return 200, [(b'content-type', b'text/plain')
                 ], text_writer('This is not a test')
Exemplo n.º 3
0
async def test_page(scope: Scope, info: Info, _matches: RouteMatches,
                    _content: Content) -> HttpResponse:
    """A request handler which provides the page to respond to server sent events"""
    host = header.find(b'host', scope['headers']).decode()
    fetch_url = f"{scope['scheme']}://{host}/events"
    html = info['page_template'].substitute(__FETCH_URL__=fetch_url)
    return 200, [(b'content-type', b'text/html')], text_writer(html)
async def test_page(scope: Scope, info: Info, matches: RouteMatches,
                    content: Content) -> HttpResponse:
    """A request handler which provides the page to respond to server sent events"""
    html = """
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Example</title>
  </head>
  <body>
    <h1>Server Sent Events</h1>
    
    Time: <snap id="time"></span>
    
    <script>
      var eventSource = new EventSource("/events")
      eventSource.onmessage = function(event) {
        element = document.getElementById("time")
        element.innerHTML = event.data
      }
    </script>
  </body>
</html>

"""
    return 200, [(b'content-type', b'text/html')], text_writer(html)
async def test_page(
        scope: Scope,
        info: Info,
        matches: RouteMatches,
        content: Content
) -> HttpResponse:
    """A simple page which receives server sent events"""
    html = """
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Server Sent Evets</title>
  </head>
  <body>
    <h1>Server Sent Events</h1>
    
    Time: <snap id="time"></span>
    
    <script>
      var eventSource = new EventSource("http://localhost:9009/events")
      eventSource.onmessage = function(event) {
        console.log('onmessage', event)
        element = document.getElementById("time")
        element.innerHTML = event.data
      }
    </script>
  </body>
</html>
"""

    return 200, [(b'content-type', b'text/html')], text_writer(html)
Exemplo n.º 6
0
async def test_page(scope: Scope, info: Info, matches: RouteMatches,
                    content: Content) -> HttpResponse:
    """A request handler which returns an HTML document with secondary content"""

    html = """
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Example 1</title>
    <script src="/clickHandler.js"></script>
  </head>
  <body>
    <h1>Example 1</h1>
    <button type="button" onclick="handleClick('here')">
        Click me
    </button>
    <p id="here" />
    <script
  </body>
</html>

"""
    pushes = [('/clickhandler.js', [(b'accept', b'text/javascript')])]
    return 200, [(b'content-type', b'text/html')], text_writer(html), pushes
Exemplo n.º 7
0
async def get_form(
        scope: Scope,
        _info: Info,
        _matches: RouteMatches,
        _content: Content
) -> HttpResponse:
    """A response handler which returns a form and sets some cookies"""
    cookies = header.cookie(scope['headers'])

    first_name = cookies.get(b'first_name', [b'Micky'])[0]
    last_name = cookies.get(b'last_name', [b'Mouse'])[0]

    html_list = '<dl>'
    for name, values in cookies.items():
        for value in values:
            html_list += f'<dt>{name.decode()}</dt><dd>{value.decode()}</dd>'
    html_list += '</dl>'

    html = FORM_HTML.format(
        first_name=first_name.decode(),
        last_name=last_name.decode(),
        cookies=html_list
    )
    headers = [
        (b'content-type', b'text/html'),
    ]
    return 200, headers, text_writer(html)
async def get_info(scope, info, matches, content):
    accept = header.find(b'accept', scope['headers'])
    if accept != b'application/json':
        return 500
    text = json.dumps(info)
    headers = [(b'content-type', b'application/json')]
    return 200, headers, text_writer(text)
Exemplo n.º 9
0
async def http_request_callback(
        scope: Scope,
        info: Info,
        matches: RouteMatches,
        content: Content
) -> HttpResponse:
    """The final request handler"""
    return 200, [(b'content-type', b'text/plain')], text_writer(info['message'])
Exemplo n.º 10
0
async def get_form(
        scope: Scope,
        info: Info,
        matches: RouteMatches,
        content: Content
) -> HttpResponse:
    """A request handler which returns a form"""
    return 200, [(b'content-type', b'text/html')], text_writer(FORM)
Exemplo n.º 11
0
 async def get_page(self, _scope: Scope, _info: Info,
                    _matches: RouteMatches,
                    _content: Content) -> HttpResponse:
     filename = pkg_resources.resource_filename(__name__, "cpumon.html")
     with open(filename) as file_ptr:
         html = file_ptr.read()
     headers = [(b'content-type', b'text/html')]
     return 200, headers, text_writer(html)
Exemplo n.º 12
0
 async def dummy(self, scope: Scope, info: Info, matches: RouteMatches,
                 content: Content) -> HttpResponse:
     try:
         return self._authenticated_response(scope, "*****@*****.**")
     except Exception as error:
         return http_status_code.INTERNAL_SERVER_ERROR, [
             (b'content-type', b'text/plain')
         ], text_writer(str(error))
Exemplo n.º 13
0
async def http_request_callback(
        scope: Scope,
        info: Info,
        matches: RouteMatches,
        content: Content
) -> HttpResponse:
    """A request handler which returns some text"""
    return 200, [(b'content-type', b'text/plain')], text_writer('This is not a test')
async def http_request_callback(_scope: Scope, info: Info,
                                _matches: RouteMatches,
                                _content: Content) -> HttpResponse:
    """
    A Simple endpoint to demonstrate that requests can still be serviced when
    a background task is running.
    """
    headers: List[Header] = [(b'content-type', b'text/plain')]
    return 200, headers, text_writer(f"Last time tick: {info.get('now')}")
async def get_info(
        _scope: Scope,
        info: Info,
        _matches: RouteMatches,
        _content: Content
) -> HttpResponse:
    """GET handler"""
    text = json.dumps(info)
    return 200, [(b'content-type', b'application/json')], text_writer(text)
Exemplo n.º 16
0
async def get_info(scope: Scope, info: Info, _matches: RouteMatches,
                   _content: Content) -> HttpResponse:
    """Handle the GET request"""
    accept = header.find(b'accept', scope['headers'])
    if accept != b'application/json':
        return 500
    text = json.dumps(info)
    headers = [(b'content-type', b'application/json')]
    return 200, headers, text_writer(text)
Exemplo n.º 17
0
async def session_handler(request: HttpRequest) -> HttpResponse:
    session = session_data(request)
    now = session.get('now')
    message = f'The time was {now}' if now else 'First time'
    session['now'] = datetime.now()
    headers: List[Tuple[bytes, bytes]] = [(b'content-type', b'text/plain'),
                                          (b'content-length',
                                           str(len(message)).encode('ascii'))]
    return HttpResponse(200, headers, text_writer(message))
Exemplo n.º 18
0
async def http_request_callback(scope: Scope, info: Info,
                                matches: RouteMatches,
                                content: Content) -> HttpResponse:
    """
    A Simple endpoint to demonstrate that requests can still be serviced when
    a background task is running.
    """
    return 200, [(b'content-type', b'text/plain')
                 ], text_writer('This is not a test')
Exemplo n.º 19
0
async def test_asset(scope: Scope, info: Info, matches: RouteMatches,
                     content: Content) -> HttpResponse:
    """A request handler which provides an asset required by the html."""
    js_content = """
function handleClick(id) {
  document.getElementById(id).innerHTML = Date()
}
"""
    return 200, [(b'content-type', b'text/javascript')
                 ], text_writer(js_content)
Exemplo n.º 20
0
 async def register(self, scope: Scope, info: Info, matches: RouteMatches,
                    content: Content) -> HttpResponse:
     try:
         text = await text_reader(content)
         body = json.loads(text)
         await self.auth_service.register(body['email'], body['password'])
         return self._authenticated_response(scope, body['email'])
     except Exception as error:
         return http_status_code.INTERNAL_SERVER_ERROR, [
             (b'content-type', b'text/plain')
         ], text_writer(str(error))
Exemplo n.º 21
0
async def post_form(
        scope: Scope,
        info: Info,
        matches: RouteMatches,
        content: Content
) -> HttpResponse:
    """A request handler for the form POST"""
    text = await text_reader(content)
    data = urllib.parse.parse_qs(text)
    print(data)
    return 200, [(b'content-type', b'text/plain')], text_writer('This is not a test')
Exemplo n.º 22
0
async def websocket_page(scope, info, matches, content):
    scheme = 'wss' if scope['scheme'] == 'https' else 'ws'
    if scope['http_version'] in ('2', '2.0'):
        authority = header.find(b':authority',
                                scope['headers']).decode('ascii')
    else:
        host, port = scope['server']
        authority = f'{host}:{port}'
    web_socket_url = f"{scheme}://{authority}/websocket_handler"
    print(web_socket_url)

    page = info['html'].replace('WEB_SOCKET_URL', web_socket_url)
    return 200, [(b'content-type', b'text/html')], text_writer(page)
Exemplo n.º 23
0
async def get_form(
        scope: Scope,
        info: Info,
        matches: RouteMatches,
        content: Content
) -> HttpResponse:
    """A response handler which returns a form and sets some cookies"""
    headers = [
        (b'content-type', b'text/html'),
        (b'set-cookie', b'first=first cookie'),
        (b'set-cookie', b'second=second cookie'),
    ]
    return 200, headers, text_writer(FORM)
Exemplo n.º 24
0
async def post_form(
        scope: Scope,
        info: Info,
        matches: RouteMatches,
        content: Content
) -> HttpResponse:
    """A response handler that reads the cookies from a posted form."""
    cookies = header.cookie(scope['headers'])
    html_list = '<dl>'
    for name, values in cookies.items():
        for value in values:
            html_list += f'<dt>{name.decode()}</dt><dd>{value.decode()}</dd>'
    html_list += '</dl>'
    return 200, [(b'content-type', b'text/html')], text_writer(COOKIES.format(cookies=html_list))
Exemplo n.º 25
0
async def index(scope: Scope, info: Info, matches: RouteMatches,
                content: Content) -> HttpResponse:
    """A request handler which provides an index of the compression methods"""
    html = """
<!DOCTYPE html>
<html>
  <body>
    <ul>
      <li><a href='/gzip'>gzip</a></li>
      <li><a href='/deflate'>deflate</a></li>
      <li><a href='/compress'>compress</a></li>
    </ul>
  </body>
</html>
"""
    return 200, [(b'content-type', b'text/html')], text_writer(html)
async def test_page(_scope: Scope, _info: Info, _matches: RouteMatches,
                    _content: Content) -> HttpResponse:
    """A request handler which returns some html"""
    html = """
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Hypercorn http</title>
  </head>
  <body>
    <h1>Hypercorn https</h1>
    
    <p>I'm secure<p>
  </body>
</html>
"""
    return 200, [(b'content-type', b'text/html')], text_writer(html)
Exemplo n.º 27
0
async def test_page2(_scope: Scope, _info: Info, _matches: RouteMatches,
                     _content: Content) -> HttpResponse:
    """A request handler which returns HTML"""
    html = """
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Example 2</title>
  </head>
  <body>
    <h1>Example 2</h1>

    <p>This is simple<p>
  </body>
</html>
"""
    return 200, [(b'content-type', b'text/html')], text_writer(html)
Exemplo n.º 28
0
    async def __call__(self, scope: Scope, info: Info, matches: RouteMatches,
                       content: Content,
                       handler: HttpRequestCallback) -> HttpResponse:

        logger.debug(f'Jwt Authentication Request: {scope["path"]}')

        try:
            payload = self.token_manager.get_jwt_payload_from_headers(
                scope['headers'])
            if payload is None:
                return http_status.UNAUTHORIZED, None, None

            now = datetime.utcnow()

            if payload['exp'] > now:
                logger.debug('Cookie still valid')
                cookie = None
            else:
                logger.debug('Renewing cookie')
                if not self.auth_service.user_valid(payload['sub']):
                    return http_status.FORBIDDEN, [
                        (b'content-type', b'text/plain')
                    ], text_writer("Invalid user")
                token = self.token_manager.encode(payload['sub'], now,
                                                  payload['iat'])
                cookie = self.token_manager.make_cookie(token)

            if info:
                info['jwt'] = payload
            else:
                info = {'jwt': payload}

            next_status, next_headers, next_content = await handler(
                scope, info, matches, content)

            if cookie:
                if next_headers is None:
                    next_headers = []
                next_headers.append((b"set-cookie", cookie))

            return next_status, next_headers, next_content
        except:
            logger.exception("JWT authentication failed")
            return http_status.INTERNAL_SERVER_ERROR, None, None
Exemplo n.º 29
0
async def get_form(scope, info, matches, content):
    cookies = header.cookie(scope['headers'])

    first_name = cookies.get(b'first_name', [b'Micky'])[0]
    last_name = cookies.get(b'last_name', [b'Mouse'])[0]

    html_list = '<dl>'
    for name, values in cookies.items():
        for value in values:
            html_list += f'<dt>{name.decode()}</dt><dd>{value.decode()}</dd>'
    html_list += '</dl>'

    html = FORM_HTML.format(first_name=first_name.decode(),
                            last_name=last_name.decode(),
                            cookies=html_list)
    headers = [
        (b'content-type', b'text/html'),
    ]
    return 200, headers, text_writer(html)
Exemplo n.º 30
0
async def index_handler(
        _scope: Scope,
        _info: Info,
        _matches: RouteMatches,
        _content: Content
) -> HttpResponse:
    """The index page"""
    html = """
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Raising Exceptions</title>
  </head>
  <body>
    <h1>Raising Exceptions</h1>
    
    <ul>
        <li><a href="/raise_none_exception">
            Raise a 401 exception with no content
        </li>
        <li><a href="/raise_text_exception">
            Raise a 401 exception with text content
        </li>
        <li><a href="/raise_bytes_exception">
            Raise a 401 exception with bytes content
        </li>
        <li><a href="/raise_writer_exception">
            Raise a 401 exception with a writer providing content
        </li>
    </ul>
  </body>
</html>
"""
    headers: List[Headers] = [
        (b'content-type', b'text/html')
    ]
    return 200, headers, text_writer(html)