| 1 |
from enum import Enum |
| 2 |
from os import environ |
| 3 |
|
| 4 |
from pydantic import UUID4, BaseModel |
| 5 |
|
| 6 |
from litestar import Controller, Litestar, Router, get, post |
| 7 |
from litestar.connection import ASGIConnection |
| 8 |
from litestar.exceptions import PermissionDeniedException |
| 9 |
from litestar.handlers.base import BaseRouteHandler |
| 10 |
|
| 11 |
|
| 12 |
class UserRole(str, Enum): |
| 13 |
CONSUMER = "consumer" |
| 14 |
ADMIN = "admin" |
| 15 |
|
| 16 |
|
| 17 |
class User(BaseModel): |
| 18 |
id: UUID4 |
| 19 |
role: UserRole |
| 20 |
|
| 21 |
@property |
| 22 |
def is_admin(self) -> bool: |
| 23 |
"""Determines whether the user is an admin user""" |
| 24 |
return self.role == UserRole.ADMIN |
| 25 |
|
| 26 |
|
| 27 |
def admin_user_guard(connection: ASGIConnection, _: BaseRouteHandler) -> None: |
| 28 |
if not connection.user.is_admin: |
| 29 |
raise PermissionDeniedException() |
| 30 |
|
| 31 |
|
| 32 |
@post(path="/user", guards=[admin_user_guard]) |
| 33 |
def create_user(data: User) -> User: ... |
| 34 |
|
| 35 |
|
| 36 |
def my_guard(connection: ASGIConnection, handler: BaseRouteHandler) -> None: ... |
| 37 |
|
| 38 |
|
| 39 |
# controller |
| 40 |
class UserController(Controller): |
| 41 |
path = "/user" |
| 42 |
guards = [my_guard] |
| 43 |
|
| 44 |
|
| 45 |
# router |
| 46 |
admin_router = Router(path="admin", route_handlers=[UserController], guards=[my_guard]) |
| 47 |
|
| 48 |
# app |
| 49 |
app = Litestar(route_handlers=[admin_router], guards=[my_guard]) |
| 50 |
|
| 51 |
|
| 52 |
def secret_token_guard(connection: ASGIConnection, route_handler: BaseRouteHandler) -> None: |
| 53 |
if ( |
| 54 |
route_handler.opt.get("secret") |
| 55 |
and not connection.headers.get("Secret-Header", "") == route_handler.opt["secret"] |
| 56 |
): |
| 57 |
raise PermissionDeniedException() |
| 58 |
|
| 59 |
|
| 60 |
@get(path="/secret", guards=[secret_token_guard], opt={"secret": environ.get("SECRET")}) |
| 61 |
def secret_endpoint() -> None: ... |