| 1 |
import dataclasses |
| 2 |
|
| 3 |
from typing_extensions import Annotated |
| 4 |
|
| 5 |
from litestar import Litestar, get |
| 6 |
from litestar.exceptions import NotAuthorizedException |
| 7 |
from litestar.params import CookieParameter, FromPath, HeaderParameter |
| 8 |
|
| 9 |
VALID_TOKEN = "super-secret-secret" |
| 10 |
VALID_COOKIE_VALUE = "cookie-secret" |
| 11 |
|
| 12 |
|
| 13 |
@dataclasses.dataclass |
| 14 |
class User: |
| 15 |
id: int |
| 16 |
name: str |
| 17 |
|
| 18 |
|
| 19 |
USER_DB = { |
| 20 |
1: User(id=1, name="John Doe"), |
| 21 |
} |
| 22 |
|
| 23 |
|
| 24 |
@get(path="/users/{user_id:int}/") |
| 25 |
async def get_user( |
| 26 |
user_id: FromPath[int], |
| 27 |
token: Annotated[str, HeaderParameter(name="X-API-KEY")], |
| 28 |
cookie: Annotated[str, CookieParameter(name="my-cookie-param")], |
| 29 |
) -> User: |
| 30 |
if token != VALID_TOKEN or cookie != VALID_COOKIE_VALUE: |
| 31 |
raise NotAuthorizedException |
| 32 |
return USER_DB[user_id] |
| 33 |
|
| 34 |
|
| 35 |
app = Litestar(route_handlers=[get_user]) |