Yesod Non-AJAX HTML Form CSRF Token

145 Views Asked by At

I just turned on CSRF protection middleware in Yesod.

My jQuery AJAX calls are working, with the CSRF token being added into the header as per the normal scaffold.

Now I have a normal HTML "POST" form, not generated by Yesod. I want to include the CSRF protection token as a hidden input.

So far I have this in my ExampleHandler.hs

            mcsrftoken <- fmap reqToken getRequest                                                                                                                  
            let csrftoken = case mcsrftoken of                                                                                                                      
                                Nothing -> "NO_TOKEN"                                                                                                               
                                Just t  -> t            

(Thanks to the Snoymaster at Yesod 1.2 CSRF protection)

And in example.hamlet:

  <form method="post" action="@{ExampleR someId}">
   <input name="_token" type="text" value=#{csrftoken}>

This one form works.

I have a lot of handlers, so I do not want to paste the code (or a function) in every one, to retrieve the token. I also do not want to convert all my HTML forms into AJAX.

I tried to paste the above token retrieving snippet into Foundation.hs, to get the token everywhere, but then I get:

 Variable not in scope: csrftoken

On the line in the handler where the example.hamlet is pulled in.

How can I make get the csrftoken variable in scope in all handlers?

Is there a better way to get the CSRF token into the non-generated HTML forms?

Thank you haskellers and Yesod fans

0

There are 0 best solutions below