Skip to content

Commit

Permalink
Initial draft of Yesod middleware enforcing CSRF protection
Browse files Browse the repository at this point in the history
  • Loading branch information
MaxGabriel committed Jul 1, 2015
1 parent 29e07bc commit 46421a3
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions yesod-core/Yesod/Core/Class/Yesod.hs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import Yesod.Core.Types
import Yesod.Core.Internal.Session
import Yesod.Core.Widget
import Control.Monad.Trans.Class (lift)
import Data.CaseInsensitive (CI)

-- | Define settings for a Yesod applications. All methods have intelligent
-- defaults, and therefore no implementation is required.
Expand Down Expand Up @@ -411,6 +412,30 @@ authorizationCheck = do
void $ notAuthenticated
Unauthorized s' -> permissionDenied s'

-- | Calls 'csrfCheckMiddleware' with 'isWriteRequest' and 'defaultCsrfHeaderName' as parameters.
--
-- Since 1.4.12
defaultCsrfCheckMiddleware :: Yesod site => HandlerT site IO ()
defaultCsrfCheckMiddleware = do
csrfCheckMiddleware
(getCurrentRoute >>= maybe (return False) isWriteRequest)
defaultCsrfHeaderName

-- | Looks up the CSRF token from the request headers. If the value doesn't match the token stored in the session,
-- this function throws a 'PermissionDenied' error.
--
-- For details, see the "AJAX CSRF protection" section of 'Yesod.Core.Handler'.
--
-- Since 1.4.12
csrfCheckMiddleware :: Yesod site
=> HandlerT site IO Bool -- ^ Whether or not to perform the CSRF check.
-> CI S8.ByteString -- ^ The header name to lookup the CSRF token from.
-> HandlerT site IO ()
csrfCheckMiddleware shouldCheckFn headerName = do
shouldCheck <- shouldCheckFn
when shouldCheck (checkCsrfHeaderNamed headerName)


-- | Convert a widget to a 'PageContent'.
widgetToPageContent :: (Eq (Route site), Yesod site)
=> WidgetT site IO ()
Expand Down

0 comments on commit 46421a3

Please sign in to comment.