| 1 |
from typing import Any, Dict, Literal, Optional |
| 2 |
from uuid import UUID, uuid4 |
| 3 |
|
| 4 |
from pydantic import BaseModel, EmailStr, SecretStr |
| 5 |
|
| 6 |
from litestar import Litestar, Request, get, post |
| 7 |
from litestar.connection import ASGIConnection |
| 8 |
from litestar.exceptions import NotAuthorizedException |
| 9 |
from litestar.middleware.session.server_side import ServerSideSessionBackend, ServerSideSessionConfig |
| 10 |
from litestar.openapi.config import OpenAPIConfig |
| 11 |
from litestar.security.session_auth import SessionAuth |
| 12 |
from litestar.stores.memory import MemoryStore |
| 13 |
|
| 14 |
|
| 15 |
# Let's assume we have a User model that is a pydantic model. |
| 16 |
# This though is not required - we need some sort of user class - |
| 17 |
# but it can be any arbitrary value, e.g. an SQLAlchemy model, |
| 18 |
# a representation of a MongoDB etc. |
| 19 |
class User(BaseModel): |
| 20 |
id: UUID |
| 21 |
name: str |
| 22 |
email: EmailStr |
| 23 |
|
| 24 |
|
| 25 |
# we also have pydantic types for two different |
| 26 |
# kinds of POST request bodies: one for creating |
| 27 |
# a user, e.g. "sign-up", and the other for logging |
| 28 |
# an existing user in. |
| 29 |
class UserCreatePayload(BaseModel): |
| 30 |
name: str |
| 31 |
email: EmailStr |
| 32 |
password: SecretStr |
| 33 |
|
| 34 |
|
| 35 |
class UserLoginPayload(BaseModel): |
| 36 |
email: EmailStr |
| 37 |
password: SecretStr |
| 38 |
|
| 39 |
|
| 40 |
MOCK_DB: Dict[str, User] = {} |
| 41 |
memory_store = MemoryStore() |
| 42 |
|
| 43 |
|
| 44 |
# The SessionAuth class requires a handler callable |
| 45 |
# that takes the session dictionary, and returns the |
| 46 |
# 'User' instance correlating to it. |
| 47 |
# |
| 48 |
# The session dictionary itself is a value the user decides |
| 49 |
# upon. So for example, it might be a simple dictionary |
| 50 |
# that holds a user id, for example: { "id": "abcd123" } |
| 51 |
# |
| 52 |
# Note: The callable can be either sync or async - both will work. |
| 53 |
async def retrieve_user_handler( |
| 54 |
session: Dict[str, Any], connection: "ASGIConnection[Any, Any, Any, Any]" |
| 55 |
) -> Optional[User]: |
| 56 |
return MOCK_DB.get(user_id) if (user_id := session.get("user_id")) else None |
| 57 |
|
| 58 |
|
| 59 |
@post("/login") |
| 60 |
async def login(data: UserLoginPayload, request: "Request[Any, Any, Any]") -> User: |
| 61 |
# we received log-in data via post. |
| 62 |
# our login handler should retrieve from persistence (a db etc.) |
| 63 |
# the user data and verify that the login details |
| 64 |
# are correct. If we are using passwords, we should check that |
| 65 |
# the password hashes match etc. We will simply assume that we |
| 66 |
# have done all of that we now have a user value: |
| 67 |
user_id = await memory_store.get(data.email) |
| 68 |
|
| 69 |
if not user_id: |
| 70 |
raise NotAuthorizedException |
| 71 |
user_id = user_id.decode("utf-8") |
| 72 |
|
| 73 |
# once verified we can create a session. |
| 74 |
# to do this we simply need to call the Litestar |
| 75 |
# 'Request.set_session' method, which accepts either dictionaries |
| 76 |
# or pydantic models. In our case, we can simply record a |
| 77 |
# simple dictionary with the user ID value: |
| 78 |
request.set_session({"user_id": user_id}) |
| 79 |
|
| 80 |
# you can do whatever we want here. In this case, we will simply return the user data: |
| 81 |
return MOCK_DB[user_id] |
| 82 |
|
| 83 |
|
| 84 |
@post("/signup") |
| 85 |
async def signup(data: UserCreatePayload, request: Request[Any, Any, Any]) -> User: |
| 86 |
# this is similar to the login handler, except here we should |
| 87 |
# insert into persistence - after doing whatever extra |
| 88 |
# validation we might require. We will assume that this is done, |
| 89 |
# and we now have a user instance with an assigned ID value: |
| 90 |
user = User(name=data.name, email=data.email, id=uuid4()) |
| 91 |
|
| 92 |
await memory_store.set(data.email, str(user.id)) |
| 93 |
MOCK_DB[str(user.id)] = user |
| 94 |
# we are creating a session the same as we do in the |
| 95 |
# 'login_handler' above: |
| 96 |
request.set_session({"user_id": str(user.id)}) |
| 97 |
|
| 98 |
# and again, you can add whatever logic is required here, we |
| 99 |
# will simply return the user: |
| 100 |
return user |
| 101 |
|
| 102 |
|
| 103 |
# the endpoint below requires the user to be already authenticated |
| 104 |
# to be able to access it. |
| 105 |
@get("/user", sync_to_thread=False) |
| 106 |
def get_user(request: Request[User, Dict[Literal["user_id"], str], Any]) -> Any: |
| 107 |
# because this route requires authentication, we can access |
| 108 |
# `request.user`, which is the authenticated user returned |
| 109 |
# by the 'retrieve_user_handler' function we passed to SessionAuth. |
| 110 |
return request.user |
| 111 |
|
| 112 |
|
| 113 |
# We add the session security schema to the OpenAPI config. |
| 114 |
openapi_config = OpenAPIConfig( |
| 115 |
title="My API", |
| 116 |
version="1.0.0", |
| 117 |
) |
| 118 |
|
| 119 |
session_auth = SessionAuth[User, ServerSideSessionBackend]( |
| 120 |
retrieve_user_handler=retrieve_user_handler, |
| 121 |
# we must pass a config for a session backend. |
| 122 |
# all session backends are supported |
| 123 |
session_backend_config=ServerSideSessionConfig(), |
| 124 |
# exclude any URLs that should not have authentication. |
| 125 |
# We exclude the documentation URLs, signup and login. |
| 126 |
exclude=["/login", "/signup", "/schema"], |
| 127 |
) |
| 128 |
|
| 129 |
|
| 130 |
# We initialize the app instance, passing to it the 'session_auth.on_app_init' and the 'openapi_config'. |
| 131 |
app = Litestar( |
| 132 |
route_handlers=[login, signup, get_user], |
| 133 |
on_app_init=[session_auth.on_app_init], |
| 134 |
openapi_config=openapi_config, |
| 135 |
) |