|
| 1 | +from casbin.enforcer import Enforcer |
| 2 | +from starlette.authentication import BaseUser |
| 3 | +from starlette.requests import Request |
| 4 | +from starlette.responses import JSONResponse |
| 5 | +from starlette.status import HTTP_403_FORBIDDEN |
| 6 | +from starlette.types import ASGIApp, Receive, Scope, Send |
| 7 | + |
| 8 | + |
| 9 | +class CasbinMiddleware: |
| 10 | + """ |
| 11 | + Middleware for Casbin |
| 12 | + """ |
| 13 | + |
| 14 | + def __init__( |
| 15 | + self, |
| 16 | + app: ASGIApp, |
| 17 | + enforcer: Enforcer, |
| 18 | + ) -> None: |
| 19 | + """ |
| 20 | + Configure Casbin Middleware |
| 21 | +
|
| 22 | + :param app:Retain for ASGI. |
| 23 | + :param enforcer:Casbin Enforcer, must be initialized before FastAPI start. |
| 24 | + """ |
| 25 | + self.app = app |
| 26 | + self.enforcer = enforcer |
| 27 | + |
| 28 | + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: |
| 29 | + if scope["type"] not in ("http", "websocket"): |
| 30 | + await self.app(scope, receive, send) |
| 31 | + return |
| 32 | + |
| 33 | + if self._enforce(scope, receive): |
| 34 | + await self.app(scope, receive, send) |
| 35 | + return |
| 36 | + else: |
| 37 | + response = JSONResponse( |
| 38 | + status_code=HTTP_403_FORBIDDEN, |
| 39 | + content="Forbidden" |
| 40 | + ) |
| 41 | + |
| 42 | + await response(scope, receive, send) |
| 43 | + return |
| 44 | + |
| 45 | + def _enforce(self, scope: Scope, receive: Receive) -> bool: |
| 46 | + """ |
| 47 | + Enforce a request |
| 48 | +
|
| 49 | + :param user: user will be sent to enforcer |
| 50 | + :param request: ASGI Request |
| 51 | + :return: Enforce Result |
| 52 | + """ |
| 53 | + |
| 54 | + request = Request(scope, receive) |
| 55 | + |
| 56 | + path = request.url.path |
| 57 | + method = request.method |
| 58 | + if 'user' not in scope: |
| 59 | + raise RuntimeError("Casbin Middleware must work with an Authentication Middleware") |
| 60 | + |
| 61 | + assert isinstance(request.user, BaseUser) |
| 62 | + |
| 63 | + user = request.user.display_name if request.user.is_authenticated else 'anonymous' |
| 64 | + |
| 65 | + print(user, path, method) |
| 66 | + |
| 67 | + return self.enforcer.enforce(user, path, method) |
0 commit comments