Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e373d037f0 | ||
|
|
4321d93a82 | ||
|
|
68b6cb9862 | ||
|
|
c7f9b3ff3b | ||
|
|
261dd2f980 | ||
|
|
f204416e36 | ||
|
|
7bc66ce3bb | ||
|
|
43f2227140 | ||
|
|
b0cddde6ec |
3
.github/FUNDING.yml
vendored
Normal file
3
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
github: miguelgrinberg
|
||||||
|
patreon: miguelgrinberg
|
||||||
|
custom: https://paypal.me/miguelgrinberg
|
||||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -25,8 +25,6 @@ wheels/
|
|||||||
.installed.cfg
|
.installed.cfg
|
||||||
*.egg
|
*.egg
|
||||||
MANIFEST
|
MANIFEST
|
||||||
requirements.txt
|
|
||||||
requirements-dev.txt
|
|
||||||
|
|
||||||
# PyInstaller
|
# PyInstaller
|
||||||
# Usually these files are written by a python script from a template
|
# Usually these files are written by a python script from a template
|
||||||
@@ -92,8 +90,6 @@ venv/
|
|||||||
ENV/
|
ENV/
|
||||||
env.bak/
|
env.bak/
|
||||||
venv.bak/
|
venv.bak/
|
||||||
.direnv
|
|
||||||
.envrc
|
|
||||||
|
|
||||||
# Spyder project settings
|
# Spyder project settings
|
||||||
.spyderproject
|
.spyderproject
|
||||||
|
|||||||
18
CHANGES.md
18
CHANGES.md
@@ -1,23 +1,5 @@
|
|||||||
# Microdot change log
|
# Microdot change log
|
||||||
|
|
||||||
**Release 2.0.7** - 2024-11-10
|
|
||||||
|
|
||||||
- Accept responses with just a status code [#263](https://github.com/miguelgrinberg/microdot/issues/263) ([commit #1](https://github.com/miguelgrinberg/microdot/commit/4eac013087f807cafa244b8a6b7b0ed4c82ff150) [commit #2](https://github.com/miguelgrinberg/microdot/commit/c46e4291061046f1be13f300dd08645b71c16635))
|
|
||||||
- Fixed compressed file content-type assignment [#251](https://github.com/miguelgrinberg/microdot/issues/251) ([commit](https://github.com/miguelgrinberg/microdot/commit/482ab6d5ca068d71ea6301f45918946161e9fcc1)) (thanks **Lukas Kremla**!)
|
|
||||||
- Better documentation for start_server[#252](https://github.com/miguelgrinberg/microdot/issues/252) ([commit](https://github.com/miguelgrinberg/microdot/commit/0a021462e0c42c249d587a2d600f5a21a408adfc))
|
|
||||||
- Fix URLs in documentation [#253](https://github.com/miguelgrinberg/microdot/issues/253) ([commit](https://github.com/miguelgrinberg/microdot/commit/5e5fc5e93e11cbf6e3dc8036494e8732d1815d3e)) (thanks **Stanislav Garanzha**!)
|
|
||||||
|
|
||||||
**Release 2.0.6** - 2024-06-18
|
|
||||||
|
|
||||||
- Add event ID to the SSE implementation [#213](https://github.com/miguelgrinberg/microdot/issues/213) ([commit](https://github.com/miguelgrinberg/microdot/commit/904d5fcaa2d19d939a719b8e68c4dee3eb470739)) (thanks **Hamsanger**!)
|
|
||||||
- Configurable session cookie options [#242](https://github.com/miguelgrinberg/microdot/issues/242) ([commit](https://github.com/miguelgrinberg/microdot/commit/0151611fc84fec450820d673f4c4d70c32c990a7))
|
|
||||||
- Improved cookie support in the test client ([commit](https://github.com/miguelgrinberg/microdot/commit/4cb155ee411dc2d9c9f15714cb32b25ba79b156a))
|
|
||||||
- Cookie path support in session extension and test client ([commit](https://github.com/miguelgrinberg/microdot/commit/6ffb8a8fe920111c4d8c16e98715a0d5ee2d1da3))
|
|
||||||
- Refactor `Session` class to make it more reusable ([commit](https://github.com/miguelgrinberg/microdot/commit/dea79c5ce224dec7858ffef45a42bed442fd3a5a))
|
|
||||||
- Use `@functools.wraps` on decorated functions ([commit](https://github.com/miguelgrinberg/microdot/commit/f6876c0d154adcae96098405fb6a1fdf1ea4ec28))
|
|
||||||
- Removed outdated import from documentation [#216](https://github.com/miguelgrinberg/microdot/issues/216) ([commit](https://github.com/miguelgrinberg/microdot/commit/6b1fd6191702e7a9ad934fddfcdd0a3cebea7c94)) (thanks **Carlo Colombo**!)
|
|
||||||
- Add roadmap details to readme ([commit](https://github.com/miguelgrinberg/microdot/commit/a0ea439def238084c4d68309c0992b66ffd28ad6))
|
|
||||||
|
|
||||||
**Release 2.0.5** - 2024-03-09
|
**Release 2.0.5** - 2024-03-09
|
||||||
|
|
||||||
- Correct handling of 0 as an integer argument (regression from #207) [#212](https://github.com/miguelgrinberg/microdot/issues/212) ([commit](https://github.com/miguelgrinberg/microdot/commit/d0a4cf8fa7dfb1da7466157b18d3329a8cf9a5df))
|
- Correct handling of 0 as an integer argument (regression from #207) [#212](https://github.com/miguelgrinberg/microdot/issues/212) ([commit](https://github.com/miguelgrinberg/microdot/commit/d0a4cf8fa7dfb1da7466157b18d3329a8cf9a5df))
|
||||||
|
|||||||
16
docs/api.rst
16
docs/api.rst
@@ -44,6 +44,22 @@ User Sessions
|
|||||||
.. automodule:: microdot.session
|
.. automodule:: microdot.session
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
|
Authentication
|
||||||
|
--------------
|
||||||
|
|
||||||
|
.. automodule:: microdot.auth
|
||||||
|
:inherited-members:
|
||||||
|
:special-members: __call__
|
||||||
|
:members:
|
||||||
|
|
||||||
|
User Logins
|
||||||
|
-----------
|
||||||
|
|
||||||
|
.. automodule:: microdot.login
|
||||||
|
:inherited-members:
|
||||||
|
:special-members: __call__
|
||||||
|
:members:
|
||||||
|
|
||||||
Cross-Origin Resource Sharing (CORS)
|
Cross-Origin Resource Sharing (CORS)
|
||||||
------------------------------------
|
------------------------------------
|
||||||
|
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ Microdot is a highly extensible web application framework. The extensions
|
|||||||
described in this section are maintained as part of the Microdot project in
|
described in this section are maintained as part of the Microdot project in
|
||||||
the same source code repository.
|
the same source code repository.
|
||||||
|
|
||||||
WebSocket Support
|
WebSocket
|
||||||
~~~~~~~~~~~~~~~~~
|
~~~~~~~~~
|
||||||
|
|
||||||
.. list-table::
|
.. list-table::
|
||||||
:align: left
|
:align: left
|
||||||
@@ -39,8 +39,8 @@ Example::
|
|||||||
message = await ws.receive()
|
message = await ws.receive()
|
||||||
await ws.send(message)
|
await ws.send(message)
|
||||||
|
|
||||||
Server-Sent Events Support
|
Server-Sent Events
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. list-table::
|
.. list-table::
|
||||||
:align: left
|
:align: left
|
||||||
@@ -78,8 +78,8 @@ Example::
|
|||||||
the SSE object. For bidirectional communication with the client, use the
|
the SSE object. For bidirectional communication with the client, use the
|
||||||
WebSocket extension.
|
WebSocket extension.
|
||||||
|
|
||||||
Rendering Templates
|
Templates
|
||||||
~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~
|
||||||
|
|
||||||
Many web applications use HTML templates for rendering content to clients.
|
Many web applications use HTML templates for rendering content to clients.
|
||||||
Microdot includes extensions to render templates with the
|
Microdot includes extensions to render templates with the
|
||||||
@@ -202,8 +202,8 @@ must be used.
|
|||||||
.. note::
|
.. note::
|
||||||
The Jinja extension is not compatible with MicroPython.
|
The Jinja extension is not compatible with MicroPython.
|
||||||
|
|
||||||
Maintaining Secure User Sessions
|
Secure User Sessions
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
.. list-table::
|
.. list-table::
|
||||||
:align: left
|
:align: left
|
||||||
@@ -270,6 +270,117 @@ The :func:`save() <microdot.session.SessionDict.save>` and
|
|||||||
:func:`delete() <microdot.session.SessionDict.delete>` methods are used to update
|
:func:`delete() <microdot.session.SessionDict.delete>` methods are used to update
|
||||||
and destroy the user session respectively.
|
and destroy the user session respectively.
|
||||||
|
|
||||||
|
Authentication
|
||||||
|
~~~~~~~~~~~~~~
|
||||||
|
|
||||||
|
.. list-table::
|
||||||
|
:align: left
|
||||||
|
|
||||||
|
* - Compatibility
|
||||||
|
- | CPython & MicroPython
|
||||||
|
|
||||||
|
* - Required Microdot source files
|
||||||
|
- | `auth.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/auth.py>`_
|
||||||
|
|
||||||
|
* - Required external dependencies
|
||||||
|
- | None
|
||||||
|
|
||||||
|
* - Examples
|
||||||
|
- | `basic_auth.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/auth/basic_auth.py>`_
|
||||||
|
| `token_auth.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/auth/token_auth.py>`_
|
||||||
|
|
||||||
|
The authentication extension provides helper classes for two commonly used
|
||||||
|
authentication patterns, described below.
|
||||||
|
|
||||||
|
Basic Authentication
|
||||||
|
^^^^^^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
|
`Basic Authentication <https://en.wikipedia.org/wiki/Basic_access_authentication>`_
|
||||||
|
is a method of authentication that is part of the HTTP specification. It allows
|
||||||
|
clients to authenticate to a server using a username and a password. Web
|
||||||
|
browsers have native support for Basic Authentication and will automatically
|
||||||
|
prompt the user for a username and a password when a protected resource is
|
||||||
|
accessed.
|
||||||
|
|
||||||
|
To use Basic Authentication, create an instance of the :class:`BasicAuth <microdot.auth.BasicAuth>`
|
||||||
|
class::
|
||||||
|
|
||||||
|
from microdot.auth import BasicAuth
|
||||||
|
|
||||||
|
auth = BasicAuth(app)
|
||||||
|
|
||||||
|
Next, create an authentication function. The function must accept a request
|
||||||
|
object and a username and password pair provided by the user. If the
|
||||||
|
credentials are valid, the function must return an object that represents the
|
||||||
|
user. Decorate the function with ``@auth.authenticate``::
|
||||||
|
|
||||||
|
@auth.authenticate
|
||||||
|
async def verify_user(request, username, password):
|
||||||
|
user = await load_user_from_database(username)
|
||||||
|
if user and user.verify_password(password):
|
||||||
|
return user
|
||||||
|
|
||||||
|
If the authentication function cannot validate the user provided credentials it
|
||||||
|
must return ``None``.
|
||||||
|
|
||||||
|
To protect a route with authentication, add the ``auth`` instance as a
|
||||||
|
decorator::
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
@auth
|
||||||
|
async def index(request):
|
||||||
|
return f'Hello, {request.g.current_user}!'
|
||||||
|
|
||||||
|
While running an authenticated request, the user object returned by the
|
||||||
|
authenticaction function is accessible as ``request.g.current_user``.
|
||||||
|
|
||||||
|
Token Authentication
|
||||||
|
^^^^^^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
|
To set up token authentication, create an instance of :class:`TokenAuth <microdot.auth.TokenAuth>`::
|
||||||
|
|
||||||
|
from microdot.auth import TokenAuth
|
||||||
|
|
||||||
|
auth = TokenAuth()
|
||||||
|
|
||||||
|
Then add a function that verifies the token and returns the user it belongs to,
|
||||||
|
or ``None`` if the token is invalid or expired::
|
||||||
|
|
||||||
|
@auth.authenticate
|
||||||
|
async def verify_token(request, token):
|
||||||
|
return load_user_from_token(token)
|
||||||
|
|
||||||
|
As with Basic authentication, the ``auth`` instance is used as a decorator to
|
||||||
|
protect your routes::
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
@auth
|
||||||
|
async def index(request):
|
||||||
|
return f'Hello, {request.g.current_user}!'
|
||||||
|
|
||||||
|
User Logins
|
||||||
|
~~~~~~~~~~~
|
||||||
|
|
||||||
|
.. list-table::
|
||||||
|
:align: left
|
||||||
|
|
||||||
|
* - Compatibility
|
||||||
|
- | CPython & MicroPython
|
||||||
|
|
||||||
|
* - Required Microdot source files
|
||||||
|
- | `login.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/auth.py>`_
|
||||||
|
| `session.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/session.py>`_
|
||||||
|
|
||||||
|
* - Required external dependencies
|
||||||
|
- | CPython: `PyJWT <https://pyjwt.readthedocs.io/>`_
|
||||||
|
| MicroPython: `jwt.py <https://github.com/micropython/micropython-lib/blob/master/python-ecosys/pyjwt/jwt.py>`_,
|
||||||
|
`hmac.py <https://github.com/micropython/micropython-lib/blob/master/python-stdlib/hmac/hmac.py>`_
|
||||||
|
|
||||||
|
* - Examples
|
||||||
|
- | `login.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/login/login.py>`_
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Cross-Origin Resource Sharing (CORS)
|
Cross-Origin Resource Sharing (CORS)
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
@@ -286,7 +397,7 @@ Cross-Origin Resource Sharing (CORS)
|
|||||||
- | None
|
- | None
|
||||||
|
|
||||||
* - Examples
|
* - Examples
|
||||||
- | `app.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/cors/app.py>`_
|
- | `cors.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/cors/cors.py>`_
|
||||||
|
|
||||||
The CORS extension provides support for `Cross-Origin Resource Sharing
|
The CORS extension provides support for `Cross-Origin Resource Sharing
|
||||||
(CORS) <https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS>`_. CORS is a
|
(CORS) <https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS>`_. CORS is a
|
||||||
@@ -305,8 +416,8 @@ Example::
|
|||||||
cors = CORS(app, allowed_origins=['https://example.com'],
|
cors = CORS(app, allowed_origins=['https://example.com'],
|
||||||
allow_credentials=True)
|
allow_credentials=True)
|
||||||
|
|
||||||
Testing with the Test Client
|
Test Client
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~
|
||||||
|
|
||||||
.. list-table::
|
.. list-table::
|
||||||
:align: left
|
:align: left
|
||||||
@@ -342,8 +453,8 @@ Example::
|
|||||||
See the documentation for the :class:`TestClient <microdot.test_client.TestClient>`
|
See the documentation for the :class:`TestClient <microdot.test_client.TestClient>`
|
||||||
class for more details.
|
class for more details.
|
||||||
|
|
||||||
Deploying on a Production Web Server
|
Production Deployments
|
||||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
~~~~~~~~~~~~~~~~~~~~~~
|
||||||
|
|
||||||
The ``Microdot`` class creates its own simple web server. This is enough for an
|
The ``Microdot`` class creates its own simple web server. This is enough for an
|
||||||
application deployed with MicroPython, but when using CPython it may be useful
|
application deployed with MicroPython, but when using CPython it may be useful
|
||||||
@@ -363,7 +474,7 @@ Using an ASGI Web Server
|
|||||||
- | `asgi.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/asgi.py>`_
|
- | `asgi.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot/asgi.py>`_
|
||||||
|
|
||||||
* - Required external dependencies
|
* - Required external dependencies
|
||||||
- | An ASGI web server, such as `Uvicorn <https://www.uvicorn.org/>`_.
|
- | An ASGI web server, such as `Uvicorn <https://uvicorn.org/>`_.
|
||||||
|
|
||||||
* - Examples
|
* - Examples
|
||||||
- | `hello_asgi.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello_asgi.py>`_
|
- | `hello_asgi.py <https://github.com/miguelgrinberg/microdot/blob/main/examples/hello/hello_asgi.py>`_
|
||||||
|
|||||||
@@ -82,34 +82,8 @@ handler functions can be defined as ``async def`` or ``def`` functions, but
|
|||||||
``async def`` functions are recommended for performance.
|
``async def`` functions are recommended for performance.
|
||||||
|
|
||||||
The :func:`run() <microdot.Microdot.run>` method starts the application's web
|
The :func:`run() <microdot.Microdot.run>` method starts the application's web
|
||||||
server on port 5000 by default, and creates its own asynchronous loop. This
|
server on port 5000 by default. This method blocks while it waits for
|
||||||
method blocks while it waits for connections from clients.
|
connections from clients.
|
||||||
|
|
||||||
For some applications it may be necessary to run the web server alongside other
|
|
||||||
asynchronous tasks, on an already running loop. In that case, instead of
|
|
||||||
``app.run()`` the web server can be started by invoking the
|
|
||||||
:func:`start_server() <microdot.Microdot.start_server>` coroutine as shown in
|
|
||||||
the following example::
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
from microdot import Microdot
|
|
||||||
|
|
||||||
app = Microdot()
|
|
||||||
|
|
||||||
@app.route('/')
|
|
||||||
async def index(request):
|
|
||||||
return 'Hello, world!'
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
# start the server in a background task
|
|
||||||
server = asyncio.create_task(app.start_server())
|
|
||||||
|
|
||||||
# ... do other asynchronous work here ...
|
|
||||||
|
|
||||||
# cleanup before ending the application
|
|
||||||
await server
|
|
||||||
|
|
||||||
asyncio.run(main())
|
|
||||||
|
|
||||||
Running with CPython
|
Running with CPython
|
||||||
^^^^^^^^^^^^^^^^^^^^
|
^^^^^^^^^^^^^^^^^^^^
|
||||||
@@ -118,7 +92,7 @@ Running with CPython
|
|||||||
:align: left
|
:align: left
|
||||||
|
|
||||||
* - Required Microdot source files
|
* - Required Microdot source files
|
||||||
- | `microdot.py <https://github.com/miguelgrinberg/microdot/blob/main/src/microdot/microdot.py>`_
|
- | `microdot.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot.py>`_
|
||||||
|
|
||||||
* - Required external dependencies
|
* - Required external dependencies
|
||||||
- | None
|
- | None
|
||||||
@@ -144,7 +118,7 @@ Running with MicroPython
|
|||||||
:align: left
|
:align: left
|
||||||
|
|
||||||
* - Required Microdot source files
|
* - Required Microdot source files
|
||||||
- | `microdot.py <https://github.com/miguelgrinberg/microdot/blob/main/src/microdot/microdot.py>`_
|
- | `microdot.py <https://github.com/miguelgrinberg/microdot/tree/main/src/microdot.py>`_
|
||||||
|
|
||||||
* - Required external dependencies
|
* - Required external dependencies
|
||||||
- | None
|
- | None
|
||||||
@@ -171,9 +145,8 @@ changed by passing the ``port`` argument to the ``run()`` method.
|
|||||||
Web Server Configuration
|
Web Server Configuration
|
||||||
^^^^^^^^^^^^^^^^^^^^^^^^
|
^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
The :func:`run() <microdot.Microdot.run>` and
|
The :func:`run() <microdot.Microdot.run>` method supports a few arguments to
|
||||||
:func:`start_server() <microdot.Microdot.start_server>` methods support a few
|
configure the web server.
|
||||||
arguments to configure the web server.
|
|
||||||
|
|
||||||
- ``port``: The port number to listen on. Pass the desired port number in this
|
- ``port``: The port number to listen on. Pass the desired port number in this
|
||||||
argument to use a port different than the default of 5000. For example::
|
argument to use a port different than the default of 5000. For example::
|
||||||
|
|||||||
1
examples/auth/README.md
Normal file
1
examples/auth/README.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
This directory contains examples that demonstrate basic and token authentication.
|
||||||
31
examples/auth/basic_auth.py
Normal file
31
examples/auth/basic_auth.py
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
from hashlib import sha1
|
||||||
|
from microdot import Microdot
|
||||||
|
from microdot.auth import BasicAuth
|
||||||
|
|
||||||
|
|
||||||
|
def create_hash(password):
|
||||||
|
return sha1(password).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
USERS = {
|
||||||
|
'susan': create_hash(b'hello'),
|
||||||
|
'david': create_hash(b'bye'),
|
||||||
|
}
|
||||||
|
app = Microdot()
|
||||||
|
auth = BasicAuth()
|
||||||
|
|
||||||
|
|
||||||
|
@auth.authenticate
|
||||||
|
async def check_credentials(request, username, password):
|
||||||
|
if username in USERS and USERS[username] == create_hash(password.encode()):
|
||||||
|
return username
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
@auth
|
||||||
|
async def index(request):
|
||||||
|
return f'Hello, {request.g.current_user}!'
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
app.run(debug=True)
|
||||||
26
examples/auth/token_auth.py
Normal file
26
examples/auth/token_auth.py
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
from microdot import Microdot
|
||||||
|
from microdot.auth import TokenAuth
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
auth = TokenAuth()
|
||||||
|
|
||||||
|
TOKENS = {
|
||||||
|
'susan-token': 'susan',
|
||||||
|
'david-token': 'david',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@auth.authenticate
|
||||||
|
async def check_token(request, token):
|
||||||
|
if token in TOKENS:
|
||||||
|
return TOKENS[token]
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
@auth
|
||||||
|
async def index(request):
|
||||||
|
return f'Hello, {request.g.current_user}!'
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
app.run(debug=True)
|
||||||
@@ -16,7 +16,7 @@ blinker==1.7.0
|
|||||||
# quart
|
# quart
|
||||||
build==1.0.3
|
build==1.0.3
|
||||||
# via pip-tools
|
# via pip-tools
|
||||||
certifi==2024.7.4
|
certifi==2023.11.17
|
||||||
# via requests
|
# via requests
|
||||||
charset-normalizer==3.3.2
|
charset-normalizer==3.3.2
|
||||||
# via requests
|
# via requests
|
||||||
@@ -57,7 +57,7 @@ itsdangerous==2.1.2
|
|||||||
# via
|
# via
|
||||||
# flask
|
# flask
|
||||||
# quart
|
# quart
|
||||||
jinja2==3.1.4
|
jinja2==3.1.3
|
||||||
# via
|
# via
|
||||||
# flask
|
# flask
|
||||||
# quart
|
# quart
|
||||||
@@ -82,9 +82,9 @@ pydantic-core==2.14.5
|
|||||||
# via pydantic
|
# via pydantic
|
||||||
pyproject-hooks==1.0.0
|
pyproject-hooks==1.0.0
|
||||||
# via build
|
# via build
|
||||||
quart==0.19.7
|
quart==0.19.4
|
||||||
# via -r requirements.in
|
# via -r requirements.in
|
||||||
requests==2.32.0
|
requests==2.31.0
|
||||||
# via -r requirements.in
|
# via -r requirements.in
|
||||||
sniffio==1.3.0
|
sniffio==1.3.0
|
||||||
# via anyio
|
# via anyio
|
||||||
@@ -95,11 +95,11 @@ typing-extensions==4.9.0
|
|||||||
# fastapi
|
# fastapi
|
||||||
# pydantic
|
# pydantic
|
||||||
# pydantic-core
|
# pydantic-core
|
||||||
urllib3==2.2.2
|
urllib3==2.1.0
|
||||||
# via requests
|
# via requests
|
||||||
uvicorn==0.24.0.post1
|
uvicorn==0.24.0.post1
|
||||||
# via -r requirements.in
|
# via -r requirements.in
|
||||||
werkzeug==3.0.6
|
werkzeug==3.0.1
|
||||||
# via
|
# via
|
||||||
# flask
|
# flask
|
||||||
# quart
|
# quart
|
||||||
|
|||||||
1
examples/login/README.md
Normal file
1
examples/login/README.md
Normal file
@@ -0,0 +1 @@
|
|||||||
|
This directory contains examples that demonstrate user logins.
|
||||||
122
examples/login/login.py
Normal file
122
examples/login/login.py
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
from hashlib import sha1
|
||||||
|
from microdot import Microdot, redirect
|
||||||
|
from microdot.session import Session
|
||||||
|
from microdot.login import Login
|
||||||
|
|
||||||
|
|
||||||
|
class User:
|
||||||
|
def __init__(self, id, username, password):
|
||||||
|
self.id = id
|
||||||
|
self.username = username
|
||||||
|
self.password_hash = self.create_hash(password)
|
||||||
|
|
||||||
|
def create_hash(self, password):
|
||||||
|
# note: to keep this example simple, passwords are hashed with the SHA1
|
||||||
|
# algorithm. In a real application, you should use a stronger
|
||||||
|
# algorithm, such as bcrypt.
|
||||||
|
return sha1(password.encode()).hexdigest()
|
||||||
|
|
||||||
|
def check_password(self, password):
|
||||||
|
return self.create_hash(password) == self.password_hash
|
||||||
|
|
||||||
|
|
||||||
|
USERS = {
|
||||||
|
'user001': User('user001', 'susan', 'hello'),
|
||||||
|
'user002': User('user002', 'david', 'bye'),
|
||||||
|
}
|
||||||
|
|
||||||
|
app = Microdot()
|
||||||
|
Session(app, secret_key='top-secret!')
|
||||||
|
auth = Login()
|
||||||
|
|
||||||
|
|
||||||
|
@auth.id_to_user
|
||||||
|
async def get_user(user_id):
|
||||||
|
print('get_user', user_id)
|
||||||
|
return USERS.get(user_id)
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/login', methods=['GET', 'POST'])
|
||||||
|
async def login(request):
|
||||||
|
if request.method == 'GET':
|
||||||
|
return '''
|
||||||
|
<!doctype html>
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
<h1>Please Login</h1>
|
||||||
|
<form method="POST">
|
||||||
|
<p>
|
||||||
|
Username<br>
|
||||||
|
<input name="username" autofocus>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Password:<br>
|
||||||
|
<input name="password" type="password">
|
||||||
|
<br>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<input name="remember_me" type="checkbox"> Remember me
|
||||||
|
<br>
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<button type="submit">Login</button>
|
||||||
|
</p>
|
||||||
|
</form>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
''', {'Content-Type': 'text/html'}
|
||||||
|
username = request.form['username']
|
||||||
|
password = request.form['password']
|
||||||
|
remember_me = bool(request.form.get('remember_me'))
|
||||||
|
|
||||||
|
for user in USERS.values():
|
||||||
|
if user.username == username:
|
||||||
|
if user.check_password(password):
|
||||||
|
return await auth.login_user(request, user,
|
||||||
|
remember=remember_me)
|
||||||
|
return redirect('/login')
|
||||||
|
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
@auth
|
||||||
|
async def index(request):
|
||||||
|
return f'''
|
||||||
|
<!doctype html>
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
<h1>Hello, {request.g.current_user.username}!</h1>
|
||||||
|
<p>
|
||||||
|
<a href="/fresh">Click here</a> to access the fresh login page.
|
||||||
|
</p>
|
||||||
|
<form method="POST" action="/logout">
|
||||||
|
<button type="submit">Logout</button>
|
||||||
|
</form>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
''', {'Content-Type': 'text/html'}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get('/fresh')
|
||||||
|
@auth.fresh
|
||||||
|
async def fresh(request):
|
||||||
|
return f'''
|
||||||
|
<!doctype html>
|
||||||
|
<html>
|
||||||
|
<body>
|
||||||
|
<h1>Hello, {request.g.current_user.username}!</h1>
|
||||||
|
<p>This page requires a fresh login session.</p>
|
||||||
|
<p><a href="/">Go back</a> to the main page.</p>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
''', {'Content-Type': 'text/html'}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post('/logout')
|
||||||
|
@auth
|
||||||
|
async def logout(request):
|
||||||
|
await auth.logout_user(request)
|
||||||
|
return redirect('/')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
app.run(debug=True)
|
||||||
@@ -1,3 +1,7 @@
|
|||||||
|
# This is a simple example that demonstrates how to use the user session, but
|
||||||
|
# is not intended as a complete login solution. See the login subdirectory for
|
||||||
|
# a more complete example.
|
||||||
|
|
||||||
from microdot import Microdot, Response, redirect
|
from microdot import Microdot, Response, redirect
|
||||||
from microdot.session import Session, with_session
|
from microdot.session import Session, with_session
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "microdot"
|
name = "microdot"
|
||||||
version = "2.0.8.dev0"
|
version = "2.0.6.dev0"
|
||||||
authors = [
|
authors = [
|
||||||
{ name = "Miguel Grinberg", email = "miguel.grinberg@gmail.com" },
|
{ name = "Miguel Grinberg", email = "miguel.grinberg@gmail.com" },
|
||||||
]
|
]
|
||||||
@@ -14,8 +14,6 @@ classifiers = [
|
|||||||
"Operating System :: OS Independent",
|
"Operating System :: OS Independent",
|
||||||
]
|
]
|
||||||
requires-python = ">=3.8"
|
requires-python = ">=3.8"
|
||||||
dependencies = [
|
|
||||||
]
|
|
||||||
|
|
||||||
[project.readme]
|
[project.readme]
|
||||||
file = "README.md"
|
file = "README.md"
|
||||||
@@ -26,12 +24,9 @@ Homepage = "https://github.com/miguelgrinberg/microdot"
|
|||||||
"Bug Tracker" = "https://github.com/miguelgrinberg/microdot/issues"
|
"Bug Tracker" = "https://github.com/miguelgrinberg/microdot/issues"
|
||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
dev = [
|
|
||||||
"tox",
|
|
||||||
]
|
|
||||||
docs = [
|
docs = [
|
||||||
"sphinx",
|
"sphinx",
|
||||||
"pyjwt",
|
"pyjwt"
|
||||||
]
|
]
|
||||||
|
|
||||||
[tool.setuptools]
|
[tool.setuptools]
|
||||||
|
|||||||
144
src/microdot/auth.py
Normal file
144
src/microdot/auth.py
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
from microdot import abort
|
||||||
|
from microdot.microdot import invoke_handler
|
||||||
|
|
||||||
|
|
||||||
|
class BaseAuth:
|
||||||
|
def __init__(self):
|
||||||
|
self.auth_callback = None
|
||||||
|
self.error_callback = None
|
||||||
|
|
||||||
|
def __call__(self, f):
|
||||||
|
"""Decorator to protect a route with authentication.
|
||||||
|
|
||||||
|
An instance of this class must be used as a decorator on the routes
|
||||||
|
that need to be protected. Example::
|
||||||
|
|
||||||
|
auth = BasicAuth() # or TokenAuth()
|
||||||
|
|
||||||
|
@app.route('/protected')
|
||||||
|
@auth
|
||||||
|
def protected(request):
|
||||||
|
# ...
|
||||||
|
|
||||||
|
Routes that are decorated in this way will only be invoked if the
|
||||||
|
authentication callback returned a valid user object, otherwise the
|
||||||
|
error callback will be executed.
|
||||||
|
"""
|
||||||
|
async def wrapper(request, *args, **kwargs):
|
||||||
|
auth = self._get_auth(request)
|
||||||
|
if not auth:
|
||||||
|
return await invoke_handler(self.error_callback, request)
|
||||||
|
request.g.current_user = await invoke_handler(
|
||||||
|
self.auth_callback, request, *auth)
|
||||||
|
if not request.g.current_user:
|
||||||
|
return await invoke_handler(self.error_callback, request)
|
||||||
|
return await invoke_handler(f, request, *args, **kwargs)
|
||||||
|
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
class BasicAuth(BaseAuth):
|
||||||
|
"""Basic Authentication.
|
||||||
|
|
||||||
|
:param realm: The realm that is displayed when the user is prompted to
|
||||||
|
authenticate in the browser.
|
||||||
|
:param charset: The charset that is used to encode the realm.
|
||||||
|
:param scheme: The authentication scheme. Defaults to 'Basic'.
|
||||||
|
:param error_status: The error status code to return when authentication
|
||||||
|
fails. Defaults to 401.
|
||||||
|
"""
|
||||||
|
def __init__(self, realm='Please login', charset='UTF-8', scheme='Basic',
|
||||||
|
error_status=401):
|
||||||
|
super().__init__()
|
||||||
|
self.realm = realm
|
||||||
|
self.charset = charset
|
||||||
|
self.scheme = scheme
|
||||||
|
self.error_status = error_status
|
||||||
|
self.error_callback = self.authentication_error
|
||||||
|
|
||||||
|
def _get_auth(self, request):
|
||||||
|
auth = request.headers.get('Authorization')
|
||||||
|
if auth and auth.startswith('Basic '):
|
||||||
|
import binascii
|
||||||
|
try:
|
||||||
|
username, password = binascii.a2b_base64(
|
||||||
|
auth[6:]).decode().split(':', 1)
|
||||||
|
except Exception: # pragma: no cover
|
||||||
|
return None
|
||||||
|
return username, password
|
||||||
|
|
||||||
|
def authentication_error(self, request):
|
||||||
|
return '', self.error_status, {
|
||||||
|
'WWW-Authenticate': '{} realm="{}", charset="{}"'.format(
|
||||||
|
self.scheme, self.realm, self.charset)}
|
||||||
|
|
||||||
|
def authenticate(self, f):
|
||||||
|
"""Decorator to configure the authentication callback.
|
||||||
|
|
||||||
|
This decorator must be used with a function that accepts the request
|
||||||
|
object, a username and a password and returns a user object if the
|
||||||
|
credentials are valid, or ``None`` if they are not. Example::
|
||||||
|
|
||||||
|
@auth.authenticate
|
||||||
|
async def check_credentials(request, username, password):
|
||||||
|
user = get_user(username)
|
||||||
|
if user and user.check_password(password):
|
||||||
|
return get_user(username)
|
||||||
|
"""
|
||||||
|
self.auth_callback = f
|
||||||
|
|
||||||
|
|
||||||
|
class TokenAuth(BaseAuth):
|
||||||
|
"""Token based authentication.
|
||||||
|
|
||||||
|
:param header: The name of the header that will contain the token. Defaults
|
||||||
|
to 'Authorization'.
|
||||||
|
:param scheme: The authentication scheme. Defaults to 'Bearer'.
|
||||||
|
:param error_status: The error status code to return when authentication
|
||||||
|
fails. Defaults to 401.
|
||||||
|
"""
|
||||||
|
def __init__(self, header='Authorization', scheme='Bearer',
|
||||||
|
error_status=401):
|
||||||
|
super().__init__()
|
||||||
|
self.header = header
|
||||||
|
self.scheme = scheme.lower()
|
||||||
|
self.error_status = error_status
|
||||||
|
self.error_callback = self.authentication_error
|
||||||
|
|
||||||
|
def _get_auth(self, request):
|
||||||
|
auth = request.headers.get(self.header)
|
||||||
|
if auth:
|
||||||
|
if self.header == 'Authorization':
|
||||||
|
try:
|
||||||
|
scheme, token = auth.split(' ', 1)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
if scheme.lower() == self.scheme:
|
||||||
|
return (token.strip(),)
|
||||||
|
else:
|
||||||
|
return (auth,)
|
||||||
|
|
||||||
|
def authenticate(self, f):
|
||||||
|
"""Decorator to configure the authentication callback.
|
||||||
|
|
||||||
|
This decorator must be used with a function that accepts the request
|
||||||
|
object, a username and a password and returns a user object if the
|
||||||
|
credentials are valid, or ``None`` if they are not. Example::
|
||||||
|
|
||||||
|
@auth.authenticate
|
||||||
|
async def check_credentials(request, token):
|
||||||
|
return get_user(token)
|
||||||
|
"""
|
||||||
|
self.auth_callback = f
|
||||||
|
|
||||||
|
def errorhandler(self, f):
|
||||||
|
"""Decorator to configure the error callback.
|
||||||
|
|
||||||
|
Microdot calls the error callback to allow the application to generate
|
||||||
|
a custom error response. The default error response is to call
|
||||||
|
``abort(401)``.
|
||||||
|
"""
|
||||||
|
self.error_callback = f
|
||||||
|
|
||||||
|
def authentication_error(self, request):
|
||||||
|
abort(self.error_status)
|
||||||
150
src/microdot/login.py
Normal file
150
src/microdot/login.py
Normal file
@@ -0,0 +1,150 @@
|
|||||||
|
from time import time
|
||||||
|
from microdot import redirect
|
||||||
|
from microdot.microdot import urlencode, invoke_handler
|
||||||
|
|
||||||
|
|
||||||
|
class Login:
|
||||||
|
def __init__(self, login_url='/login'):
|
||||||
|
self.login_url = login_url
|
||||||
|
self.user_callback = None
|
||||||
|
self.user_id_callback = lambda user: user.id
|
||||||
|
|
||||||
|
def id_to_user(self, f):
|
||||||
|
"""Decorator to configure the user callback.
|
||||||
|
|
||||||
|
The decorated function receives the user ID as an argument and must
|
||||||
|
return the corresponding user object, or ``None`` if the user ID is
|
||||||
|
invalid.
|
||||||
|
"""
|
||||||
|
self.user_callback = f
|
||||||
|
|
||||||
|
def user_to_id(self, f):
|
||||||
|
"""Decorator to configure the user ID callback.
|
||||||
|
|
||||||
|
The decorated functon receives the user object as an argument and must
|
||||||
|
return the corresponding user ID. By default, the ``id`` attribute of
|
||||||
|
the user object is used.
|
||||||
|
"""
|
||||||
|
self.user_id_callback = f
|
||||||
|
|
||||||
|
def _get_session(self, request):
|
||||||
|
return request.app._session.get(request)
|
||||||
|
|
||||||
|
def _update_remember_cookie(self, request, days, user_id=None):
|
||||||
|
remember_payload = request.app._session.encode({
|
||||||
|
'user_id': user_id,
|
||||||
|
'days': days,
|
||||||
|
'exp': time() + days * 24 * 60 * 60
|
||||||
|
})
|
||||||
|
|
||||||
|
@request.after_request
|
||||||
|
async def _set_remember_cookie(request, response):
|
||||||
|
response.set_cookie('_remember', remember_payload,
|
||||||
|
max_age=days * 24 * 60 * 60)
|
||||||
|
return response
|
||||||
|
|
||||||
|
def _get_user_id_from_session(self, request):
|
||||||
|
session = self._get_session(request)
|
||||||
|
if session and '_user_id' in session:
|
||||||
|
return session['_user_id']
|
||||||
|
if '_remember' in request.cookies:
|
||||||
|
remember_payload = request.app._session.decode(
|
||||||
|
request.cookies['_remember'])
|
||||||
|
user_id = remember_payload.get('user_id')
|
||||||
|
if user_id: # pragma: no branch
|
||||||
|
self._update_remember_cookie(
|
||||||
|
request, remember_payload.get('_days', 30), user_id)
|
||||||
|
session['_user_id'] = user_id
|
||||||
|
session['_fresh'] = False
|
||||||
|
session.save()
|
||||||
|
return user_id
|
||||||
|
|
||||||
|
async def _redirect_to_login(self, request):
|
||||||
|
return '', 302, {'Location': self.login_url + '?next=' + urlencode(
|
||||||
|
request.url)}
|
||||||
|
|
||||||
|
async def login_user(self, request, user, remember=False,
|
||||||
|
redirect_url='/'):
|
||||||
|
"""Log a user in.
|
||||||
|
|
||||||
|
:param request: the request object
|
||||||
|
:param user: the user object
|
||||||
|
:param remember: if the user's logged in state should be remembered
|
||||||
|
with a cookie after the session ends. Set to the
|
||||||
|
number of days the remember cookie should last, or to
|
||||||
|
``True`` to use a default duration of 30 days.
|
||||||
|
:param redirect_url: the URL to redirect to after login
|
||||||
|
|
||||||
|
This call marks the user as logged in by storing their user ID in the
|
||||||
|
user session. The application must call this method to log a user in
|
||||||
|
after their credentials have been validated.
|
||||||
|
|
||||||
|
The method returns a redirect response, either to the URL the user
|
||||||
|
originally intended to visit, or if there is no original URL to the URL
|
||||||
|
specified by the `redirect_url`.
|
||||||
|
"""
|
||||||
|
session = self._get_session(request)
|
||||||
|
session['_user_id'] = await invoke_handler(self.user_id_callback, user)
|
||||||
|
session['_fresh'] = True
|
||||||
|
session.save()
|
||||||
|
|
||||||
|
if remember:
|
||||||
|
days = 30 if remember is True else int(remember)
|
||||||
|
self._update_remember_cookie(request, days, session['_user_id'])
|
||||||
|
|
||||||
|
next_url = request.args.get('next', redirect_url)
|
||||||
|
if not next_url.startswith('/'):
|
||||||
|
next_url = redirect_url
|
||||||
|
return redirect(next_url)
|
||||||
|
|
||||||
|
async def logout_user(self, request):
|
||||||
|
"""Log a user out.
|
||||||
|
|
||||||
|
:param request: the request object
|
||||||
|
|
||||||
|
This call removes information about the user's log in from the user
|
||||||
|
session. If a remember cookie exists, it is removed as well.
|
||||||
|
"""
|
||||||
|
session = self._get_session(request)
|
||||||
|
session.pop('_user_id', None)
|
||||||
|
session.pop('_fresh', None)
|
||||||
|
session.save()
|
||||||
|
if '_remember' in request.cookies:
|
||||||
|
self._update_remember_cookie(request, 0)
|
||||||
|
|
||||||
|
def __call__(self, f):
|
||||||
|
"""Decorator to protect a route with authentication.
|
||||||
|
|
||||||
|
If the user is not logged in, Microdot will redirect to the login page
|
||||||
|
first. The decorated route will only run after successful login by the
|
||||||
|
user. If the user is already logged in, the route will run immediately.
|
||||||
|
"""
|
||||||
|
async def wrapper(request, *args, **kwargs):
|
||||||
|
user_id = self._get_user_id_from_session(request)
|
||||||
|
if not user_id:
|
||||||
|
return await self._redirect_to_login(request)
|
||||||
|
request.g.current_user = await invoke_handler(
|
||||||
|
self.user_callback, user_id)
|
||||||
|
if not request.g.current_user:
|
||||||
|
return await self._redirect_to_login(request)
|
||||||
|
return await invoke_handler(f, request, *args, **kwargs)
|
||||||
|
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
def fresh(self, f):
|
||||||
|
"""Decorator to protect a route with "fresh" authentication.
|
||||||
|
|
||||||
|
This decorator prevents the route from running when the login session
|
||||||
|
is not fresh. A fresh session is a session that has been created from
|
||||||
|
direct user interaction with the login page, as opposite to a session
|
||||||
|
that was restored from a "remember me" cookie.
|
||||||
|
"""
|
||||||
|
base_wrapper = self.__call__(f)
|
||||||
|
|
||||||
|
async def wrapper(request, *args, **kwargs):
|
||||||
|
session = self._get_session(request)
|
||||||
|
if session.get('_fresh'):
|
||||||
|
return await base_wrapper(request, *args, **kwargs)
|
||||||
|
return await self._redirect_to_login(request)
|
||||||
|
|
||||||
|
return wrapper
|
||||||
@@ -774,9 +774,6 @@ class Response:
|
|||||||
first.
|
first.
|
||||||
"""
|
"""
|
||||||
if content_type is None:
|
if content_type is None:
|
||||||
if compressed and filename.endswith('.gz'):
|
|
||||||
ext = filename[:-3].split('.')[-1]
|
|
||||||
else:
|
|
||||||
ext = filename.split('.')[-1]
|
ext = filename.split('.')[-1]
|
||||||
if ext in Response.types_map:
|
if ext in Response.types_map:
|
||||||
content_type = Response.types_map[ext]
|
content_type = Response.types_map[ext]
|
||||||
@@ -1369,12 +1366,7 @@ class Microdot:
|
|||||||
if res is None:
|
if res is None:
|
||||||
res = await invoke_handler(
|
res = await invoke_handler(
|
||||||
f, req, **req.url_args)
|
f, req, **req.url_args)
|
||||||
if isinstance(res, int):
|
|
||||||
res = '', res
|
|
||||||
if isinstance(res, tuple):
|
if isinstance(res, tuple):
|
||||||
if isinstance(res[0], int):
|
|
||||||
res = ('', res[0],
|
|
||||||
res[1] if len(res) > 1 else {})
|
|
||||||
body = res[0]
|
body = res[0]
|
||||||
if isinstance(res[1], int):
|
if isinstance(res[1], int):
|
||||||
status_code = res[1]
|
status_code = res[1]
|
||||||
|
|||||||
@@ -29,21 +29,14 @@ class Session:
|
|||||||
"""
|
"""
|
||||||
secret_key = None
|
secret_key = None
|
||||||
|
|
||||||
def __init__(self, app=None, secret_key=None, cookie_options=None):
|
def __init__(self, app=None, secret_key=None):
|
||||||
self.secret_key = secret_key
|
self.secret_key = secret_key
|
||||||
self.cookie_options = cookie_options or {}
|
|
||||||
if app is not None:
|
if app is not None:
|
||||||
self.initialize(app)
|
self.initialize(app)
|
||||||
|
|
||||||
def initialize(self, app, secret_key=None, cookie_options=None):
|
def initialize(self, app, secret_key=None):
|
||||||
if secret_key is not None:
|
if secret_key is not None:
|
||||||
self.secret_key = secret_key
|
self.secret_key = secret_key
|
||||||
if cookie_options is not None:
|
|
||||||
self.cookie_options = cookie_options
|
|
||||||
if 'path' not in self.cookie_options:
|
|
||||||
self.cookie_options['path'] = '/'
|
|
||||||
if 'http_only' not in self.cookie_options:
|
|
||||||
self.cookie_options['http_only'] = True
|
|
||||||
app._session = self
|
app._session = self
|
||||||
|
|
||||||
def get(self, request):
|
def get(self, request):
|
||||||
@@ -93,8 +86,7 @@ class Session:
|
|||||||
|
|
||||||
@request.after_request
|
@request.after_request
|
||||||
def _update_session(request, response):
|
def _update_session(request, response):
|
||||||
response.set_cookie('session', encoded_session,
|
response.set_cookie('session', encoded_session, http_only=True)
|
||||||
**self.cookie_options)
|
|
||||||
return response
|
return response
|
||||||
|
|
||||||
def delete(self, request):
|
def delete(self, request):
|
||||||
@@ -117,7 +109,8 @@ class Session:
|
|||||||
"""
|
"""
|
||||||
@request.after_request
|
@request.after_request
|
||||||
def _delete_session(request, response):
|
def _delete_session(request, response):
|
||||||
response.delete_cookie('session', **self.cookie_options)
|
response.set_cookie('session', '', http_only=True,
|
||||||
|
expires='Thu, 01 Jan 1970 00:00:01 GMT')
|
||||||
return response
|
return response
|
||||||
|
|
||||||
def encode(self, payload, secret_key=None):
|
def encode(self, payload, secret_key=None):
|
||||||
|
|||||||
@@ -112,13 +112,9 @@ class TestClient:
|
|||||||
headers['Host'] = 'example.com:1234'
|
headers['Host'] = 'example.com:1234'
|
||||||
return body, headers
|
return body, headers
|
||||||
|
|
||||||
def _process_cookies(self, path, headers):
|
def _process_cookies(self, headers):
|
||||||
cookies = ''
|
cookies = ''
|
||||||
for name, value in self.cookies.items():
|
for name, value in self.cookies.items():
|
||||||
if isinstance(value, tuple):
|
|
||||||
value, cookie_path = value
|
|
||||||
if not path.startswith(cookie_path):
|
|
||||||
continue
|
|
||||||
if cookies:
|
if cookies:
|
||||||
cookies += '; '
|
cookies += '; '
|
||||||
cookies += name + '=' + value
|
cookies += name + '=' + value
|
||||||
@@ -127,7 +123,7 @@ class TestClient:
|
|||||||
headers['Cookie'] += '; ' + cookies
|
headers['Cookie'] += '; ' + cookies
|
||||||
else:
|
else:
|
||||||
headers['Cookie'] = cookies
|
headers['Cookie'] = cookies
|
||||||
return headers
|
return cookies, headers
|
||||||
|
|
||||||
def _render_request(self, method, path, headers, body):
|
def _render_request(self, method, path, headers, body):
|
||||||
request_bytes = '{method} {path} HTTP/1.0\n'.format(
|
request_bytes = '{method} {path} HTTP/1.0\n'.format(
|
||||||
@@ -143,45 +139,36 @@ class TestClient:
|
|||||||
for cookie in cookies:
|
for cookie in cookies:
|
||||||
cookie_name, cookie_value = cookie.split('=', 1)
|
cookie_name, cookie_value = cookie.split('=', 1)
|
||||||
cookie_options = cookie_value.split(';')
|
cookie_options = cookie_value.split(';')
|
||||||
path = '/'
|
|
||||||
delete = False
|
delete = False
|
||||||
for option in cookie_options[1:]:
|
for option in cookie_options[1:]:
|
||||||
option = option.strip().lower()
|
if option.strip().lower().startswith(
|
||||||
if option.startswith(
|
|
||||||
'max-age='): # pragma: no cover
|
'max-age='): # pragma: no cover
|
||||||
_, age = option.split('=', 1)
|
_, age = option.strip().split('=', 1)
|
||||||
try:
|
try:
|
||||||
age = int(age)
|
age = int(age)
|
||||||
except ValueError: # pragma: no cover
|
except ValueError: # pragma: no cover
|
||||||
age = 0
|
age = 0
|
||||||
if age <= 0:
|
if age <= 0:
|
||||||
delete = True
|
delete = True
|
||||||
elif option.startswith('expires='):
|
break
|
||||||
_, e = option.split('=', 1)
|
elif option.strip().lower().startswith('expires='):
|
||||||
|
_, e = option.strip().split('=', 1)
|
||||||
# this is a very limited parser for cookie expiry
|
# this is a very limited parser for cookie expiry
|
||||||
# that only detects a cookie deletion request when
|
# that only detects a cookie deletion request when
|
||||||
# the date is 1/1/1970
|
# the date is 1/1/1970
|
||||||
if '1 jan 1970' in e.lower(): # pragma: no branch
|
if '1 jan 1970' in e.lower(): # pragma: no branch
|
||||||
delete = True
|
delete = True
|
||||||
elif option.startswith('path='):
|
break
|
||||||
_, path = option.split('=', 1)
|
|
||||||
if delete:
|
if delete:
|
||||||
if cookie_name in self.cookies: # pragma: no branch
|
if cookie_name in self.cookies: # pragma: no branch
|
||||||
cookie_path = self.cookies[cookie_name][1] \
|
|
||||||
if isinstance(self.cookies[cookie_name], tuple) \
|
|
||||||
else '/'
|
|
||||||
if path == cookie_path:
|
|
||||||
del self.cookies[cookie_name]
|
del self.cookies[cookie_name]
|
||||||
else:
|
else:
|
||||||
if path == '/':
|
|
||||||
self.cookies[cookie_name] = cookie_options[0]
|
self.cookies[cookie_name] = cookie_options[0]
|
||||||
else:
|
|
||||||
self.cookies[cookie_name] = (cookie_options[0], path)
|
|
||||||
|
|
||||||
async def request(self, method, path, headers=None, body=None, sock=None):
|
async def request(self, method, path, headers=None, body=None, sock=None):
|
||||||
headers = headers or {}
|
headers = headers or {}
|
||||||
body, headers = self._process_body(body, headers)
|
body, headers = self._process_body(body, headers)
|
||||||
headers = self._process_cookies(path, headers)
|
cookies, headers = self._process_cookies(headers)
|
||||||
request_bytes = self._render_request(method, path, headers, body)
|
request_bytes = self._render_request(method, path, headers, body)
|
||||||
if sock:
|
if sock:
|
||||||
reader = sock[0]
|
reader = sock[0]
|
||||||
|
|||||||
@@ -9,3 +9,4 @@ from tests.test_sse import * # noqa: F401, F403
|
|||||||
from tests.test_cors import * # noqa: F401, F403
|
from tests.test_cors import * # noqa: F401, F403
|
||||||
from tests.test_utemplate import * # noqa: F401, F403
|
from tests.test_utemplate import * # noqa: F401, F403
|
||||||
from tests.test_session import * # noqa: F401, F403
|
from tests.test_session import * # noqa: F401, F403
|
||||||
|
from tests.test_auth import * # noqa: F401, F403
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
foo
|
|
||||||
125
tests/test_auth.py
Normal file
125
tests/test_auth.py
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
import asyncio
|
||||||
|
import binascii
|
||||||
|
import unittest
|
||||||
|
from microdot import Microdot
|
||||||
|
from microdot.auth import BasicAuth, TokenAuth
|
||||||
|
from microdot.test_client import TestClient
|
||||||
|
|
||||||
|
|
||||||
|
class TestAuth(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
if hasattr(asyncio, 'set_event_loop'):
|
||||||
|
asyncio.set_event_loop(asyncio.new_event_loop())
|
||||||
|
cls.loop = asyncio.get_event_loop()
|
||||||
|
|
||||||
|
def _run(self, coro):
|
||||||
|
return self.loop.run_until_complete(coro)
|
||||||
|
|
||||||
|
def test_basic_auth(self):
|
||||||
|
app = Microdot()
|
||||||
|
basic_auth = BasicAuth()
|
||||||
|
|
||||||
|
@basic_auth.authenticate
|
||||||
|
def authenticate(request, username, password):
|
||||||
|
if username == 'foo' and password == 'bar':
|
||||||
|
return {'username': username}
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
@basic_auth
|
||||||
|
def index(request):
|
||||||
|
return request.g.current_user['username']
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 401)
|
||||||
|
|
||||||
|
res = self._run(client.get('/', headers={
|
||||||
|
'Authorization': 'Basic ' + binascii.b2a_base64(
|
||||||
|
b'foo:bar').decode()}))
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
self.assertEqual(res.text, 'foo')
|
||||||
|
|
||||||
|
res = self._run(client.get('/', headers={
|
||||||
|
'Authorization': 'Basic ' + binascii.b2a_base64(
|
||||||
|
b'foo:baz').decode()}))
|
||||||
|
self.assertEqual(res.status_code, 401)
|
||||||
|
|
||||||
|
def test_token_auth(self):
|
||||||
|
app = Microdot()
|
||||||
|
token_auth = TokenAuth()
|
||||||
|
|
||||||
|
@token_auth.authenticate
|
||||||
|
def authenticate(request, token):
|
||||||
|
if token == 'foo':
|
||||||
|
return 'user'
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
@token_auth
|
||||||
|
def index(request):
|
||||||
|
return request.g.current_user
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 401)
|
||||||
|
|
||||||
|
res = self._run(client.get('/', headers={
|
||||||
|
'Authorization': 'Basic foo'}))
|
||||||
|
self.assertEqual(res.status_code, 401)
|
||||||
|
|
||||||
|
res = self._run(client.get('/', headers={'Authorization': 'foo'}))
|
||||||
|
self.assertEqual(res.status_code, 401)
|
||||||
|
|
||||||
|
res = self._run(client.get('/', headers={
|
||||||
|
'Authorization': 'Bearer foo'}))
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
self.assertEqual(res.text, 'user')
|
||||||
|
|
||||||
|
def test_token_auth_custom_header(self):
|
||||||
|
app = Microdot()
|
||||||
|
token_auth = TokenAuth(header='X-Auth-Token')
|
||||||
|
|
||||||
|
@token_auth.authenticate
|
||||||
|
def authenticate(request, token):
|
||||||
|
if token == 'foo':
|
||||||
|
return 'user'
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
@token_auth
|
||||||
|
def index(request):
|
||||||
|
return request.g.current_user
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 401)
|
||||||
|
|
||||||
|
res = self._run(client.get('/', headers={
|
||||||
|
'Authorization': 'Basic foo'}))
|
||||||
|
self.assertEqual(res.status_code, 401)
|
||||||
|
|
||||||
|
res = self._run(client.get('/', headers={'Authorization': 'foo'}))
|
||||||
|
self.assertEqual(res.status_code, 401)
|
||||||
|
|
||||||
|
res = self._run(client.get('/', headers={
|
||||||
|
'Authorization': 'Bearer foo'}))
|
||||||
|
self.assertEqual(res.status_code, 401)
|
||||||
|
|
||||||
|
res = self._run(client.get('/', headers={
|
||||||
|
'X-Token-Auth': 'Bearer foo'}))
|
||||||
|
self.assertEqual(res.status_code, 401)
|
||||||
|
|
||||||
|
res = self._run(client.get('/', headers={'X-Auth-Token': 'foo'}))
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
self.assertEqual(res.text, 'user')
|
||||||
|
|
||||||
|
res = self._run(client.get('/', headers={'x-auth-token': 'foo'}))
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
self.assertEqual(res.text, 'user')
|
||||||
|
|
||||||
|
@token_auth.errorhandler
|
||||||
|
def error_handler(request):
|
||||||
|
return {'status_code': 403}, 403
|
||||||
|
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 403)
|
||||||
|
self.assertEqual(res.json, {'status_code': 403})
|
||||||
185
tests/test_login.py
Normal file
185
tests/test_login.py
Normal file
@@ -0,0 +1,185 @@
|
|||||||
|
import asyncio
|
||||||
|
import unittest
|
||||||
|
from microdot import Microdot
|
||||||
|
from microdot.login import Login
|
||||||
|
from microdot.session import Session
|
||||||
|
from microdot.test_client import TestClient
|
||||||
|
|
||||||
|
|
||||||
|
class TestLogin(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
if hasattr(asyncio, 'set_event_loop'):
|
||||||
|
asyncio.set_event_loop(asyncio.new_event_loop())
|
||||||
|
cls.loop = asyncio.get_event_loop()
|
||||||
|
|
||||||
|
def _run(self, coro):
|
||||||
|
return self.loop.run_until_complete(coro)
|
||||||
|
|
||||||
|
def test_login(self):
|
||||||
|
app = Microdot()
|
||||||
|
Session(app, secret_key='secret')
|
||||||
|
login = Login()
|
||||||
|
|
||||||
|
class User:
|
||||||
|
def __init__(self, id, name):
|
||||||
|
self.id = id
|
||||||
|
self.name = name
|
||||||
|
|
||||||
|
@login.id_to_user
|
||||||
|
def id_to_user(user_id):
|
||||||
|
return User(user_id, f'user{user_id}')
|
||||||
|
|
||||||
|
@app.get('/')
|
||||||
|
@login
|
||||||
|
def index(request):
|
||||||
|
return request.g.current_user.name
|
||||||
|
|
||||||
|
@app.post('/login')
|
||||||
|
async def login_route(request):
|
||||||
|
return await login.login_user(request, User(123, 'user123'))
|
||||||
|
|
||||||
|
@app.post('/logout')
|
||||||
|
async def logout_route(request):
|
||||||
|
await login.logout_user(request)
|
||||||
|
return 'ok'
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.get('/?foo=bar'))
|
||||||
|
self.assertEqual(res.status_code, 302)
|
||||||
|
self.assertEqual(res.headers['Location'], '/login?next=/%3Ffoo%3Dbar')
|
||||||
|
|
||||||
|
res = self._run(client.post('/login?next=/%3Ffoo=bar'))
|
||||||
|
self.assertEqual(res.status_code, 302)
|
||||||
|
self.assertEqual(res.headers['Location'], '/?foo=bar')
|
||||||
|
self.assertEqual(len(res.headers['Set-Cookie']), 1)
|
||||||
|
self.assertIn('session', client.cookies)
|
||||||
|
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
self.assertEqual(res.text, 'user123')
|
||||||
|
|
||||||
|
res = self._run(client.post('/logout'))
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 302)
|
||||||
|
|
||||||
|
def test_login_bad_user_id(self):
|
||||||
|
app = Microdot()
|
||||||
|
Session(app, secret_key='secret')
|
||||||
|
login = Login()
|
||||||
|
|
||||||
|
@login.id_to_user
|
||||||
|
def id_to_user(user_id):
|
||||||
|
return None
|
||||||
|
|
||||||
|
@login.user_to_id
|
||||||
|
def user_to_id(user):
|
||||||
|
return user
|
||||||
|
|
||||||
|
@app.get('/foo')
|
||||||
|
@login
|
||||||
|
async def index(request):
|
||||||
|
return 'ok'
|
||||||
|
|
||||||
|
@app.post('/login')
|
||||||
|
async def login_route(request):
|
||||||
|
return await login.login_user(request, 'user')
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.post('/login?next=/'))
|
||||||
|
self.assertEqual(res.status_code, 302)
|
||||||
|
self.assertEqual(res.headers['Location'], '/')
|
||||||
|
res = self._run(client.get('/foo'))
|
||||||
|
self.assertEqual(res.status_code, 302)
|
||||||
|
self.assertEqual(res.headers['Location'], '/login?next=/foo')
|
||||||
|
|
||||||
|
def test_login_bad_redirect(self):
|
||||||
|
app = Microdot()
|
||||||
|
Session(app, secret_key='secret')
|
||||||
|
login = Login()
|
||||||
|
|
||||||
|
@login.id_to_user
|
||||||
|
def id_to_user(user_id):
|
||||||
|
return user_id
|
||||||
|
|
||||||
|
@login.user_to_id
|
||||||
|
def user_to_id(user):
|
||||||
|
return user
|
||||||
|
|
||||||
|
@app.get('/')
|
||||||
|
@login
|
||||||
|
async def index(request):
|
||||||
|
return 'ok'
|
||||||
|
|
||||||
|
@app.post('/login')
|
||||||
|
async def login_route(request):
|
||||||
|
return await login.login_user(request, 'user')
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.post('/login?next=http://example.com'))
|
||||||
|
self.assertEqual(res.status_code, 302)
|
||||||
|
self.assertEqual(res.headers['Location'], '/')
|
||||||
|
|
||||||
|
def test_login_remember(self):
|
||||||
|
app = Microdot()
|
||||||
|
Session(app, secret_key='secret')
|
||||||
|
login = Login()
|
||||||
|
|
||||||
|
@login.id_to_user
|
||||||
|
def id_to_user(user_id):
|
||||||
|
return user_id
|
||||||
|
|
||||||
|
@login.user_to_id
|
||||||
|
def user_to_id(user):
|
||||||
|
return user
|
||||||
|
|
||||||
|
@app.get('/')
|
||||||
|
@login
|
||||||
|
def index(request):
|
||||||
|
return request.g.current_user
|
||||||
|
|
||||||
|
@app.post('/login')
|
||||||
|
async def login_route(request):
|
||||||
|
return await login.login_user(request, 'user', remember=True)
|
||||||
|
|
||||||
|
@app.post('/logout')
|
||||||
|
async def logout(request):
|
||||||
|
await login.logout_user(request)
|
||||||
|
return 'ok'
|
||||||
|
|
||||||
|
@app.get('/fresh')
|
||||||
|
@login.fresh
|
||||||
|
async def fresh(request):
|
||||||
|
return f'fresh {request.g.current_user}'
|
||||||
|
|
||||||
|
client = TestClient(app)
|
||||||
|
res = self._run(client.post('/login?next=/%3Ffoo=bar'))
|
||||||
|
self.assertEqual(res.status_code, 302)
|
||||||
|
self.assertEqual(res.headers['Location'], '/?foo=bar')
|
||||||
|
self.assertEqual(len(res.headers['Set-Cookie']), 2)
|
||||||
|
self.assertIn('session', client.cookies)
|
||||||
|
self.assertIn('_remember', client.cookies)
|
||||||
|
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
self.assertEqual(res.text, 'user')
|
||||||
|
res = self._run(client.get('/fresh'))
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
self.assertEqual(res.text, 'fresh user')
|
||||||
|
|
||||||
|
del client.cookies['session']
|
||||||
|
print(client.cookies)
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
res = self._run(client.get('/fresh'))
|
||||||
|
self.assertEqual(res.status_code, 302)
|
||||||
|
self.assertEqual(res.headers['Location'], '/login?next=/fresh')
|
||||||
|
|
||||||
|
res = self._run(client.post('/logout'))
|
||||||
|
self.assertEqual(res.status_code, 200)
|
||||||
|
self.assertFalse('_remember' in client.cookies)
|
||||||
|
|
||||||
|
res = self._run(client.get('/'))
|
||||||
|
self.assertEqual(res.status_code, 302)
|
||||||
@@ -203,7 +203,6 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
req.cookies['one'] + req.cookies['two'] + req.cookies['three'])
|
req.cookies['one'] + req.cookies['two'] + req.cookies['three'])
|
||||||
res.set_cookie('four', '4')
|
res.set_cookie('four', '4')
|
||||||
res.delete_cookie('two', path='/')
|
res.delete_cookie('two', path='/')
|
||||||
res.delete_cookie('one', path='/bad')
|
|
||||||
return res
|
return res
|
||||||
|
|
||||||
client = TestClient(app, cookies={'one': '1', 'two': '2'})
|
client = TestClient(app, cookies={'one': '1', 'two': '2'})
|
||||||
@@ -274,14 +273,6 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
return '<p>four</p>', 202, \
|
return '<p>four</p>', 202, \
|
||||||
{'Content-Type': 'text/html; charset=UTF-8'}
|
{'Content-Type': 'text/html; charset=UTF-8'}
|
||||||
|
|
||||||
@app.route('/status')
|
|
||||||
def five(req):
|
|
||||||
return 202
|
|
||||||
|
|
||||||
@app.route('/status-headers')
|
|
||||||
def six(req):
|
|
||||||
return 202, {'Content-Type': 'text/html; charset=UTF-8'}
|
|
||||||
|
|
||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
|
|
||||||
res = self._run(client.get('/body'))
|
res = self._run(client.get('/body'))
|
||||||
@@ -307,18 +298,6 @@ class TestMicrodot(unittest.TestCase):
|
|||||||
'text/html; charset=UTF-8')
|
'text/html; charset=UTF-8')
|
||||||
self.assertEqual(res.text, '<p>four</p>')
|
self.assertEqual(res.text, '<p>four</p>')
|
||||||
|
|
||||||
res = self._run(client.get('/status'))
|
|
||||||
self.assertEqual(res.text, '')
|
|
||||||
self.assertEqual(res.status_code, 202)
|
|
||||||
self.assertEqual(res.headers['Content-Type'],
|
|
||||||
'text/plain; charset=UTF-8')
|
|
||||||
|
|
||||||
res = self._run(client.get('/status-headers'))
|
|
||||||
self.assertEqual(res.text, '')
|
|
||||||
self.assertEqual(res.status_code, 202)
|
|
||||||
self.assertEqual(res.headers['Content-Type'],
|
|
||||||
'text/html; charset=UTF-8')
|
|
||||||
|
|
||||||
def test_before_after_request(self):
|
def test_before_after_request(self):
|
||||||
app = Microdot()
|
app = Microdot()
|
||||||
|
|
||||||
|
|||||||
@@ -136,10 +136,10 @@ class TestResponse(unittest.TestCase):
|
|||||||
self.assertTrue(fd.response.endswith(b'\r\n\r\nfoobar'))
|
self.assertTrue(fd.response.endswith(b'\r\n\r\nfoobar'))
|
||||||
|
|
||||||
def test_create_from_other(self):
|
def test_create_from_other(self):
|
||||||
res = Response(23.7)
|
res = Response(123)
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
self.assertEqual(res.headers, {})
|
self.assertEqual(res.headers, {})
|
||||||
self.assertEqual(res.body, 23.7)
|
self.assertEqual(res.body, 123)
|
||||||
|
|
||||||
def test_create_with_status_code(self):
|
def test_create_with_status_code(self):
|
||||||
res = Response('not found', 404)
|
res = Response('not found', 404)
|
||||||
@@ -193,7 +193,6 @@ class TestResponse(unittest.TestCase):
|
|||||||
expires='Tue, 05 Nov 2019 02:23:54 GMT', max_age=123,
|
expires='Tue, 05 Nov 2019 02:23:54 GMT', max_age=123,
|
||||||
secure=True, http_only=True)
|
secure=True, http_only=True)
|
||||||
res.delete_cookie('foo8', http_only=True)
|
res.delete_cookie('foo8', http_only=True)
|
||||||
res.delete_cookie('foo9', path='/s')
|
|
||||||
self.assertEqual(res.headers, {'Set-Cookie': [
|
self.assertEqual(res.headers, {'Set-Cookie': [
|
||||||
'foo1=bar1',
|
'foo1=bar1',
|
||||||
'foo2=bar2; Path=/; Partitioned',
|
'foo2=bar2; Path=/; Partitioned',
|
||||||
@@ -206,8 +205,6 @@ class TestResponse(unittest.TestCase):
|
|||||||
'HttpOnly',
|
'HttpOnly',
|
||||||
('foo8=; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Max-Age=0; '
|
('foo8=; Expires=Thu, 01 Jan 1970 00:00:01 GMT; Max-Age=0; '
|
||||||
'HttpOnly'),
|
'HttpOnly'),
|
||||||
('foo9=; Path=/s; Expires=Thu, 01 Jan 1970 00:00:01 GMT; '
|
|
||||||
'Max-Age=0'),
|
|
||||||
]})
|
]})
|
||||||
|
|
||||||
def test_redirect(self):
|
def test_redirect(self):
|
||||||
@@ -280,17 +277,6 @@ class TestResponse(unittest.TestCase):
|
|||||||
'application/octet-stream')
|
'application/octet-stream')
|
||||||
self.assertEqual(res.headers['Content-Encoding'], 'gzip')
|
self.assertEqual(res.headers['Content-Encoding'], 'gzip')
|
||||||
|
|
||||||
def test_send_file_gzip_handling(self):
|
|
||||||
res = Response.send_file('tests/files/test.txt.gz')
|
|
||||||
self.assertEqual(res.status_code, 200)
|
|
||||||
self.assertEqual(res.headers['Content-Type'],
|
|
||||||
'application/octet-stream')
|
|
||||||
|
|
||||||
res = Response.send_file('tests/files/test.txt.gz', compressed=True)
|
|
||||||
self.assertEqual(res.status_code, 200)
|
|
||||||
self.assertEqual(res.headers['Content-Type'], 'text/plain')
|
|
||||||
self.assertEqual(res.headers['Content-Encoding'], 'gzip')
|
|
||||||
|
|
||||||
def test_default_content_type(self):
|
def test_default_content_type(self):
|
||||||
original_content_type = Response.default_content_type
|
original_content_type = Response.default_content_type
|
||||||
res = Response('foo')
|
res = Response('foo')
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ class TestSession(unittest.TestCase):
|
|||||||
|
|
||||||
@app.post('/set')
|
@app.post('/set')
|
||||||
@with_session
|
@with_session
|
||||||
async def save_session(req, session):
|
def save_session(req, session):
|
||||||
session['name'] = 'joe'
|
session['name'] = 'joe'
|
||||||
session.save()
|
session.save()
|
||||||
return 'OK'
|
return 'OK'
|
||||||
@@ -82,77 +82,3 @@ class TestSession(unittest.TestCase):
|
|||||||
|
|
||||||
res = self._run(client.get('/'))
|
res = self._run(client.get('/'))
|
||||||
self.assertEqual(res.status_code, 200)
|
self.assertEqual(res.status_code, 200)
|
||||||
|
|
||||||
def test_session_default_path(self):
|
|
||||||
app = Microdot()
|
|
||||||
Session(app, secret_key='some-other-secret')
|
|
||||||
client = TestClient(app)
|
|
||||||
|
|
||||||
@app.get('/')
|
|
||||||
@with_session
|
|
||||||
def index(req, session):
|
|
||||||
session['foo'] = 'bar'
|
|
||||||
session.save()
|
|
||||||
return ''
|
|
||||||
|
|
||||||
@app.get('/child')
|
|
||||||
@with_session
|
|
||||||
def child(req, session):
|
|
||||||
return str(session.get('foo'))
|
|
||||||
|
|
||||||
@app.get('/delete')
|
|
||||||
@with_session
|
|
||||||
def delete(req, session):
|
|
||||||
session.delete()
|
|
||||||
return ''
|
|
||||||
|
|
||||||
res = self._run(client.get('/'))
|
|
||||||
self.assertEqual(res.status_code, 200)
|
|
||||||
res = self._run(client.get('/child'))
|
|
||||||
self.assertEqual(res.text, 'bar')
|
|
||||||
res = self._run(client.get('/delete'))
|
|
||||||
res = self._run(client.get('/child'))
|
|
||||||
self.assertEqual(res.text, 'None')
|
|
||||||
|
|
||||||
def test_session_custom_path(self):
|
|
||||||
app = Microdot()
|
|
||||||
session_ext = Session()
|
|
||||||
session_ext.initialize(app, secret_key='some-other-secret',
|
|
||||||
cookie_options={'path': '/child',
|
|
||||||
'http_only': False})
|
|
||||||
client = TestClient(app)
|
|
||||||
|
|
||||||
@app.get('/')
|
|
||||||
@with_session
|
|
||||||
def index(req, session):
|
|
||||||
return str(session.get('foo'))
|
|
||||||
|
|
||||||
@app.get('/child')
|
|
||||||
@with_session
|
|
||||||
def child(req, session):
|
|
||||||
session['foo'] = 'bar'
|
|
||||||
session.save()
|
|
||||||
return ''
|
|
||||||
|
|
||||||
@app.get('/child/foo')
|
|
||||||
@with_session
|
|
||||||
def foo(req, session):
|
|
||||||
return str(session.get('foo'))
|
|
||||||
|
|
||||||
@app.get('/child/delete')
|
|
||||||
@with_session
|
|
||||||
def delete(req, session):
|
|
||||||
session.delete()
|
|
||||||
return ''
|
|
||||||
|
|
||||||
res = self._run(client.get('/child'))
|
|
||||||
self.assertEqual(res.status_code, 200)
|
|
||||||
res = self._run(client.get('/'))
|
|
||||||
self.assertEqual(res.text, 'None')
|
|
||||||
res = self._run(client.get('/child/foo'))
|
|
||||||
self.assertEqual(res.text, 'bar')
|
|
||||||
res = self._run(client.get('/child/delete'))
|
|
||||||
res = self._run(client.get('/'))
|
|
||||||
self.assertEqual(res.text, 'None')
|
|
||||||
res = self._run(client.get('/child/foo'))
|
|
||||||
self.assertEqual(res.text, 'None')
|
|
||||||
|
|||||||
Reference in New Issue
Block a user