Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for Middlewares #41

Closed
tonychengchime opened this issue May 20, 2022 · 3 comments
Closed

Support for Middlewares #41

tonychengchime opened this issue May 20, 2022 · 3 comments

Comments

@tonychengchime
Copy link

tonychengchime commented May 20, 2022

Hi, does Twirpy support Middlewares like Starlette? I'm trying to implement an auth layer and would like to do it in a Middleware.

I did not see in the documentation or code where to specify them.

Thanks

@ofpiyush
Copy link
Contributor

Hi @tonychengchime, thanks for reaching out.

Yes! Twirp has support for both "middlewares" and hooks. They're nothing like the ones you see in Starlette though. And for your use case, they're not ideal.

For more nuanced use cases, twirp has the concept of hooks.
This is how it looks like in go: https://pkg.go.dev/github.com/twitchtv/twirp#ServerHooks

Equivalent implementation in python. https://github.com/verloop/twirpy/blob/0.0.7/twirp/hook.py

You can pass a hook with the kwarg like so, TwirpAsgiApp(hook=MyHook).

Since you want to do auth, you can use request_received or request_routed hook. Both of them run before the request body is read at all.

You can raise a TwirpServerException with Unauthenticated or PermissionDenied code from within your hook.

I can post a more complete example tomorrow if that'll help.

@tonychengchime
Copy link
Author

Hi Piyush, that was very helpful. I got what I need so I will close this ticket. Thanks

@ofpiyush
Copy link
Contributor

ofpiyush commented May 22, 2022

Today I got some time to check starlette's middlewares again.

@tonychengchime check the "Using middleware in other frameworks" section on https://www.starlette.io/middleware/

Twirpy is a standard ASGI app, so it should work for youad well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants