Skip to content

Commit 142c89b

Browse files
committed
Added option to restrict access to whole Server with Authentication
1 parent ee7a8b0 commit 142c89b

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

adafruit_httpserver/server.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
from errno import EAGAIN, ECONNRESET, ETIMEDOUT
1818

19+
from .authentication import Basic, Bearer, require_authentication
1920
from .exceptions import AuthenticationError, FileNotExistsError, InvalidPathError
2021
from .methods import GET, HEAD
2122
from .request import Request
@@ -34,6 +35,7 @@ def __init__(self, socket_source: Protocol, root_path: str) -> None:
3435
in CircuitPython or the `socket` module in CPython.
3536
:param str root_path: Root directory to serve files from
3637
"""
38+
self._auths = []
3739
self._buffer = bytearray(1024)
3840
self._timeout = 1
3941
self.routes = _Routes()
@@ -177,6 +179,10 @@ def poll(self):
177179
handler = self.routes.find_handler(_Route(request.path, request.method))
178180

179181
try:
182+
# Check server authentications if necessary
183+
if self._auths:
184+
require_authentication(request, self._auths)
185+
180186
# If a handler for route exists and is callable, call it.
181187
if handler is not None and callable(handler):
182188
handler(request)
@@ -216,6 +222,18 @@ def poll(self):
216222
return
217223
raise
218224

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+
219237
@property
220238
def request_buffer_size(self) -> int:
221239
"""

0 commit comments

Comments
 (0)