moonlette 0.0.2__tar.gz → 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of moonlette might be problematic. Click here for more details.
- {moonlette-0.0.2/src/moonlette.egg-info → moonlette-0.2.0}/PKG-INFO +37 -8
- moonlette-0.2.0/README.md +57 -0
- {moonlette-0.0.2 → moonlette-0.2.0}/pyproject.toml +2 -0
- moonlette-0.2.0/src/moonlette/__init__.py +1 -0
- moonlette-0.2.0/src/moonlette/auth_server.py +367 -0
- moonlette-0.2.0/src/moonlette/http_request_context.py +29 -0
- moonlette-0.2.0/src/moonlette/interfaces/__init__.py +0 -0
- moonlette-0.2.0/src/moonlette/interfaces/ws_session.py +36 -0
- {moonlette-0.0.2 → moonlette-0.2.0}/src/moonlette/server.py +147 -83
- moonlette-0.2.0/src/moonlette/static/auth_status.js +60 -0
- moonlette-0.2.0/src/moonlette/static/forbidden.html +12 -0
- moonlette-0.2.0/src/moonlette/static/login.html +34 -0
- moonlette-0.2.0/src/moonlette/static/profile.html +33 -0
- moonlette-0.2.0/src/moonlette/static/style.css +17 -0
- moonlette-0.2.0/src/moonlette/user.py +41 -0
- moonlette-0.2.0/src/moonlette/user_db.py +123 -0
- moonlette-0.2.0/src/moonlette/ws_request_context.py +29 -0
- {moonlette-0.0.2 → moonlette-0.2.0/src/moonlette.egg-info}/PKG-INFO +37 -8
- moonlette-0.2.0/src/moonlette.egg-info/SOURCES.txt +22 -0
- {moonlette-0.0.2 → moonlette-0.2.0}/src/moonlette.egg-info/requires.txt +3 -0
- moonlette-0.0.2/README.md +0 -30
- moonlette-0.0.2/src/moonlette/__init__.py +0 -1
- moonlette-0.0.2/src/moonlette.egg-info/SOURCES.txt +0 -10
- {moonlette-0.0.2 → moonlette-0.2.0}/LICENSE +0 -0
- {moonlette-0.0.2 → moonlette-0.2.0}/setup.cfg +0 -0
- {moonlette-0.0.2 → moonlette-0.2.0}/src/moonlette.egg-info/dependency_links.txt +0 -0
- {moonlette-0.0.2 → moonlette-0.2.0}/src/moonlette.egg-info/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: moonlette
|
|
3
|
-
Version: 0.0
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: A simple web server with websocket support based on starlette and uvicorn
|
|
5
5
|
Author-email: Visual Topology <dev@visualtopology.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -20,11 +20,17 @@ License-File: LICENSE
|
|
|
20
20
|
Requires-Dist: starlette[full]
|
|
21
21
|
Requires-Dist: uvicorn[standard]
|
|
22
22
|
Requires-Dist: requests
|
|
23
|
+
Provides-Extra: auth
|
|
24
|
+
Requires-Dist: authlib; extra == "auth"
|
|
23
25
|
Dynamic: license-file
|
|
24
26
|
|
|
27
|
+
from moonlette.ws_request_context import WSRequestContext
|
|
28
|
+
|
|
25
29
|
# moonlette
|
|
26
30
|
|
|
27
|
-
A simple web server with websockets support based on starlette, uvicorn and authlib.
|
|
31
|
+
A simple web server with websockets support based on starlette, anyio, uvicorn and authlib.
|
|
32
|
+
|
|
33
|
+
HTTP requests are handled synchronously in threads. Websockets are handled asynchronously.
|
|
28
34
|
|
|
29
35
|
## Installation
|
|
30
36
|
|
|
@@ -34,20 +40,43 @@ pip install moonlette
|
|
|
34
40
|
|
|
35
41
|
## Example usage (http)
|
|
36
42
|
|
|
37
|
-
```
|
|
38
|
-
from
|
|
43
|
+
```python
|
|
44
|
+
from webserver.http_request_context import HTTPRequestContext
|
|
45
|
+
from webserver.server import Server
|
|
46
|
+
|
|
39
47
|
server = Server(port=8081, host="localhost")
|
|
40
|
-
|
|
41
|
-
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def handler(request_context: HTTPRequestContext):
|
|
42
51
|
return (200, b"It Worked!", "text/plain", {})
|
|
43
52
|
|
|
53
|
+
|
|
44
54
|
server.attach_handler("GET", "/test", handler)
|
|
45
55
|
server.run()
|
|
46
56
|
```
|
|
47
57
|
|
|
48
|
-
## Example usage (
|
|
58
|
+
## Example usage (websockets)
|
|
49
59
|
|
|
50
|
-
|
|
60
|
+
```python
|
|
61
|
+
from webserver.server import Server
|
|
62
|
+
from webserver.ws_request_context import WSRequestContext
|
|
63
|
+
|
|
64
|
+
server = Server(port=8081, host="localhost")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class EchoHandler:
|
|
68
|
+
|
|
69
|
+
def __init__(self, ctx: WSRequestContext):
|
|
70
|
+
self.ctx = ctx
|
|
71
|
+
|
|
72
|
+
async def recv(self, msg):
|
|
73
|
+
# echo the message back
|
|
74
|
+
self.ctx.sender(msg)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
server.attach_ws_handler("/echo", EchoHandler)
|
|
78
|
+
server.run()
|
|
79
|
+
```
|
|
51
80
|
|
|
52
81
|
## Documentation
|
|
53
82
|
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
from moonlette.ws_request_context import WSRequestContext
|
|
2
|
+
|
|
3
|
+
# moonlette
|
|
4
|
+
|
|
5
|
+
A simple web server with websockets support based on starlette, anyio, uvicorn and authlib.
|
|
6
|
+
|
|
7
|
+
HTTP requests are handled synchronously in threads. Websockets are handled asynchronously.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
pip install moonlette
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Example usage (http)
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from webserver.http_request_context import HTTPRequestContext
|
|
19
|
+
from webserver.server import Server
|
|
20
|
+
|
|
21
|
+
server = Server(port=8081, host="localhost")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def handler(request_context: HTTPRequestContext):
|
|
25
|
+
return (200, b"It Worked!", "text/plain", {})
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
server.attach_handler("GET", "/test", handler)
|
|
29
|
+
server.run()
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Example usage (websockets)
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from webserver.server import Server
|
|
36
|
+
from webserver.ws_request_context import WSRequestContext
|
|
37
|
+
|
|
38
|
+
server = Server(port=8081, host="localhost")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class EchoHandler:
|
|
42
|
+
|
|
43
|
+
def __init__(self, ctx: WSRequestContext):
|
|
44
|
+
self.ctx = ctx
|
|
45
|
+
|
|
46
|
+
async def recv(self, msg):
|
|
47
|
+
# echo the message back
|
|
48
|
+
self.ctx.sender(msg)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
server.attach_ws_handler("/echo", EchoHandler)
|
|
52
|
+
server.run()
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Documentation
|
|
56
|
+
|
|
57
|
+
Coming Soon
|
|
@@ -35,6 +35,8 @@ where = ["src"]
|
|
|
35
35
|
|
|
36
36
|
[project.optional-dependencies]
|
|
37
37
|
|
|
38
|
+
AUTH = ["authlib"]
|
|
39
|
+
|
|
38
40
|
[tool.setuptools.package-data]
|
|
39
41
|
moonlette = ["**/*.json", "**/*.zip", "**/*.html", "**/*.js", "**/*.svg", "**/*.png", "**/.txt", "**/*.woff2", "**/*.yaml", "**/*.toml", "**/*.css"]
|
|
40
42
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.0"
|
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
# Moonlette - a simple web server
|
|
2
|
+
#
|
|
3
|
+
# MIT License - Copyright (C) 2026 Visual Topology Ltd
|
|
4
|
+
#
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
|
|
6
|
+
# and associated documentation files (the "Software"), to deal in the Software without
|
|
7
|
+
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
|
|
8
|
+
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
|
|
9
|
+
# Software is furnished to do so, subject to the following conditions:
|
|
10
|
+
#
|
|
11
|
+
# The above copyright notice and this permission notice shall be included in all copies or
|
|
12
|
+
# substantial portions of the Software.
|
|
13
|
+
#
|
|
14
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
|
|
15
|
+
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
16
|
+
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
|
17
|
+
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
import os
|
|
22
|
+
from typing import Type, Callable, Any
|
|
23
|
+
from importlib.resources import files
|
|
24
|
+
|
|
25
|
+
from starlette.requests import Request
|
|
26
|
+
from starlette.responses import RedirectResponse, HTMLResponse, Response, JSONResponse
|
|
27
|
+
from starlette.websockets import WebSocket
|
|
28
|
+
from starlette.middleware.sessions import SessionMiddleware
|
|
29
|
+
|
|
30
|
+
from authlib.integrations.starlette_client import OAuth
|
|
31
|
+
|
|
32
|
+
from .server import Server
|
|
33
|
+
from .user import User
|
|
34
|
+
from .user_db import UserDB
|
|
35
|
+
|
|
36
|
+
from .http_request_context import HTTPRequestContext
|
|
37
|
+
|
|
38
|
+
from typing import TypeAlias
|
|
39
|
+
|
|
40
|
+
from .ws_request_context import WSRequestContext
|
|
41
|
+
from moonlette.interfaces.ws_session import WSSession
|
|
42
|
+
|
|
43
|
+
HTTPRequestHandler:TypeAlias = Callable[[HTTPRequestContext],tuple[int,bytes,str,dict[str,str]]]
|
|
44
|
+
WSHandler:TypeAlias = Callable[[WSRequestContext],WSSession]
|
|
45
|
+
|
|
46
|
+
class AuthServer(Server):
|
|
47
|
+
|
|
48
|
+
def __init__(self,
|
|
49
|
+
host: str = "localhost",
|
|
50
|
+
port: int = 8889,
|
|
51
|
+
startup_timeout_s: int = 5,
|
|
52
|
+
log_level: str = "info",
|
|
53
|
+
secret_key:str = None,
|
|
54
|
+
user_db:UserDB = None,
|
|
55
|
+
auth_provider_config_path: str = None,
|
|
56
|
+
auth_path = "/moonlette_auth",
|
|
57
|
+
auth_path_external = None,
|
|
58
|
+
auth_folder=None):
|
|
59
|
+
|
|
60
|
+
super().__init__(host=host, port=port, startup_timeout_s=startup_timeout_s, log_level=log_level)
|
|
61
|
+
if secret_key is None:
|
|
62
|
+
raise Exception("Please specify a value for parameter secret_key")
|
|
63
|
+
self.secret_key = secret_key
|
|
64
|
+
self.auth_config = {}
|
|
65
|
+
self.user_db = user_db
|
|
66
|
+
self.unauthorised_http_handlers = []
|
|
67
|
+
self.oauth = OAuth()
|
|
68
|
+
self.auth_path = auth_path
|
|
69
|
+
self.auth_path_external = auth_path_external if auth_path_external is not None else auth_path
|
|
70
|
+
|
|
71
|
+
if auth_folder is None:
|
|
72
|
+
auth_folder = self.__get_path_of_resource("moonlette","static")
|
|
73
|
+
self.auth_folder = auth_folder
|
|
74
|
+
|
|
75
|
+
self.login_urls = (self.auth_path+"/login.html", self.auth_path_external+"/login.html")
|
|
76
|
+
self.login_provider_folder = (self.auth_path + "/login_provider", self.auth_path_external + "/login_provider")
|
|
77
|
+
self.logout_urls = (self.auth_path+"/logout.html", self.auth_path_external+"/logout.html")
|
|
78
|
+
self.profile_urls = (self.auth_path+"/profile.html", self.auth_path_external+"/profile.html")
|
|
79
|
+
self.auth_urls = (self.auth_path+"/authorised", self.auth_path_external+"/auth")
|
|
80
|
+
self.auth_status_urls = (self.auth_path+"/auth_status.json", self.auth_path_external+"/auth_status.json")
|
|
81
|
+
|
|
82
|
+
if auth_provider_config_path is not None:
|
|
83
|
+
self.__load_providers(auth_provider_config_path)
|
|
84
|
+
|
|
85
|
+
self.attach_unauthorised_webroot(self.auth_path, self.auth_folder)
|
|
86
|
+
|
|
87
|
+
def __get_path_of_resource(self, package, resource=""):
|
|
88
|
+
return str(files(package).joinpath(resource))
|
|
89
|
+
|
|
90
|
+
def __add_oidc_provider(self, provider_id, label, configuration, token_settings, **kwargs):
|
|
91
|
+
self.auth_config[provider_id] = {
|
|
92
|
+
"label": label,
|
|
93
|
+
"provider_type": "oidc",
|
|
94
|
+
"configuration": configuration,
|
|
95
|
+
"token_settings": token_settings
|
|
96
|
+
}
|
|
97
|
+
self.oauth.register(name=provider_id, **configuration)
|
|
98
|
+
|
|
99
|
+
def __add_dummy_provider(self, provider_id, label, user_id, user_name, user_email):
|
|
100
|
+
self.auth_config[provider_id] = {
|
|
101
|
+
"label": label,
|
|
102
|
+
"provider_type": "dummy",
|
|
103
|
+
"configuration": {
|
|
104
|
+
"user_id": user_id,
|
|
105
|
+
"user_name": user_name,
|
|
106
|
+
"user_email": user_email
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
def __load_providers(self, auth_provider_config_path:str):
|
|
111
|
+
import tomllib
|
|
112
|
+
import re
|
|
113
|
+
env_pattern = re.compile(r"\${(\w+)}")
|
|
114
|
+
|
|
115
|
+
def sub_env_vars(o):
|
|
116
|
+
if isinstance(o, dict):
|
|
117
|
+
for key, value in o.items():
|
|
118
|
+
o[key] = sub_env_vars(value)
|
|
119
|
+
elif isinstance(o, list):
|
|
120
|
+
for idx in range(len(o)):
|
|
121
|
+
o[idx] = sub_env_vars(o[idx])
|
|
122
|
+
elif isinstance(o, str):
|
|
123
|
+
o = re.sub(env_pattern, lambda m: os.getenv(m.group(1)), o)
|
|
124
|
+
return o
|
|
125
|
+
|
|
126
|
+
with open(auth_provider_config_path, "r") as f:
|
|
127
|
+
auth_provider_config = tomllib.loads(f.read())
|
|
128
|
+
|
|
129
|
+
auth_provider_config = sub_env_vars(auth_provider_config)
|
|
130
|
+
for provider_id in auth_provider_config:
|
|
131
|
+
|
|
132
|
+
provider = auth_provider_config[provider_id]
|
|
133
|
+
provider_type = provider["provider_type"]
|
|
134
|
+
label = provider["label"]
|
|
135
|
+
if provider_type == "dummy":
|
|
136
|
+
self.__add_dummy_provider(provider_id, label, provider["user_id"], provider["user_name"],
|
|
137
|
+
provider["user_email"])
|
|
138
|
+
elif provider_type == "oidc":
|
|
139
|
+
oidc_configuration = {}
|
|
140
|
+
for key in provider:
|
|
141
|
+
if key not in ["provider_type", "label", "token_settings"]:
|
|
142
|
+
oidc_configuration[key] = provider[key]
|
|
143
|
+
self.__add_oidc_provider(provider_id, label, configuration=oidc_configuration,
|
|
144
|
+
token_settings=provider["token_settings"])
|
|
145
|
+
|
|
146
|
+
def register_middleware(self, app):
|
|
147
|
+
app.add_middleware(SessionMiddleware, secret_key=self.secret_key)
|
|
148
|
+
super().register_middleware(app)
|
|
149
|
+
|
|
150
|
+
def attach_http_handler(self, method:str, path:str, handler:HTTPRequestHandler, required_roles:list[str]|None=None):
|
|
151
|
+
"""
|
|
152
|
+
Attach an authorised HTTP handler
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
method: the HTTP method, for example GET, POST, ...
|
|
156
|
+
path: the path to listen at
|
|
157
|
+
handler: a function which receives an HTTPRequestContext and returns an HTTP response in the form (response-code,response-bytes,mime-type,response-custom-headers)
|
|
158
|
+
required_roles: optional list of roles to which an authenticated user should belong to access this resource
|
|
159
|
+
"""
|
|
160
|
+
def checked_handler(request_context:HTTPRequestContext) -> tuple[int,bytes,str,dict[str,str]]:
|
|
161
|
+
user_roles = request_context.user.get_roles()
|
|
162
|
+
if required_roles:
|
|
163
|
+
for (role,group) in required_roles:
|
|
164
|
+
if (role,group) not in user_roles:
|
|
165
|
+
suffix = os.path.splitext(path)[1]
|
|
166
|
+
if suffix == "" or suffix == ".html":
|
|
167
|
+
return self.serve_file(os.path.join(self.auth_folder, "forbidden.html"))
|
|
168
|
+
else:
|
|
169
|
+
return (403, b"FORBIDDEN", "text/plain", {})
|
|
170
|
+
return handler(request_context)
|
|
171
|
+
super().attach_http_handler(method, path, checked_handler)
|
|
172
|
+
|
|
173
|
+
def attach_webroot(self, path_prefix:str, static_folder:str, required_roles:list[str]|None=None) -> None:
|
|
174
|
+
"""
|
|
175
|
+
Attach a web root
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
path_prefix: the path to match
|
|
179
|
+
static_folder: the directory to serve matching sub-paths from
|
|
180
|
+
required_roles: optional list of roles to which the authenticated user should belong
|
|
181
|
+
"""
|
|
182
|
+
def serve_static(request_context):
|
|
183
|
+
filepath = os.path.join(static_folder,request_context.path_parameters["path"])
|
|
184
|
+
return self.serve_file(filepath)
|
|
185
|
+
self.attach_http_handler("GET", path_prefix + "/$$path", serve_static, required_roles=required_roles)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def attach_ws_handler(self, path:str, handler:WSHandler, required_roles:list[str]|None=None):
|
|
189
|
+
"""
|
|
190
|
+
Attach an authorised Websocket handler
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
path: the path to connect a websocket
|
|
194
|
+
handler: a function which receives a WSRequestContext and returns an object sub-classing WSSession to handle websocket messages
|
|
195
|
+
required_roles: optional list of roles to which the authenticated user should belong
|
|
196
|
+
"""
|
|
197
|
+
def checked_handler(request_context:WSRequestContext) -> WSSession:
|
|
198
|
+
user_roles = request_context.user.get_roles()
|
|
199
|
+
if required_roles:
|
|
200
|
+
for (role,group) in required_roles:
|
|
201
|
+
if role not in user_roles:
|
|
202
|
+
return (403, b"FORBIDDEN", "text/plain", {})
|
|
203
|
+
return handler(request_context)
|
|
204
|
+
super().attach_ws_handler(path, checked_handler)
|
|
205
|
+
|
|
206
|
+
def attach_unauthorised_http_handler(self, method:str, path:str, handler:HTTPRequestHandler) -> None:#
|
|
207
|
+
"""
|
|
208
|
+
Attach an unauthorised HTTP handler
|
|
209
|
+
|
|
210
|
+
Args:
|
|
211
|
+
method: the HTTP method, for example GET, POST, ...
|
|
212
|
+
path: the path to listen at
|
|
213
|
+
handler: a function which recieves an HTTPRequestContext and returns an HTTP response in the form (response-code,response-bytes,mime-type,response-custom-headers)
|
|
214
|
+
"""
|
|
215
|
+
t = (method, path, handler)
|
|
216
|
+
self.unauthorised_http_handlers.append(t)
|
|
217
|
+
|
|
218
|
+
def attach_unauthorised_webroot(self, path_prefix:str, static_folder:str) -> None:
|
|
219
|
+
"""
|
|
220
|
+
Attach an unauthorised web root
|
|
221
|
+
|
|
222
|
+
Args:
|
|
223
|
+
path_prefix: the path to match
|
|
224
|
+
static_folder: the directory to serve matching sub-paths from
|
|
225
|
+
"""
|
|
226
|
+
def serve_static(request_context):
|
|
227
|
+
filepath = os.path.join(static_folder,request_context.path_parameters["path"])
|
|
228
|
+
return self.serve_file(filepath)
|
|
229
|
+
self.attach_unauthorised_http_handler("GET", path_prefix + "/$$path", serve_static)
|
|
230
|
+
|
|
231
|
+
async def _http_endpoint(self, request:Request, user:User|None=None):
|
|
232
|
+
|
|
233
|
+
path = "/" + request.path_params["path"]
|
|
234
|
+
|
|
235
|
+
if path == self.auth_status_urls[0]:
|
|
236
|
+
return JSONResponse(self.__get_auth_status(request), status_code=200)
|
|
237
|
+
|
|
238
|
+
if path == "/.well-known/appspecific/com.chrome.devtools.json":
|
|
239
|
+
return HTMLResponse(b"Not Found", 404)
|
|
240
|
+
|
|
241
|
+
print("***:"+path)
|
|
242
|
+
|
|
243
|
+
if path == self.login_urls[0]:
|
|
244
|
+
(status, content, mimetype, headers) = self.serve_file(os.path.join(self.auth_folder,"login.html"))
|
|
245
|
+
return HTMLResponse(content, status_code=status, headers=headers, media_type=mimetype)
|
|
246
|
+
|
|
247
|
+
elif path.startswith(self.login_provider_folder[0]):
|
|
248
|
+
provider_id = path.split("/")[-1]
|
|
249
|
+
provider_config = self.auth_config[provider_id]["configuration"]
|
|
250
|
+
provider_type = self.auth_config[provider_id]["provider_type"]
|
|
251
|
+
request.session['auth.provider_id'] = provider_id
|
|
252
|
+
if provider_type == "oidc":
|
|
253
|
+
redirect_url = provider_config["redirect_url"]
|
|
254
|
+
return await getattr(self.oauth, provider_id).authorize_redirect(request, redirect_url)
|
|
255
|
+
elif provider_type == "dummy":
|
|
256
|
+
request.session['user_id'] = provider_config["user_id"]
|
|
257
|
+
request.session['user_email'] = provider_config["user_email"]
|
|
258
|
+
request.session['user_name'] = provider_config["user_name"]
|
|
259
|
+
return RedirectResponse(url=request.session.pop("target_path","/"))
|
|
260
|
+
else:
|
|
261
|
+
return HTMLResponse(b"Internal Error", status_code=500)
|
|
262
|
+
|
|
263
|
+
elif path == self.auth_urls[0]:
|
|
264
|
+
provider_id = request.session['auth.provider_id']
|
|
265
|
+
provider = self.auth_config[provider_id]
|
|
266
|
+
provider_type = provider["provider_type"]
|
|
267
|
+
if provider_type == "oidc":
|
|
268
|
+
oauth = getattr(self.oauth,provider_id)
|
|
269
|
+
token = await oauth.authorize_access_token(request)
|
|
270
|
+
token_settings = provider["token_settings"]
|
|
271
|
+
user = token.get('userinfo')
|
|
272
|
+
if user:
|
|
273
|
+
# parse the token
|
|
274
|
+
for setting, key in token_settings.items():
|
|
275
|
+
if isinstance(key, str):
|
|
276
|
+
value = user.get(key)
|
|
277
|
+
if value is None:
|
|
278
|
+
return HTMLResponse(b"Internal Error", status_code=500)
|
|
279
|
+
else:
|
|
280
|
+
values = []
|
|
281
|
+
for subkey in key:
|
|
282
|
+
value = user.get(subkey)
|
|
283
|
+
if value is None:
|
|
284
|
+
return HTMLResponse(b"Internal Error", status_code=500)
|
|
285
|
+
values.append(value)
|
|
286
|
+
value = " ".join(values)
|
|
287
|
+
request.session[setting] = value
|
|
288
|
+
return RedirectResponse(url=request.session.pop("target_path","/index.html"))
|
|
289
|
+
else:
|
|
290
|
+
return HTMLResponse(b"Internal Error", status_code=500)
|
|
291
|
+
else:
|
|
292
|
+
return RedirectResponse(url=self.login_urls[1])
|
|
293
|
+
|
|
294
|
+
elif path == self.logout_urls[0]:
|
|
295
|
+
request.session.pop('auth.provider_id', None)
|
|
296
|
+
request.session.pop('user_id', None)
|
|
297
|
+
request.session.pop('user_email', None)
|
|
298
|
+
request.session.pop('user_name', None)
|
|
299
|
+
return RedirectResponse(url=self.login_urls[1])
|
|
300
|
+
|
|
301
|
+
# if the request can be served without authentication, do so
|
|
302
|
+
r = await super()._http_endpoint(request, user, handlers=self.unauthorised_http_handlers)
|
|
303
|
+
if r.status_code != 404:
|
|
304
|
+
return r
|
|
305
|
+
|
|
306
|
+
user_id = request.session.get('user_id')
|
|
307
|
+
|
|
308
|
+
if user_id and path == self.profile_urls[0]:
|
|
309
|
+
(status, content, mimetype, headers) = self.serve_file(os.path.join(self.auth_folder, "profile.html"))
|
|
310
|
+
return HTMLResponse(content, status_code=status, headers=headers, media_type=mimetype)
|
|
311
|
+
|
|
312
|
+
if not user_id:
|
|
313
|
+
request.session["target_path"] = path
|
|
314
|
+
return RedirectResponse(url=self.login_urls[1])
|
|
315
|
+
|
|
316
|
+
user_name = request.session.get('user_name', "")
|
|
317
|
+
user_email = request.session.get('user_email', "")
|
|
318
|
+
|
|
319
|
+
roles = self.user_db.get_roles_for_user(user_id)
|
|
320
|
+
|
|
321
|
+
user = User(user_id, user_name, user_email, [(role,group) for (user_id, role, group) in roles], {})
|
|
322
|
+
|
|
323
|
+
return await super()._http_endpoint(request, user)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
async def _websocket_endpoint(self, websocket: WebSocket):
|
|
327
|
+
|
|
328
|
+
user_id = websocket.session.get('user_id')
|
|
329
|
+
if not user_id:
|
|
330
|
+
await websocket.send_denial_response(Response(401, b"UNAUTHORIZED", "text/plain", {}))
|
|
331
|
+
return
|
|
332
|
+
|
|
333
|
+
user_name = websocket.session.get('user_name', "")
|
|
334
|
+
user_email = websocket.session.get('user_email', "")
|
|
335
|
+
roles = self.user_db.get_roles_for_user(user_id)
|
|
336
|
+
user = User(user_id, user_name, user_email, roles, {})
|
|
337
|
+
|
|
338
|
+
return await super()._websocket_endpoint(websocket, user)
|
|
339
|
+
|
|
340
|
+
def __get_auth_status(self, request:Request) -> dict[str,Any]:
|
|
341
|
+
user_id = request.session.get('user_id', "")
|
|
342
|
+
user_name = request.session.get('user_name', "")
|
|
343
|
+
user_email = request.session.get('user_email', "")
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
auth_providers = {}
|
|
347
|
+
for provider_id in self.auth_config:
|
|
348
|
+
auth_providers[provider_id] = {
|
|
349
|
+
"label": self.auth_config[provider_id]["label"],
|
|
350
|
+
"link": self.login_provider_folder[1]+"/"+provider_id
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
return {
|
|
354
|
+
"auth_status": "authenticated" if user_id else "not authenticated",
|
|
355
|
+
"user_id": user_id,
|
|
356
|
+
"user_name": user_name,
|
|
357
|
+
"user_email": user_email,
|
|
358
|
+
"auth_providers": auth_providers
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Moonlette - a simple web server
|
|
2
|
+
#
|
|
3
|
+
# MIT License - Copyright (C) 2026 Visual Topology Ltd
|
|
4
|
+
#
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
|
|
6
|
+
# and associated documentation files (the "Software"), to deal in the Software without
|
|
7
|
+
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
|
|
8
|
+
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
|
|
9
|
+
# Software is furnished to do so, subject to the following conditions:
|
|
10
|
+
#
|
|
11
|
+
# The above copyright notice and this permission notice shall be included in all copies or
|
|
12
|
+
# substantial portions of the Software.
|
|
13
|
+
#
|
|
14
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
|
|
15
|
+
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
16
|
+
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
|
17
|
+
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class HTTPRequestContext:
|
|
22
|
+
|
|
23
|
+
def __init__(self, path, headers, path_parameters, query_params, request_body, user):
|
|
24
|
+
self.path = path
|
|
25
|
+
self.headers = headers
|
|
26
|
+
self.path_parameters = path_parameters
|
|
27
|
+
self.query_parameters = query_params
|
|
28
|
+
self.request_body = request_body
|
|
29
|
+
self.user = user
|
|
File without changes
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Moonlette - a simple web server
|
|
2
|
+
#
|
|
3
|
+
# MIT License - Copyright (C) 2026 Visual Topology Ltd
|
|
4
|
+
#
|
|
5
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
|
|
6
|
+
# and associated documentation files (the "Software"), to deal in the Software without
|
|
7
|
+
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
|
|
8
|
+
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
|
|
9
|
+
# Software is furnished to do so, subject to the following conditions:
|
|
10
|
+
#
|
|
11
|
+
# The above copyright notice and this permission notice shall be included in all copies or
|
|
12
|
+
# substantial portions of the Software.
|
|
13
|
+
#
|
|
14
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
|
|
15
|
+
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
16
|
+
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
|
17
|
+
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
19
|
+
|
|
20
|
+
from abc import ABC, abstractmethod
|
|
21
|
+
|
|
22
|
+
class WSSession(ABC):
|
|
23
|
+
|
|
24
|
+
@abstractmethod
|
|
25
|
+
async def recv(self, msg:bytes) -> None:
|
|
26
|
+
"""
|
|
27
|
+
Called when a message is received over the websocket
|
|
28
|
+
Args:
|
|
29
|
+
msg: binary message
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
@abstractmethod
|
|
33
|
+
async def close(self):
|
|
34
|
+
"""
|
|
35
|
+
Called when the websocket was closed
|
|
36
|
+
"""
|