aminalaee / sqladmin

SQLAlchemy Admin for FastAPI and Starlette
https://aminalaee.dev/sqladmin/
BSD 3-Clause "New" or "Revised" License
1.9k stars 189 forks source link

SessionMiddleware for auth #849

Open xodiumx opened 6 days ago

xodiumx commented 6 days ago

Checklist

Is your feature related to a problem? Please describe.

Hi, was working on a task and ran into an issue where my application initializes two sessions.

AuthenticationBackend class creates its own session in the init method:

class AuthenticationBackend:
    """Base class for implementing the Authentication into SQLAdmin.
    You need to inherit this class and override the methods:
    `login`, `logout` and `authenticate`.
    """

    def __init__(self, secret_key: str) -> None:
        from starlette.middleware.sessions import SessionMiddleware

        self.middlewares = [
            Middleware(SessionMiddleware, secret_key=secret_key),
        ]

But if I need a session also in my application I initialize, when starting the app

fastapi_app = FastAPI()
fastapi_app.add_middleware(SessionMiddleware, secret_key="some")

and then I can't use session object from AuthBackend

Describe the solution you would like.

I think it would be more transparent to pass this middleware to the AuthenticationBackend, for example like this:

# or middlewares: list[Middleware]
def __init__(self, session_middleware: Middleware) -> None:
    self.middlewares = [
        session_middleware,
    ]

and initialize this middleware on application startup:

session = Middleware(SessionMiddleware, secret_key="some-key")
fastapi_app = FastAPI(middleware=[session,])
admin = Admin(
    authentication_backend=AdminAuthBackend(session_middleware=session),
)

I hope this helps someone spend less time looking for the problem than it took me to find it 🥲

aminalaee commented 1 day ago

I think you can subclass AuthenticationBackend to modify this. But adding middlewares to the init is also fine by me. We just have to make it optional and initialize it when no argument is passed.

aminalaee commented 1 day ago

Feel free to create a PR for it.