1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
|
#!/usr/bin/env python
import asyncio
import http
import http.cookies
import pathlib
import signal
import urllib.parse
import uuid
import websockets
from websockets.frames import CloseCode
# User accounts database
USERS = {}
def create_token(user, lifetime=1):
"""Create token for user and delete it once its lifetime is over."""
token = uuid.uuid4().hex
USERS[token] = user
asyncio.get_running_loop().call_later(lifetime, USERS.pop, token)
return token
def get_user(token):
"""Find user authenticated by token or return None."""
return USERS.get(token)
# Utilities
def get_cookie(raw, key):
cookie = http.cookies.SimpleCookie(raw)
morsel = cookie.get(key)
if morsel is not None:
return morsel.value
def get_query_param(path, key):
query = urllib.parse.urlparse(path).query
params = urllib.parse.parse_qs(query)
values = params.get(key, [])
if len(values) == 1:
return values[0]
# Main HTTP server
CONTENT_TYPES = {
".css": "text/css",
".html": "text/html; charset=utf-8",
".ico": "image/x-icon",
".js": "text/javascript",
}
async def serve_html(path, request_headers):
user = get_query_param(path, "user")
path = urllib.parse.urlparse(path).path
if path == "/":
if user is None:
page = "index.html"
else:
page = "test.html"
else:
page = path[1:]
try:
template = pathlib.Path(__file__).with_name(page)
except ValueError:
pass
else:
if template.is_file():
headers = {"Content-Type": CONTENT_TYPES[template.suffix]}
body = template.read_bytes()
if user is not None:
token = create_token(user)
body = body.replace(b"TOKEN", token.encode())
return http.HTTPStatus.OK, headers, body
return http.HTTPStatus.NOT_FOUND, {}, b"Not found\n"
async def noop_handler(websocket):
pass
# Send credentials as the first message in the WebSocket connection
async def first_message_handler(websocket):
token = await websocket.recv()
user = get_user(token)
if user is None:
await websocket.close(CloseCode.INTERNAL_ERROR, "authentication failed")
return
await websocket.send(f"Hello {user}!")
message = await websocket.recv()
assert message == f"Goodbye {user}."
# Add credentials to the WebSocket URI in a query parameter
class QueryParamProtocol(websockets.WebSocketServerProtocol):
async def process_request(self, path, headers):
token = get_query_param(path, "token")
if token is None:
return http.HTTPStatus.UNAUTHORIZED, [], b"Missing token\n"
user = get_user(token)
if user is None:
return http.HTTPStatus.UNAUTHORIZED, [], b"Invalid token\n"
self.user = user
async def query_param_handler(websocket):
user = websocket.user
await websocket.send(f"Hello {user}!")
message = await websocket.recv()
assert message == f"Goodbye {user}."
# Set a cookie on the domain of the WebSocket URI
class CookieProtocol(websockets.WebSocketServerProtocol):
async def process_request(self, path, headers):
if "Upgrade" not in headers:
template = pathlib.Path(__file__).with_name(path[1:])
headers = {"Content-Type": CONTENT_TYPES[template.suffix]}
body = template.read_bytes()
return http.HTTPStatus.OK, headers, body
token = get_cookie(headers.get("Cookie", ""), "token")
if token is None:
return http.HTTPStatus.UNAUTHORIZED, [], b"Missing token\n"
user = get_user(token)
if user is None:
return http.HTTPStatus.UNAUTHORIZED, [], b"Invalid token\n"
self.user = user
async def cookie_handler(websocket):
user = websocket.user
await websocket.send(f"Hello {user}!")
message = await websocket.recv()
assert message == f"Goodbye {user}."
# Adding credentials to the WebSocket URI in user information
class UserInfoProtocol(websockets.BasicAuthWebSocketServerProtocol):
async def check_credentials(self, username, password):
if username != "token":
return False
user = get_user(password)
if user is None:
return False
self.user = user
return True
async def user_info_handler(websocket):
user = websocket.user
await websocket.send(f"Hello {user}!")
message = await websocket.recv()
assert message == f"Goodbye {user}."
# Start all five servers
async def main():
# Set the stop condition when receiving SIGINT or SIGTERM.
loop = asyncio.get_running_loop()
stop = loop.create_future()
loop.add_signal_handler(signal.SIGINT, stop.set_result, None)
loop.add_signal_handler(signal.SIGTERM, stop.set_result, None)
async with websockets.serve(
noop_handler,
host="",
port=8000,
process_request=serve_html,
), websockets.serve(
first_message_handler,
host="",
port=8001,
), websockets.serve(
query_param_handler,
host="",
port=8002,
create_protocol=QueryParamProtocol,
), websockets.serve(
cookie_handler,
host="",
port=8003,
create_protocol=CookieProtocol,
), websockets.serve(
user_info_handler,
host="",
port=8004,
create_protocol=UserInfoProtocol,
):
print("Running on http://localhost:8000/")
await stop
print("\rExiting")
if __name__ == "__main__":
asyncio.run(main())
|