Search code examples
haskellyesodmonad-transformers

Adding a monad transformer to the Yesod Handler stack


How do I add another monad transformer to the Yesod Handler stack?

Specifically, I would like to add CRandT from Control.Monad.CryptoRandom so that I can generate secure random numbers for things like sessions ids and cipher keys.

If I do manage to add this to the stack, will it be shared among calls to the web server or will a new one be generated for each connection? The reason I care is that the latter will use up entropy used to initialize the generator, while the former will keep using the same generator once it is initialized.

Or maybe I'm way off base and completely don't understand monad transformer stacks.


Solution

  • @bheklilr's idea is definitely an approach you can take. Generally speaking, you can't insert transformers underneath HandlerT in Yesod, since the framework wouldn't know how to unwrap it.

    There does appear to be another approach: you could keep a random number generator in something like an IORef in your foundation datatype, and then define a MonadCRandom instance for your specific HandlerT App IO monad. I don't have any experience with MonadCRandom, so I can't offer an immediate demonstration on how to do it, but I think it shouldn't be too difficult. You could probably base the implementation around the MonadCRandom instance for CRandT.