16
16
17
17
from errno import EAGAIN , ECONNRESET , ETIMEDOUT
18
18
19
+ from .authentication import Basic , Bearer , require_authentication
19
20
from .exceptions import AuthenticationError , FileNotExistsError , InvalidPathError
20
21
from .methods import GET , HEAD
21
22
from .request import Request
@@ -34,6 +35,7 @@ def __init__(self, socket_source: Protocol, root_path: str) -> None:
34
35
in CircuitPython or the `socket` module in CPython.
35
36
:param str root_path: Root directory to serve files from
36
37
"""
38
+ self ._auths = []
37
39
self ._buffer = bytearray (1024 )
38
40
self ._timeout = 1
39
41
self .routes = _Routes ()
@@ -177,6 +179,10 @@ def poll(self):
177
179
handler = self .routes .find_handler (_Route (request .path , request .method ))
178
180
179
181
try :
182
+ # Check server authentications if necessary
183
+ if self ._auths :
184
+ require_authentication (request , self ._auths )
185
+
180
186
# If a handler for route exists and is callable, call it.
181
187
if handler is not None and callable (handler ):
182
188
handler (request )
@@ -216,6 +222,18 @@ def poll(self):
216
222
return
217
223
raise
218
224
225
+ def restrict_access (self , auths : List [Union [Basic , Bearer ]]) -> None :
226
+ """
227
+ Restricts access to the whole ``Server``.
228
+ It applies to all routes and files in ``root_path``.
229
+
230
+ Example::
231
+
232
+ server = Server(pool, "/static")
233
+ server.restrict_access([Basic("user", "pass")])
234
+ """
235
+ self ._auths = auths
236
+
219
237
@property
220
238
def request_buffer_size (self ) -> int :
221
239
"""
0 commit comments