Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add on_open option in WebSocketWSGI #253

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Add on_open option in WebSocketWSGI #253

wants to merge 2 commits into from

Conversation

fukuchidaisuke
Copy link

This pull request adds flexibility on accepting websocket connections as follows.

import base64
import eventlet
from eventlet import wsgi, websocket
import six
import time


def handle(ws):
    while True:
        message = ws.wait()
        if message is None:
            break
        print("received {0}".format(message))
        ws.send(message)


def on_open(environ):
    if "HTTP_COOKIE" in environ:
        cookie = six.moves.http_cookies.SimpleCookie()
        cookie.load(environ["HTTP_COOKIE"])
        if ("SID" in cookie) and cookie["SID"].value == "validSession":
            return []

    print("not authenticated")

    if "QUERY_STRING" not in environ:
        raise websocket.BadRequest(status="403 Forbidden")

    queries = six.moves.urllib.parse.parse_qs(environ["QUERY_STRING"])
    if "authorization_basic" not in queries:
        raise websocket.BadRequest(status="403 Forbidden")

    if queries["authorization_basic"][0] != base64.b64encode("username:password".encode()).decode():
        raise websocket.BadRequest(status="403 Forbidden")

    expires = time.strftime("%a, %d-%b-%Y %T GMT", time.gmtime(time.time() + 3600))
    return [("Set-Cookie", "SID=validSession; Path=/; Expires={0}".format(expires))]


if __name__ == "__main__":
    wsgi.server(eventlet.listen(("", 8080)), websocket.WebSocketWSGI(handle, on_open=on_open))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants